File size: 8,139 Bytes
bdbd148 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 |
'''
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
# 第一个1x1组卷积
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)
# 3x3深度可分离卷积
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)
# 第二个1x1组卷积
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 _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():
"""返回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() |