经典卷积模型(四)GoogLeNet-Inception(V1)代码解析

GoogleNet

原则:

  • 在设计的网络中,特别是网络的早起部分要避免瓶颈效应。在得到最终特征表示之前,特征的尺寸应该是从输入尺寸逐步地减小的。特征表达所蕴含的信息内容不能仅仅通过特征的维度来判断,还应该关注提取这些特征的网络结构。
  • 高维的特征表示适合在当前局部结构中处理。在每层后面添加激活单元,可以得到更可分的特征,网络也会训练得更快。
  • 空间聚合(inception结构)可以使用更低维度的卷积核上进行,在聚合之前使用更多的小尺寸卷积层仅会带来很少的特征损失。如果采用一个空间聚合结构,相邻单元之间的强相关性会减少这部分损失,这也有助于网络的训练。(融合不同尺度的特征信息)
  • 平衡网络的宽度和深度,也就是要平衡每个结构内的卷积层数量以及网络的总的深度。同时增加深度和宽度有利于构建更好的网络。
  • 添加两个辅助分类器帮助训练
  • 丢弃全连接层,使用平均池化层(大大减少模型 参数)
  • 使用1x1的卷积核进行降维以及映射处理

结构图

可以看出来,主要由Inception构成,网络加宽加深。
参考在这里插入图片描述

代码

由最基本的BasicConv2d,Inception,Inception辅助分类器和核心网络四个类构成。

BasicConv2d 基本卷积模块

也就是带有relu的卷积层。

class BasicConv2d(nn.Module):
   def __init__(self, in_channels, out_channels, **kwargs):
       super(BasicConv2d, self).__init__()
       self.conv = nn.Conv2d(in_channels, out_channels, **kwargs)
       self.relu = nn.ReLU(inplace=True)

   def forward(self, x):
       x = self.conv(x)
       x = self.relu(x)
       return x

Inception 多尺度融合

在这里插入图片描述
由4个Brach构成。1*1卷积核,1*1卷积核+3*3卷积核,1*1卷积核+5*5卷积核,最大池化+1*1卷积核。
def __init__(self, in_channels, ch1x1, ch3x3red, ch3x3, ch5x5red, ch5x5, pool_proj)

  1. branch1:使用1*1的卷积核,将(Hin,Win,in_channels)-> (Hin,Win,ch1x1),特征图大小不变,主要改变的是通道数得到第一张特征图(Hin,Win,ch1x1)。
    branch1 = BasicConv2d(in_channels, ch1x1, kernel_size=1)
    
  2. branch2:先使用1*1的卷积核,将(Hin,Win,in_channels)-> (Hin,Win,ch3x3red),特征图大小不变,缩小通道数,减少计算量,然后在使用大小3*3填充1的卷积核,保持特征图大小不变,改变通道数为ch3x3,得到第二张特征图(Hin,Win,ch3x3)。
    self.branch2 = nn.Sequential(
        BasicConv2d(in_channels, ch3x3red, kernel_size=1),
        BasicConv2d(ch3x3red, ch3x3, kernel_size=3, padding=1)   # 保证输出大小等于输入大小
    )
    
  3. branch3:先使用1*1的卷积核,将(Hin,Win,in_channels)-> (Hin,Win,ch5x5red),特征图大小不变,缩小通道数,减少计算量,然后在使用大小5*5填充2的卷积核,保持特征图大小不变,改变通道数为ch5x5,得到第三张特征图(Hin,Win,ch5x5)。
    self.branch3 = nn.Sequential(
        BasicConv2d(in_channels, ch5x5red, kernel_size=1),
        BasicConv2d(ch5x5red, ch5x5, kernel_size=5, padding=2)   # 保证输出大小等于输入大小
    )
    
  4. branch4:先经过最大池化层,因为stride=1,特征图大小不变,然后在使用大小1*1的卷积核,保持特征图大小不变,改变通道数为pool_proj,得到第四张特征图(Hin,Win,pool_proj)。
    self.branch4 = nn.Sequential(
        nn.MaxPool2d(kernel_size=3, stride=1, padding=1),
        BasicConv2d(in_channels, pool_proj, kernel_size=1)
    )
    
  5. 最后outputs = [branch1, branch2, branch3, branch4],且torch.cat(outputs, 1),进行拼接得到最终的特征图:(Hin,Win,ch1x1+ch1x1+ch5x5+pool_proj)

Inception主要代码:

class Inception(nn.Module):
   def __init__(self, in_channels, ch1x1, ch3x3red, ch3x3, ch5x5red, ch5x5, pool_proj):
       super(Inception, self).__init__()
       self.branch1 = BasicConv2d(in_channels, ch1x1, kernel_size=1)
       self.branch2 = nn.Sequential(
           BasicConv2d(in_channels, ch3x3red, kernel_size=1),
           BasicConv2d(ch3x3red, ch3x3, kernel_size=3, padding=1)   # 保证输出大小等于输入大小
       )
       self.branch3 = nn.Sequential(
           BasicConv2d(in_channels, ch5x5red, kernel_size=1),
           BasicConv2d(ch5x5red, ch5x5, kernel_size=5, padding=2)   # 保证输出大小等于输入大小
       )
       self.branch4 = nn.Sequential(
           nn.MaxPool2d(kernel_size=3, stride=1, padding=1),
           BasicConv2d(in_channels, pool_proj, kernel_size=1)
       )
   def forward(self, x):
       branch1 = self.branch1(x)
       branch2 = self.branch2(x)
       branch3 = self.branch3(x)
       branch4 = self.branch4(x)
       outputs = [branch1, branch2, branch3, branch4]
       return torch.cat(outputs, 1)

InceptionAux 辅助分类器

GoogleNet有两个辅助分类器,输入分别来自Inception(4a)和Inception(4d)。用来辅助Inception4a前面层和Inception4d前面层的训练,毕竟参数量太大,直接训练难以收敛。于是,辅助分类的输出按一个较小的权重(0.3)加到最终分类结果中,这样相当于做了模型融合,同时给网络增加了反向传播的梯度信号,也提供了额外的正则化,对于整个网络的训练不仅提高了模型的准确性还极大的减少了参数的数量。
在这里插入图片描述

  1. 平均池化层,池化核大小为5x5,stride=3。
  2. 卷积核大小为1x1,stride=1,卷积核个数是128
  3. 打平flatten+dropout。
  4. 第一个全连接层(节点个数是1024)+relu+dropout。
  5. 第一个全连接层输出,节点个数是1000(对应分类的类别个数)。
class InceptionAux(nn.Module):
    def __init__(self, in_channels, num_classes):
        super(InceptionAux, self).__init__()
        self.averagePool = nn.AvgPool2d(kernel_size=5, stride=3)
        self.conv = BasicConv2d(in_channels, 128, kernel_size=1)  # output[batch, 128, 4, 4]
        self.fc1 = nn.Linear(2048, 1024)
        self.fc2 = nn.Linear(1024, num_classes)
    def forward(self, x):
        # aux1: N x 512 x 14 x 14, aux2: N x 528 x 14 x 14
        x = self.averagePool(x)
        # aux1: N x 512 x 4 x 4, aux2: N x 528 x 4 x 4
        x = self.conv(x)
        # N x 128 x 4 x 4
        x = torch.flatten(x, 1)
        x = F.dropout(x, 0.5, training=self.training)
        # N x 2048
        x = F.relu(self.fc1(x), inplace=True)
        x = F.dropout(x, 0.5, training=self.training)
        # N x 1024
        x = self.fc2(x)
        # N x num_classes
        return x

GoogLeNet 网络主要部分

可以看出来,步骤分为:

  1. 进入Inception之前,由带relu的卷积层conv1+最大池化层+relu的卷积层conv2+relu的卷积层conv3+最大池化层构成。
    # N x 3 x 224 x 224
    x = self.conv1(x) #conv1 = BasicConv2d(3, 64, kernel_size=7, stride=2, padding=3)
    # N x 64 x 112 x 112
    x = self.maxpool1(x) # maxpool1 =nn.MaxPool2d(3, stride=2, ceil_mode=True),两倍下采样
    # N x 64 x 56 x 56
    x = self.conv2(x)#conv2 = BasicConv2d(64, 64, kernel_size=1)
    # N x 64 x 56 x 56
    x = self.conv3(x)#conv3 = BasicConv2d(64, 192, kernel_size=3, padding=1)
    # N x 192 x 56 x 56
    x = self.maxpool2(x) # maxpool2 = nn.MaxPool2d(3, stride=2, ceil_mode=True),两倍下采样
    
  2. Inception部分(inception3a~3b,inception4a~4e,inception5a~5b):
    每一个inception的最终特征图输出维度为:(Hin,Win,ch1x1+ch1x1+ch5x5+pool_proj),假如inception3a = Inception(192, 64, 96, 128, 16, 32, 32),即64+128+32+32=256,则变成(192,28,28)->(256,28,28)。
    # N x 192 x 28 x 28
    x = self.inception3a(x)#Inception(192, 64, 96, 128, 16, 32, 32)
    # N x 256 x 28 x 28
    x = self.inception3b(x)#Inception(256, 128, 128, 192, 32, 96, 64)
    # N x 480 x 28 x 28
    x = self.maxpool3(x)#nn.MaxPool2d(3, stride=2, ceil_mode=True)
    # N x 480 x 14 x 14
    x = self.inception4a(x)#Inception(480, 192, 96, 208, 16, 48, 64)
    # N x 512 x 14 x 14
    if self.training and self.aux_logits:    # eval model lose this layer
        aux1 = self.aux1(x)
    x = self.inception4b(x)#Inception(512, 160, 112, 224, 24, 64, 64)
    # N x 512 x 14 x 14
    x = self.inception4c(x)#Inception(512, 128, 128, 256, 24, 64, 64)
    # N x 512 x 14 x 14
    x = self.inception4d(x)#Inception(512, 112, 144, 288, 32, 64, 64)
    # N x 528 x 14 x 14
    if self.training and self.aux_logits:    # eval model lose this layer
        aux2 = self.aux2(x)
    x = self.inception4e(x)#(528, 256, 160, 320, 32, 128, 128)
    # N x 832 x 14 x 14
    x = self.maxpool4(x)# nn.MaxPool2d(3, stride=2, ceil_mode=True)
    # N x 832 x 7 x 7
    x = self.inception5a(x)#Inception(832, 256, 160, 320, 32, 128, 128)
    # N x 832 x 7 x 7
    x = self.inception5b(x)#Inception(832, 384, 192, 384, 48, 128, 128)
    
  3. 如果使用到辅助分类器InceptionAux,它接在inception4a之后和inception4d之后。
    x = self.inception4a(x)#Inception(480, 192, 96, 208, 16, 48, 64)
    # N x 512 x 14 x 14
    if self.training and self.aux_logits:    # eval model lose this layer
        aux1 = self.aux1(x)
    
    x = self.inception4d(x)#Inception(512, 112, 144, 288, 32, 64, 64)
    # N x 528 x 14 x 14
    if self.training and self.aux_logits:    # eval model lose this layer
        aux2 = self.aux2(x)
    
  4. 最终分类部分,由平均池化层+dropout+全连接层输出x,如果使用到辅助分类器就输出x, aux2, aux1。其中采用了平均池化层来代替全连接层,事实证明这样可以提高准确率0.6%。最后还是加了一个全连接层,主要是为了方便对输出进行灵活调整。
    # N x 1024 x 7 x 7
    x = self.avgpool(x)
    # N x 1024 x 1 x 1
    x = torch.flatten(x, 1)
    # N x 1024
    x = self.dropout(x)
    x = self.fc(x)
    # N x 1000 (num_classes)
    if self.training and self.aux_logits:   # eval model lose this layer
        return x, aux2, aux1
    return x
    

主要代码:

class GoogLeNet(nn.Module):
    def __init__(self, num_classes=1000, aux_logits=True, init_weights=False):
        super(GoogLeNet, self).__init__()
        self.aux_logits = aux_logits
        self.conv1 = BasicConv2d(3, 64, kernel_size=7, stride=2, padding=3)
        self.maxpool1 = nn.MaxPool2d(3, stride=2, ceil_mode=True)
        self.conv2 = BasicConv2d(64, 64, kernel_size=1)
        self.conv3 = BasicConv2d(64, 192, kernel_size=3, padding=1)
        self.maxpool2 = nn.MaxPool2d(3, stride=2, ceil_mode=True)
        self.inception3a = Inception(192, 64, 96, 128, 16, 32, 32)
        self.inception3b = Inception(256, 128, 128, 192, 32, 96, 64)
        self.maxpool3 = nn.MaxPool2d(3, stride=2, ceil_mode=True)
        self.inception4a = Inception(480, 192, 96, 208, 16, 48, 64)
        self.inception4b = Inception(512, 160, 112, 224, 24, 64, 64)
        self.inception4c = Inception(512, 128, 128, 256, 24, 64, 64)
        self.inception4d = Inception(512, 112, 144, 288, 32, 64, 64)
        self.inception4e = Inception(528, 256, 160, 320, 32, 128, 128)
        self.maxpool4 = nn.MaxPool2d(3, stride=2, ceil_mode=True)
        self.inception5a = Inception(832, 256, 160, 320, 32, 128, 128)
        self.inception5b = Inception(832, 384, 192, 384, 48, 128, 128)
        if self.aux_logits:
            self.aux1 = InceptionAux(512, num_classes)
            self.aux2 = InceptionAux(528, num_classes)
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.dropout = nn.Dropout(0.4)
        self.fc = nn.Linear(1024, num_classes)
        if init_weights:
            self._initialize_weights()
    def forward(self, x):
        # N x 3 x 224 x 224
        x = self.conv1(x)
        # N x 64 x 112 x 112
        x = self.maxpool1(x)
        # N x 64 x 56 x 56
        x = self.conv2(x)
        # N x 64 x 56 x 56
        x = self.conv3(x)
        # N x 192 x 56 x 56
        x = self.maxpool2(x)
        # N x 192 x 28 x 28
        x = self.inception3a(x)
        # N x 256 x 28 x 28
        x = self.inception3b(x)
        # N x 480 x 28 x 28
        x = self.maxpool3(x)
        # N x 480 x 14 x 14
        x = self.inception4a(x)
        # N x 512 x 14 x 14
        if self.training and self.aux_logits:    # eval model lose this layer
            aux1 = self.aux1(x)
        x = self.inception4b(x)
        # N x 512 x 14 x 14
        x = self.inception4c(x)
        # N x 512 x 14 x 14
        x = self.inception4d(x)
        # N x 528 x 14 x 14
        if self.training and self.aux_logits:    # eval model lose this layer
            aux2 = self.aux2(x)
        x = self.inception4e(x)
        # N x 832 x 14 x 14
        x = self.maxpool4(x)
        # N x 832 x 7 x 7
        x = self.inception5a(x)
        # N x 832 x 7 x 7
        x = self.inception5b(x)
        # N x 1024 x 7 x 7
        x = self.avgpool(x)
        # N x 1024 x 1 x 1
        x = torch.flatten(x, 1)
        # N x 1024
        x = self.dropout(x)
        x = self.fc(x)
        # N x 1000 (num_classes)
        if self.training and self.aux_logits:   # eval model lose this layer
            return x, aux2, aux1
        return x
    def _initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                nn.init.normal_(m.weight, 0, 0.01)
                nn.init.constant_(m.bias, 0)

参数初始化

对卷积层和全连接层的参数进行初始化,一般都是使得网络变得更好收敛。暂时不太了解初始化的操作原理,先贴一个博客以后看:https://www.cnblogs.com/quant-q/p/15056396.html

__init__
	if init_weights:
	    self._initialize_weights()
    
def _initialize_weights(self):
    for m in self.modules():
        if isinstance(m, nn.Conv2d):
            nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            if m.bias is not None:
                nn.init.constant_(m.bias, 0)
        elif isinstance(m, nn.Linear):
            nn.init.normal_(m.weight, 0, 0.01)
            nn.init.constant_(m.bias, 0)

参考

官方代码
https://blog.csdn.net/weixin_44023658/article/details/105834809

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
深度学习中,卷积神经网络(Convolutional Neural Network, CNN)是最常用和最流行的网络结构之一。然而,CNN 有一个缺点,即每一层只能提取特定大小的特征。这可能导致信息丢失和性能下降。为了解决这个问题,动态卷积被引入了 CNN 中。与传统的卷积相比,动态卷积可以自适应地学习特征的大小和形状。 DenseNet-Inception 模型是一种结合了 DenseNet 和 Inception 的网络结构,其中 DenseNet 使用密集连接来提高特征的重用,Inception 利用不同大小的卷积核来提取不同大小的特征。在这个模型中,动态卷积被引入到了 Inception 模块中,以提高模型的性能。 以下是 DenseNet-Inception 模型代码实现: ```python import torch import torch.nn as nn import torch.nn.functional as F class DenseNetInception(nn.Module): def __init__(self, num_classes=10): super(DenseNetInception, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) # Inception module with dynamic convolution self.inception1 = InceptionModule(64, 64, 96, 128, 16, 32, 32) self.inception2 = InceptionModule(256, 128, 128, 192, 32, 96, 64) self.inception3 = InceptionModule(480, 192, 96, 208, 16, 48, 64) self.inception4 = InceptionModule(512, 160, 112, 224, 24, 64, 64) self.inception5 = InceptionModule(512, 128, 128, 256, 24, 64, 64) self.inception6 = InceptionModule(512, 112, 144, 288, 32, 64, 64) self.inception7 = InceptionModule(528, 256, 160, 320, 32, 128, 128) self.inception8 = InceptionModule(832, 256, 160, 320, 32, 128, 128) self.inception9 = InceptionModule(832, 384, 192, 384, 48, 128, 128) # DenseNet module self.dense_block1 = DenseBlock(832, 32) self.trans_block1 = TransitionBlock(1024, 0.5) self.dense_block2 = DenseBlock(512, 32) self.trans_block2 = TransitionBlock(768, 0.5) self.dense_block3 = DenseBlock(384, 32) self.trans_block3 = TransitionBlock(576, 0.5) self.dense_block4 = DenseBlock(288, 32) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(288, num_classes) def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.inception1(x) x = self.inception2(x) x = self.inception3(x) x = self.inception4(x) x = self.inception5(x) x = self.inception6(x) x = self.inception7(x) x = self.inception8(x) x = self.inception9(x) x = self.dense_block1(x) x = self.trans_block1(x) x = self.dense_block2(x) x = self.trans_block2(x) x = self.dense_block3(x) x = self.trans_block3(x) x = self.dense_block4(x) x = self.avgpool(x) x = x.view(x.size(0), -1) x = self.fc(x) return x class InceptionModule(nn.Module): def __init__(self, in_channels, out1, out2_1, out2_2, out3_1, out3_2, out4_2): super(InceptionModule, self).__init__() self.branch1 = nn.Sequential( nn.Conv2d(in_channels, out1, kernel_size=1), nn.BatchNorm2d(out1), nn.ReLU(inplace=True) ) self.branch2 = nn.Sequential( nn.Conv2d(in_channels, out2_1, kernel_size=1), nn.BatchNorm2d(out2_1), nn.ReLU(inplace=True), DynamicConv2d(out2_1, out2_2, kernel_size=3, stride=1, padding=1, bias=False), nn.BatchNorm2d(out2_2), nn.ReLU(inplace=True) ) self.branch3 = nn.Sequential( nn.Conv2d(in_channels, out3_1, kernel_size=1), nn.BatchNorm2d(out3_1), nn.ReLU(inplace=True), DynamicConv2d(out3_1, out3_2, kernel_size=5, stride=1, padding=2, bias=False), nn.BatchNorm2d(out3_2), nn.ReLU(inplace=True) ) self.branch4 = nn.Sequential( nn.MaxPool2d(kernel_size=3, stride=1, padding=1), nn.Conv2d(in_channels, out4_2, kernel_size=1), nn.BatchNorm2d(out4_2), nn.ReLU(inplace=True) ) def forward(self, x): branch1 = self.branch1(x) branch2 = self.branch2(x) branch3 = self.branch3(x) branch4 = self.branch4(x) outputs = [branch1, branch2, branch3, branch4] return torch.cat(outputs, 1) class DenseBlock(nn.Module): def __init__(self, in_channels, growth_rate): super(DenseBlock, self).__init__() self.conv1 = nn.Conv2d(in_channels, 4 * growth_rate, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(4 * growth_rate) self.relu = nn.ReLU(inplace=True) self.conv2 = DynamicConv2d(4 * growth_rate, growth_rate, kernel_size=3, stride=1, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(growth_rate) def forward(self, x): out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = torch.cat([x, out], 1) return out class TransitionBlock(nn.Module): def __init__(self, in_channels, reduction): super(TransitionBlock, self).__init__() self.conv = nn.Conv2d(in_channels, int(in_channels * reduction), kernel_size=1, bias=False) self.bn = nn.BatchNorm2d(int(in_channels * reduction)) self.relu = nn.ReLU(inplace=True) self.avgpool = nn.AvgPool2d(kernel_size=2, stride=2) def forward(self, x): out = self.conv(x) out = self.bn(out) out = self.relu(out) out = self.avgpool(out) return out class DynamicConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True): super(DynamicConv2d, self).__init__() self.kernel_size = kernel_size self.stride = stride self.padding = padding self.dilation = dilation self.groups = groups self.weight = nn.Parameter(torch.Tensor(out_channels, in_channels // groups, kernel_size, kernel_size)) if bias: self.bias = nn.Parameter(torch.Tensor(out_channels)) else: self.register_parameter('bias', None) self.reset_parameters() def reset_parameters(self): nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) if self.bias is not None: fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight) bound = 1 / math.sqrt(fan_in) nn.init.uniform_(self.bias, -bound, bound) def forward(self, x): weight = F.pad(self.weight, (self.padding, self.padding, self.padding, self.padding)) weight = weight[:, :, :x.shape[-2] + self.padding * 2, :x.shape[-1] + self.padding * 2] out = F.conv2d(x, weight, self.bias, self.stride, 0, self.dilation, self.groups) return out ``` 在这个代码中,我们定义了一个 DenseNet-Inception 模型,并实现了动态卷积。在模型中,我们首先定义了一个标准的卷积层,然后定义了 Inception 模块和 DenseNet 模块。在 Inception 模块中,我们引入了动态卷积,以提高模型的性能。在 DenseNet 中,我们使用了密集连接来提高特征的重用。最后,我们定义了一个全连接层来分类。 如果您想使用这个模型来训练数据,请确保您已经定义了数据集,并使用合适的优化器和损失函数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nooobme

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值