视频:https://www.bilibili.com/video/BV1Y7411d7Ys?p=11
博客

主要内容:各种CNN优化模型

语雀内容

GoogLeNet

GoogLeNet:14年ImageNet分类第一名。引入Inception模块,采用不同大小的卷积核意味着不同大小的感受野,最后拼接意味着不同尺度特征的融合;采用了average pooling来代替全连接层;避免梯度消失,网络额外增加了2个辅助的softmax用于向前传导梯度。

image.png

说明:Inception Moudel

  1. 卷积核超参数选择困难,自动**找到卷积的最佳组合,相应的权重大。**
  2. Concatenate:把张量拼接在一块,但要保证宽度和高度是一致的(average pooling宽高一致)
  3. 1x1卷积核减少计算量,不同通道的信息融合。数量取决于输入张量的通道
    1. 卷积过程:各通道卷积再求和叠加为一个通道(cxwxh —> 1xwxh)
    2. 卷积后的每个通道信息包含了卷积前的各通道信息(融合)
    3. 多少个卷积核,卷积后多少个通道

image.pngimage.png

image.png

Inception Moudel代码说明

下图中,括号是输出channel
image.png

拼接在一起cat

沿着通道的维度拼接在一起 dim=1

  1. outputs = [branch1x1, branch5x5, branch3x3, branch_pool]
  2. return torch.cat(outputs, dim=1)

image.png

初始通道注意多少,没有写死
Inception后都是88通道

image.png
image.png

代码实现

代码说明:
1、先是1个卷积层(conv,maxpooling,relu),然后inceptionA模块,接下来又是一个卷积层(conv,mp,relu),然后inceptionA模块,最后一个全连接层(fc)。
2、1408这个数据可以通过x = x.view(in_size, -1)后调用x.shape得到。
1408 = channelswidthheight = 8844

widthheight 44来源:**

原始照片size:28x*28 nn.Conv2d(1, 10, kernel_size=5)(-4)24*24 nn.Conv2d(88, 20, kernel_size=5)(-4) :20*20 第一次InceptionA(-8): 第二次InceptionA(-8):**44*

Inception后都是88通道
image.png

  1. '''
  2. Description: Inception Moudel
  3. 视频:https://www.bilibili.com/video/BV1Y7411d7Ys?p=11
  4. 博客
  5. • https://blog.csdn.net/bit452/article/details/109693790
  6. • https://blog.csdn.net/weixin_44841652/article/details/105256034
  7. Author: HCQ
  8. Company(School): UCAS
  9. Email: 1756260160@qq.com
  10. Date: 2020-12-12 11:32:16
  11. LastEditTime: 2020-12-12 15:24:18
  12. FilePath: /pytorch/PyTorch深度学习实践/11.1AdvancedCNN-Inception.py
  13. '''
  14. """
  15. 1408 = channels*width*height = 88*4*4
  16. width*height 4*4来源:
  17. 原始照片size:28x*28
  18. nn.Conv2d(1, 10, kernel_size=5)(-4):24*24
  19. nn.Conv2d(88, 20, kernel_size=5)(-4) :20*20
  20. 第一次InceptionA(-8):
  21. 第二次InceptionA(-8):4*4
  22. """
  23. import torch
  24. import torch.nn as nn
  25. from torchvision import transforms
  26. from torchvision import datasets
  27. from torch.utils.data import DataLoader
  28. import torch.nn.functional as F
  29. import torch.optim as optim
  30. # prepare dataset
  31. batch_size = 64
  32. transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) # 归一化,均值和方差
  33. train_dataset = datasets.MNIST(root='./data/mnist/', train=True, download=True, transform=transform)
  34. train_loader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size)
  35. test_dataset = datasets.MNIST(root='./data/mnist/', train=False, download=True, transform=transform)
  36. test_loader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size)
  37. # design model using class
  38. class InceptionA(nn.Module):
  39. def __init__(self, in_channels):
  40. super(InceptionA, self).__init__()
  41. self.branch1x1 = nn.Conv2d(in_channels, 16, kernel_size=1)
  42. self.branch5x5_1 = nn.Conv2d(in_channels, 16, kernel_size=1)
  43. self.branch5x5_2 = nn.Conv2d(16, 24, kernel_size=5, padding=2)
  44. self.branch3x3_1 = nn.Conv2d(in_channels, 16, kernel_size=1)
  45. self.branch3x3_2 = nn.Conv2d(16, 24, kernel_size=3, padding=1)
  46. self.branch3x3_3 = nn.Conv2d(24, 24, kernel_size=3, padding=1)
  47. self.branch_pool = nn.Conv2d(in_channels, 24, kernel_size=1)
  48. def forward(self, x):
  49. branch1x1 = self.branch1x1(x)
  50. branch5x5 = self.branch5x5_1(x)
  51. branch5x5 = self.branch5x5_2(branch5x5)
  52. branch3x3 = self.branch3x3_1(x)
  53. branch3x3 = self.branch3x3_2(branch3x3)
  54. branch3x3 = self.branch3x3_3(branch3x3)
  55. branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
  56. branch_pool = self.branch_pool(branch_pool)
  57. outputs = [branch1x1, branch5x5, branch3x3, branch_pool]
  58. return torch.cat(outputs, dim=1) # b,c,w,h c对应的是dim=1
  59. class Net(nn.Module):
  60. def __init__(self):
  61. super(Net, self).__init__()
  62. self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
  63. self.conv2 = nn.Conv2d(88, 20, kernel_size=5) # 88 = 24x3 + 16
  64. self.incep1 = InceptionA(in_channels=10) # 与conv1 中的10对应
  65. self.incep2 = InceptionA(in_channels=20) # 与conv2 中的20对应
  66. self.mp = nn.MaxPool2d(2)
  67. self.fc = nn.Linear(1408, 10) # 暂时不知道1408咋能自动出来的 1408 = channels*width*height = 88*4*4
  68. def forward(self, x):
  69. in_size = x.size(0) # 64 x.size: torch.Size([64, 10])
  70. x = F.relu(self.mp(self.conv1(x)))
  71. x = self.incep1(x)
  72. x = F.relu(self.mp(self.conv2(x)))
  73. x = self.incep2(x)
  74. x = x.view(in_size, -1) # torch.Size([64, 1408]) Channels:64 每一层channels1408
  75. x = self.fc(x)
  76. return x
  77. model = Net()
  78. # construct loss and optimizer
  79. criterion = torch.nn.CrossEntropyLoss()
  80. optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
  81. # training cycle forward, backward, update
  82. def train(epoch):
  83. running_loss = 0.0
  84. for batch_idx, data in enumerate(train_loader, 0):
  85. inputs, target = data
  86. optimizer.zero_grad()
  87. outputs = model(inputs)
  88. loss = criterion(outputs, target)
  89. loss.backward()
  90. optimizer.step()
  91. running_loss += loss.item()
  92. if batch_idx % 300 == 299:
  93. print('[%d, %5d] loss: %.3f' % (epoch+1, batch_idx+1, running_loss/300))
  94. running_loss = 0.0
  95. def test():
  96. correct = 0
  97. total = 0
  98. with torch.no_grad():
  99. for data in test_loader:
  100. images, labels = data
  101. outputs = model(images)
  102. _, predicted = torch.max(outputs.data, dim=1)
  103. total += labels.size(0)
  104. correct += (predicted == labels).sum().item()
  105. print('accuracy on test set: %d %% ' % (100*correct/total))
  106. if __name__ == '__main__':
  107. for epoch in range(10):
  108. train(epoch)
  109. test()

结果展示

image.png

ResNet:引入残差单元,简化学习目标和难度,加快训练速度,模型加深时,不会产生退化问题;能够有效解决训练过程中梯度消失和梯度爆炸问题。ResNet

bert思路:多任务轮流训练

视频中截图: 说明:1、要解决的问题:梯度消失 2、跳连接,H(x) = F(x) + x,张量维度必须一样,加完后再激活。不要做pooling,张量的维度会发生变化。 代码说明: 1、先是1个卷积层(conv,maxpooling,relu),然后ResidualBlock模块,接下来又是一个卷积层(conv,mp,relu),然后esidualBlock模块模块,最后一个全连接层(fc)。

层数越深越好?

针对CIFAR-10,20层比56层loss要小
看上去网络变复杂了,但其实性能降低了。可能原因:梯度消失

说明

1、要解决的问题:梯度消失
2、跳连接,H(x) = F(x) + x,张量维度必须一样,加完后再激活。不要做pooling,张量的维度会发生变化
最小梯度也是1左右

image.png
image.png

代码实现

代码说明:

  • 先是1个卷积层(conv,maxpooling,relu),然后ResidualBlock模块,接下来又是一个卷积层(conv,mp,relu),然后ResidualBlock模块模块,最后一个全连接层
  • ResidualBlock模块的输出张量维度和输入张量维度要保持一致

image.png

image.png

输出通道和输入通道一致,代码中直接设置同一个channels

  • 卷积是层中的事情,res是层间的事情

image.png

总体代码

写网络,增量式开发的思想:一层写好测试下,再写下一层

image.png

'''
Description: ResNet
视频:https://www.bilibili.com/video/BV1Y7411d7Ys?p=11
博客
• https://blog.csdn.net/bit452/article/details/109693790
•  https://blog.csdn.net/weixin_44841652/article/details/105256034
Author: HCQ
Company(School): UCAS
Email: 1756260160@qq.com
Date: 2020-12-12 15:25:16
LastEditTime: 2020-12-12 15:29:18
FilePath: /pytorch/PyTorch深度学习实践/11.2AdvancedCNN-ResNet.py
'''


import torch
import torch.nn as nn
from torchvision import transforms
from torchvision import datasets
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torch.optim as optim

# prepare dataset

batch_size = 64
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) # 归一化,均值和方差

train_dataset = datasets.MNIST(root='./data/mnist/', train=True, download=True, transform=transform)
train_loader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size)
test_dataset = datasets.MNIST(root='./data/mnist/', train=False, download=True, transform=transform)
test_loader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size)

# design model using class
class ResidualBlock(nn.Module):
    def __init__(self, channels):
        super(ResidualBlock, self).__init__()
        self.channels = channels
        self.conv1 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)
        self.conv2 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)

    def forward(self, x):
        y = F.relu(self.conv1(x))
        y = self.conv2(y)
        return F.relu(x + y)

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 16, kernel_size=5)
        self.conv2 = nn.Conv2d(16, 32, kernel_size=5) # 88 = 24x3 + 16

        self.rblock1 = ResidualBlock(16)
        self.rblock2 = ResidualBlock(32)

        self.mp = nn.MaxPool2d(2)
        self.fc = nn.Linear(512, 10) # 512咋能自动出来的  512 = channels*width*height 


    def forward(self, x):
        in_size = x.size(0)

        x = self.mp(F.relu(self.conv1(x)))
        x = self.rblock1(x)
        x = self.mp(F.relu(self.conv2(x)))
        x = self.rblock2(x)

        x = x.view(in_size, -1)
        x = self.fc(x)
        return x

model = Net()

# construct loss and optimizer
criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)

# training cycle forward, backward, update


def train(epoch):
    running_loss = 0.0
    for batch_idx, data in enumerate(train_loader, 0):
        inputs, target = data
        optimizer.zero_grad()

        outputs = model(inputs)
        loss = criterion(outputs, target)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        if batch_idx % 300 == 299:
            print('[%d, %5d] loss: %.3f' % (epoch+1, batch_idx+1, running_loss/300))
            running_loss = 0.0


def test():
    correct = 0
    total = 0
    with torch.no_grad():
        for data in test_loader:
            images, labels = data
            outputs = model(images)
            _, predicted = torch.max(outputs.data, dim=1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()
    print('accuracy on test set: %d %% ' % (100*correct/total))


if __name__ == '__main__':
    for epoch in range(10):
        train(epoch)
        test()

结果展示

image.png

课后Exercise

He K, Zhang X, Ren S, et al. Identity Mappings in Deep Residual Networks[C]

更多Residual相关设计

image.png

Huang G, Liu Z, Laurens V D M, et al. Densely Connected Convolutional Networks[J]. 2016:2261-2269.

DenseNet:密集连接;加强特征传播,鼓励特征复用,极大的减少了参数量。DenseNet
多了好多
**

image.png