当前位置:   article > 正文

《PyTorch深度学习实践》第十一讲卷积神经网络进阶

《PyTorch深度学习实践》第十一讲卷积神经网络进阶

一、

1、卷积核超参数选择困难,自动找到卷积的最佳组合。

2、1x1卷积核,不同通道的信息融合。使用1x1卷积核虽然参数量增加了,但是能够显著的降低计算量(operations)

3、Inception Moudel由4个分支组成,要分清哪些是在Init里定义,哪些是在forward里调用。4个分支在dim=1(channels)上进行concatenate。24+16+24+24 = 88
4、最大池化层只改变宽、高;padding为增加输入的宽、高,使卷积后宽、高不变

二、

  1. import torch
  2. import torch.nn as nn
  3. from torchvision import transforms
  4. from torchvision import datasets
  5. from torch.utils.data import DataLoader
  6. import torch.nn.functional as F
  7. import torch.optim as optim
  8. # prepare dataset
  9. batch_size = 64
  10. transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) # 归一化,均值和方差
  11. train_dataset = datasets.MNIST(root='../dataset/mnist/', train=True, download=True, transform=transform)
  12. train_loader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size)
  13. test_dataset = datasets.MNIST(root='../dataset/mnist/', train=False, download=True, transform=transform)
  14. test_loader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size)
  15. # design model using class
  16. class InceptionA(nn.Module):
  17. def __init__(self, in_channels):
  18. super(InceptionA, self).__init__()
  19. self.branch1x1 = nn.Conv2d(in_channels, 16, kernel_size=1)
  20. self.branch5x5_1 = nn.Conv2d(in_channels, 16, kernel_size=1)
  21. self.branch5x5_2 = nn.Conv2d(16, 24, kernel_size=5, padding=2)
  22. self.branch3x3_1 = nn.Conv2d(in_channels, 16, kernel_size=1)
  23. self.branch3x3_2 = nn.Conv2d(16, 24, kernel_size=3, padding=1)
  24. self.branch3x3_3 = nn.Conv2d(24, 24, kernel_size=3, padding=1)
  25. self.branch_pool = nn.Conv2d(in_channels, 24, kernel_size=1)
  26. def forward(self, x):
  27. branch1x1 = self.branch1x1(x)
  28. branch5x5 = self.branch5x5_1(x)
  29. branch5x5 = self.branch5x5_2(branch5x5)
  30. branch3x3 = self.branch3x3_1(x)
  31. branch3x3 = self.branch3x3_2(branch3x3)
  32. branch3x3 = self.branch3x3_3(branch3x3)
  33. branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
  34. branch_pool = self.branch_pool(branch_pool)
  35. outputs = [branch1x1, branch5x5, branch3x3, branch_pool]
  36. return torch.cat(outputs, dim=1) # b,c,w,h c对应的是dim=1
  37. class Net(nn.Module):
  38. def __init__(self):
  39. super(Net, self).__init__()
  40. self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
  41. self.conv2 = nn.Conv2d(88, 20, kernel_size=5) # 88 = 24x3 + 16
  42. self.incep1 = InceptionA(in_channels=10) # 与conv1 中的10对应
  43. self.incep2 = InceptionA(in_channels=20) # 与conv2 中的20对应
  44. self.mp = nn.MaxPool2d(2)
  45. self.fc = nn.Linear(1408, 10)
  46. def forward(self, x):
  47. in_size = x.size(0)
  48. x = F.relu(self.mp(self.conv1(x)))
  49. x = self.incep1(x)
  50. x = F.relu(self.mp(self.conv2(x)))
  51. x = self.incep2(x)
  52. x = x.view(in_size, -1)
  53. x = self.fc(x)
  54. return x
  55. model = Net()
  56. # construct loss and optimizer
  57. criterion = torch.nn.CrossEntropyLoss()
  58. optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
  59. # training cycle forward, backward, update
  60. def train(epoch):
  61. running_loss = 0.0
  62. for batch_idx, data in enumerate(train_loader, 0):
  63. inputs, target = data
  64. optimizer.zero_grad()
  65. outputs = model(inputs)
  66. loss = criterion(outputs, target)
  67. loss.backward()
  68. optimizer.step()
  69. running_loss += loss.item()
  70. if batch_idx % 300 == 299:
  71. print('[%d, %5d] loss: %.3f' % (epoch+1, batch_idx+1, running_loss/300))
  72. running_loss = 0.0
  73. def test():
  74. correct = 0
  75. total = 0
  76. with torch.no_grad():
  77. for data in test_loader:
  78. images, labels = data
  79. outputs = model(images)
  80. _, predicted = torch.max(outputs.data, dim=1)
  81. total += labels.size(0)
  82. correct += (predicted == labels).sum().item()
  83. print('accuracy on test set: %d %% ' % (100*correct/total))
  84. if __name__ == '__main__':
  85. for epoch in range(10):
  86. train(epoch)
  87. test()

1、先使用类对Inception Moudel进行封装

2、先是1个卷积层(conv,maxpooling,relu),然后inceptionA模块(输出的channels是24+16+24+24=88),接下来又是一个卷积层(conv,mp,relu),然后inceptionA模块,最后一个全连接层(fc)。

3、1408这个数据可以通过x = x.view(in_size, -1)后调用x.shape得到。

三、

1、梯度消失问题,用ResNet解决

2、跳连接,H(x) = F(x) + x,张量维度必须一样,加完后再激活。不要做pooling,张量的维度会发生变化。

代码说明:

先是1个卷积层(conv,maxpooling,relu),然后ResidualBlock模块,接下来又是一个卷积层(conv,mp,relu),然后esidualBlock模块模块,最后一个全连接层(fc)。

  1. import torch
  2. import torch.nn as nn
  3. from torchvision import transforms
  4. from torchvision import datasets
  5. from torch.utils.data import DataLoader
  6. import torch.nn.functional as F
  7. import torch.optim as optim
  8. # prepare dataset
  9. batch_size = 64
  10. transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) # 归一化,均值和方差
  11. train_dataset = datasets.MNIST(root='../dataset/mnist/', train=True, download=True, transform=transform)
  12. train_loader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size)
  13. test_dataset = datasets.MNIST(root='../dataset/mnist/', train=False, download=True, transform=transform)
  14. test_loader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size)
  15. # design model using class
  16. class ResidualBlock(nn.Module):
  17. def __init__(self, channels):
  18. super(ResidualBlock, self).__init__()
  19. self.channels = channels
  20. self.conv1 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)
  21. self.conv2 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)
  22. def forward(self, x):
  23. y = F.relu(self.conv1(x))
  24. y = self.conv2(y)
  25. return F.relu(x + y)
  26. class Net(nn.Module):
  27. def __init__(self):
  28. super(Net, self).__init__()
  29. self.conv1 = nn.Conv2d(1, 16, kernel_size=5)
  30. self.conv2 = nn.Conv2d(16, 32, kernel_size=5) # 88 = 24x3 + 16
  31. self.rblock1 = ResidualBlock(16)
  32. self.rblock2 = ResidualBlock(32)
  33. self.mp = nn.MaxPool2d(2)
  34. self.fc = nn.Linear(512, 10) # 暂时不知道1408咋能自动出来的
  35. def forward(self, x):
  36. in_size = x.size(0)
  37. x = self.mp(F.relu(self.conv1(x)))
  38. x = self.rblock1(x)
  39. x = self.mp(F.relu(self.conv2(x)))
  40. x = self.rblock2(x)
  41. x = x.view(in_size, -1)
  42. x = self.fc(x)
  43. return x
  44. model = Net()
  45. # construct loss and optimizer
  46. criterion = torch.nn.CrossEntropyLoss()
  47. optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
  48. # training cycle forward, backward, update
  49. def train(epoch):
  50. running_loss = 0.0
  51. for batch_idx, data in enumerate(train_loader, 0):
  52. inputs, target = data
  53. optimizer.zero_grad()
  54. outputs = model(inputs)
  55. loss = criterion(outputs, target)
  56. loss.backward()
  57. optimizer.step()
  58. running_loss += loss.item()
  59. if batch_idx % 300 == 299:
  60. print('[%d, %5d] loss: %.3f' % (epoch+1, batch_idx+1, running_loss/300))
  61. running_loss = 0.0
  62. def test():
  63. correct = 0
  64. total = 0
  65. with torch.no_grad():
  66. for data in test_loader:
  67. images, labels = data
  68. outputs = model(images)
  69. _, predicted = torch.max(outputs.data, dim=1)
  70. total += labels.size(0)
  71. correct += (predicted == labels).sum().item()
  72. print('accuracy on test set: %d %% ' % (100*correct/total))
  73. if __name__ == '__main__':
  74. for epoch in range(10):
  75. train(epoch)
  76. test()

运行结果:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/195428
推荐阅读
相关标签
  

闽ICP备14008679号