SE-Inception v3架构的模型搭建(keras代码实现)

本文详细代码点击这里https://zhuanlan.zhihu.com/p/331753542

首先,先上SENet架构的原理图:(这里r=16)
在这里插入图片描述
在这里插入图片描述
图是将SE模块嵌入到Inception结构的一个示例。方框旁边的维度信息代表该层的输出。这里我们使用global average pooling作为Squeeze操作。紧接着两个Fully Connected 层组成一个Bottleneck结构去建模通道间的相关性,并输出和输入特征同样数目的权重。我们首先将特征维度降低到输入的1/16,然后经过ReLu激活后再通过一个Fully Connected 层升回到原来的维度。 这样做比直接用一个Fully Connected层的好处在于:

  • 具有更多的非线性,可以更好地拟合通道间复杂的相关性;
  • 极大地减少了参数量和计算量。然后通过一个Sigmoid的门获得0~1之间归一化的权重,最后通过一个Scale的操作来将归一化后的权重加权到每个通道的特征上;

SENet架构(Squeeze And Excitation),无非就是Squeeze操作和Excitation操作:

  • 首先是Squeeze操作,我们顺着空间维度来进行特征压缩,将每个二维的特征通道变成一个实数,这个实数某种程度上具有全局的感受野,并且输出的维度和输入的特征通道数相匹配。它表征着在特征通道上响应的全局分布,而且使得靠近输入的层也可以获得全局的感受野,这一点在很多任务中都是非常有用的。
  • 其次是Excitation操作,它是一个类似于循环神经网络中门的机制。通过参数 来为每个特征通道生成权重,其中参数 被学习用来显式地建模特征通道间的相关性。
  • 最后是一个Reweight的操作,我们将Excitation的输出的权重看做是进过特征选择后的每个特征通道的重要性,然后通过乘法逐通道加权到先前的特征上,完成在通道维度上的对原始特征的重标定。

接下来是代码实现:

def build_model(nb_classes, input_shape=(256,256,3)):
    inputs_dim = Input(input_shape)
    x = InceptionV3(include_top=False,
                weights='imagenet',
                input_tensor=None,
                input_shape=(256, 256, 3),
                pooling=max)(inputs_dim)

    squeeze = GlobalAveragePooling2D()(x)

    excitation = Dense(units=2048 // 16)(squeeze)
    excitation = Activation('relu')(excitation)
    excitation = Dense(units=2048)(excitation)
    excitation = Activation('sigmoid')(excitation)
    excitation = Reshape((1, 1, 2048))(excitation)

    scale = multiply([x, excitation])

    x = GlobalAveragePooling2D()(scale)
    dp_1 = Dropout(0.3)(x)
    fc2 = Dense(nb_classes)(dp_1)
    fc2 = Activation('sigmoid')(fc2) #此处注意,为sigmoid函数
    model = Model(inputs=inputs_dim, outputs=fc2)
    return model

if __name__ == '__main__':
	model =build_model(nb_classes, input_shape=(im_size1, im_size2, channels))
	opt = Adam(lr=2*1e-5)
    model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
    model.fit()

注意:

  1. multiply([x, excitation])中x的shape为(10,10,2048),excitation的shape为(1,1,2048),应保持它们的最后一维相同即2048相同。例子:如果用DesNet201,它的最后一层卷积出来的结果为(8,8,1920)(不包括全连接层),excitation 的Reshape为(1,1,1920)。
  2. fc2 = Activation(‘sigmoid’)(fc2) #此处注意,为sigmoid函数。
  • 7
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 19
    评论
在深度学习中,卷积神经网络(Convolutional Neural Network, CNN)是最常用和最流行的网络结构之一。然而,CNN 有一个缺点,即每一层只能提取特定大小的特征。这可能导致信息丢失和性能下降。为了解决这个问题,动态卷积被引入了 CNN 中。与传统的卷积相比,动态卷积可以自适应地学习特征的大小和形状。 DenseNet-Inception 模型是一种结合了 DenseNetInception 的网络结构,其中 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 中,我们使用了密集连接来提高特征的重用。最后,我们定义了一个全连接层来分类。 如果您想使用这个模型来训练数据,请确保您已经定义了数据集,并使用合适的优化器和损失函数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值