| ''' |
| ShuffleNet in PyTorch. |
| |
| ShuffleNet是一个专门为移动设备设计的高效卷积神经网络。其主要创新点在于使用了两个新操作: |
| 1. 逐点组卷积(pointwise group convolution) |
| 2. 通道重排(channel shuffle) |
| 这两个操作大大降低了计算复杂度,同时保持了良好的准确率。 |
| |
| 主要特点: |
| 1. 使用组卷积减少参数量和计算量 |
| 2. 使用通道重排操作使不同组之间的信息可以流通 |
| 3. 使用深度可分离卷积进一步降低计算复杂度 |
| 4. 设计了多个计算复杂度版本以适应不同的设备 |
| |
| Reference: |
| [1] Xiangyu Zhang, Xinyu Zhou, Mengxiao Lin, Jian Sun |
| ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices. CVPR 2018. |
| ''' |
| import torch |
| import torch.nn as nn |
| import torch.nn.functional as F |
|
|
|
|
| class ShuffleBlock(nn.Module): |
| """通道重排模块 |
| |
| 通过重新排列通道的顺序来实现不同组之间的信息交流。 |
| |
| Args: |
| groups (int): 分组数量 |
| """ |
| def __init__(self, groups): |
| super(ShuffleBlock, self).__init__() |
| self.groups = groups |
|
|
| def forward(self, x): |
| """通道重排的前向传播 |
| |
| 步骤: |
| 1. [N,C,H,W] -> [N,g,C/g,H,W] # 重塑为g组 |
| 2. [N,g,C/g,H,W] -> [N,C/g,g,H,W] # 转置g维度 |
| 3. [N,C/g,g,H,W] -> [N,C,H,W] # 重塑回原始形状 |
| |
| Args: |
| x: 输入张量,[N,C,H,W] |
| |
| Returns: |
| out: 通道重排后的张量,[N,C,H,W] |
| """ |
| N, C, H, W = x.size() |
| g = self.groups |
| return x.view(N,g,C//g,H,W).permute(0,2,1,3,4).reshape(N,C,H,W) |
|
|
|
|
| class Bottleneck(nn.Module): |
| """ShuffleNet的基本模块 |
| |
| 结构: |
| x -> 1x1 GConv -> BN -> Shuffle -> 3x3 DWConv -> BN -> 1x1 GConv -> BN -> (+) -> ReLU |
| |---------------------| |
| |
| Args: |
| in_channels (int): 输入通道数 |
| out_channels (int): 输出通道数 |
| stride (int): 步长,用于下采样 |
| groups (int): 组卷积的分组数 |
| """ |
| def __init__(self, in_channels, out_channels, stride, groups): |
| super(Bottleneck, self).__init__() |
| self.stride = stride |
| |
| |
| mid_channels = out_channels // 4 |
| g = 1 if in_channels == 24 else groups |
| |
| |
| self.conv1 = nn.Conv2d(in_channels, mid_channels, |
| kernel_size=1, groups=g, bias=False) |
| self.bn1 = nn.BatchNorm2d(mid_channels) |
| self.shuffle1 = ShuffleBlock(groups=g) |
| |
| |
| self.conv2 = nn.Conv2d(mid_channels, mid_channels, |
| kernel_size=3, stride=stride, padding=1, |
| groups=mid_channels, bias=False) |
| self.bn2 = nn.BatchNorm2d(mid_channels) |
| |
| |
| self.conv3 = nn.Conv2d(mid_channels, out_channels, |
| kernel_size=1, groups=groups, bias=False) |
| self.bn3 = nn.BatchNorm2d(out_channels) |
|
|
| |
| self.shortcut = nn.Sequential() |
| if stride == 2: |
| self.shortcut = nn.Sequential( |
| nn.AvgPool2d(3, stride=2, padding=1) |
| ) |
|
|
| def forward(self, x): |
| |
| out = F.relu(self.bn1(self.conv1(x))) |
| out = self.shuffle1(out) |
| out = F.relu(self.bn2(self.conv2(out))) |
| out = self.bn3(self.conv3(out)) |
| |
| |
| res = self.shortcut(x) |
| |
| |
| out = F.relu(torch.cat([out, res], 1)) if self.stride == 2 else F.relu(out + res) |
| return out |
|
|
|
|
| class ShuffleNet(nn.Module): |
| """ShuffleNet模型 |
| |
| 网络结构: |
| 1. 一个卷积层进行特征提取 |
| 2. 三个阶段,每个阶段包含多个带重排的残差块 |
| 3. 平均池化和全连接层进行分类 |
| |
| Args: |
| cfg (dict): 配置字典,包含: |
| - out_channels (list): 每个阶段的输出通道数 |
| - num_blocks (list): 每个阶段的块数 |
| - groups (int): 组卷积的分组数 |
| """ |
| def __init__(self, cfg): |
| super(ShuffleNet, self).__init__() |
| out_channels = cfg['out_channels'] |
| num_blocks = cfg['num_blocks'] |
| groups = cfg['groups'] |
|
|
| |
| self.conv1 = nn.Conv2d(3, 24, kernel_size=1, bias=False) |
| self.bn1 = nn.BatchNorm2d(24) |
| self.in_channels = 24 |
| |
| |
| self.layer1 = self._make_layer(out_channels[0], num_blocks[0], groups) |
| self.layer2 = self._make_layer(out_channels[1], num_blocks[1], groups) |
| self.layer3 = self._make_layer(out_channels[2], num_blocks[2], groups) |
| |
| |
| self.avg_pool = nn.AdaptiveAvgPool2d(1) |
| self.classifier = nn.Linear(out_channels[2], 10) |
| |
| |
| self._initialize_weights() |
|
|
| def _make_layer(self, out_channels, num_blocks, groups): |
| """构建ShuffleNet的一个阶段 |
| |
| Args: |
| out_channels (int): 输出通道数 |
| num_blocks (int): 块的数量 |
| groups (int): 分组数 |
| |
| Returns: |
| nn.Sequential: 一个阶段的层序列 |
| """ |
| layers = [] |
| for i in range(num_blocks): |
| stride = 2 if i == 0 else 1 |
| cat_channels = self.in_channels if i == 0 else 0 |
| layers.append( |
| Bottleneck( |
| self.in_channels, |
| out_channels - cat_channels, |
| stride=stride, |
| groups=groups |
| ) |
| ) |
| self.in_channels = out_channels |
| return nn.Sequential(*layers) |
|
|
| def forward(self, x): |
| """前向传播 |
| |
| Args: |
| x: 输入张量,[N,3,32,32] |
| |
| Returns: |
| out: 输出张量,[N,num_classes] |
| """ |
| |
| out = F.relu(self.bn1(self.conv1(x))) |
| |
| |
| out = self.layer1(out) |
| out = self.layer2(out) |
| out = self.layer3(out) |
| |
| |
| out = self.avg_pool(out) |
| out = out.view(out.size(0), -1) |
| out = self.classifier(out) |
| return out |
| |
| def feature(self, x): |
| """提取特征""" |
| out = F.relu(self.bn1(self.conv1(x))) |
| out = self.layer1(out) |
| out = self.layer2(out) |
| out = self.layer3(out) |
| out = self.avg_pool(out) |
| return out |
|
|
| def prediction(self, x): |
| """分类""" |
| x = x.view(x.size(0), -1) |
| out = self.classifier(x) |
| return out |
| |
| def _initialize_weights(self): |
| """初始化模型权重 |
| |
| 采用kaiming初始化方法: |
| - 卷积层权重采用kaiming_normal_初始化 |
| - BN层参数采用常数初始化 |
| - 线性层采用正态分布初始化 |
| """ |
| 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.BatchNorm2d): |
| nn.init.constant_(m.weight, 1) |
| 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) |
|
|
|
|
| def ShuffleNetG2(num_classes=10): |
| """返回groups=2的ShuffleNet模型""" |
| cfg = { |
| 'out_channels': [200,400,800], |
| 'num_blocks': [4,8,4], |
| 'groups': 2 |
| } |
| return ShuffleNet(cfg) |
|
|
|
|
| def ShuffleNetG3(): |
| """返回groups=3的ShuffleNet模型""" |
| cfg = { |
| 'out_channels': [240,480,960], |
| 'num_blocks': [4,8,4], |
| 'groups': 3 |
| } |
| return ShuffleNet(cfg) |
|
|
|
|
| def test(): |
| """测试函数""" |
| |
| net = ShuffleNetG2() |
| print('Model Structure:') |
| print(net) |
| |
| |
| x = torch.randn(1,3,32,32) |
| y = net(x) |
| print('\nInput Shape:', x.shape) |
| print('Output Shape:', y.shape) |
| |
| |
| from torchinfo import summary |
| device = 'cuda' if torch.cuda.is_available() else 'cpu' |
| net = net.to(device) |
| summary(net, (1,3,32,32)) |
|
|
|
|
| if __name__ == '__main__': |
| test() |