外贸企业网站模板建站流程新手搭建网站第一步
倒残差结构:
倒残差结构是MobileNetV2中引入的一种设计,用于增强网络的表达能力和特征提取能力,同时保持轻量级的特点。它的核心思想是在每个瓶颈块中,先使用一个扩张卷积(Dilated Convolution),然后再应用一个融合卷积(Pointwise Convolution),以增加非线性性和跨通道的特征表达。
- 扩张卷积(Dilated Convolution):在瓶颈块的中间层,应用了一个扩张卷积。扩张卷积通过在卷积核中引入一定的空洞(dilation),扩大了卷积核的感受野。这有助于网络捕捉更广阔的上下文信息,从而提高了特征的丰富性。
- 融合卷积(Pointwise Convolution):扩张卷积后,使用1x1的融合卷积来进行特征的融合和压缩。这个融合卷积将扩张卷积得到的特征进行通道的线性组合,从而加强了特征之间的交互。
以下是一个更详细的PyTorch代码示例:
import torch
import torch.nn as nn
from torchsummary import summary# 3、倒残差结构
class ConvBNReLU(nn.Sequential):def __init__(self, in_channel, out_channel, kernel_size=3, stride=1, groups=1):padding = (kernel_size - 1) // 2super(ConvBNReLU, self).__init__(nn.Conv2d(in_channel, out_channel, kernel_size, stride, padding, groups=groups, bias=False),nn.BatchNorm2d(out_channel),nn.ReLU(inplace=True))class InvertedResidual(nn.Module):def __init__(self, in_channel, out_channel, stride, expand_ratio):super(InvertedResidual, self).__init__()hidden_channel = in_channel * expand_ratio#expand_ratio:扩展因子self.use_shortcut = stride == 1 and in_channel == out_channellayers = []if expand_ratio != 1:layers.append(ConvBNReLU(in_channel, hidden_channel, kernel_size=1))#hxwxk-->hxwx(tk)layers.extend([#layers.extend() 是 Python 中的列表方法,用于在一个列表的末尾一次性添加另一个可迭代对象中的所有元素到该列表中。ConvBNReLU(hidden_channel, hidden_channel, kernel_size=stride, groups=hidden_channel),#hxwx(tk)-->(h/s)x(w/s)x(tk)nn.Conv2d(hidden_channel, out_channel, kernel_size=1, bias=False),#(h/s)x(w/s)x(tk)-->(h/s)x(w/s)xk'nn.BatchNorm2d(out_channel)])self.conv = nn.Sequential(*layers)def forward(self, x):if self.use_shortcut:x = x + self.conv(x)return xelse:x = self.conv(x)return xif __name__ == '__main__':model=InvertedResidual(3,64,1,6)device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')model.to(device)input_tensor=torch.randn(1,3,224,224).to(device)input_tensor1 = (3, 224, 224)output_tensor=model(input_tensor)print(output_tensor.shape)print("InvertedResidual:")summary(model, input_tensor1)
以上代码详细展示了如何使用PyTorch构建一个倒残差结构的MobileNetV2模型。您可以根据实际需要进行调整和扩展。