|
''' |
|
MobileNetv1 in PyTorch. |
|
|
|
论文: "MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications" |
|
参考: https://arxiv.org/abs/1704.04861 |
|
|
|
主要特点: |
|
1. 使用深度可分离卷积(Depthwise Separable Convolution)减少参数量和计算量 |
|
2. 引入宽度乘子(Width Multiplier)和分辨率乘子(Resolution Multiplier)进一步压缩模型 |
|
3. 适用于移动设备和嵌入式设备的轻量级CNN架构 |
|
''' |
|
|
|
import torch |
|
import torch.nn as nn |
|
|
|
|
|
class Block(nn.Module): |
|
'''深度可分离卷积块 (Depthwise Separable Convolution Block) |
|
|
|
包含: |
|
1. 深度卷积(Depthwise Conv): 对每个通道单独进行空间卷积 |
|
2. 逐点卷积(Pointwise Conv): 1x1卷积实现通道混合 |
|
|
|
Args: |
|
in_channels: 输入通道数 |
|
out_channels: 输出通道数 |
|
stride: 卷积步长 |
|
''' |
|
def __init__(self, in_channels, out_channels, stride=1): |
|
super(Block, self).__init__() |
|
|
|
|
|
self.conv1 = nn.Conv2d( |
|
in_channels=in_channels, |
|
out_channels=in_channels, |
|
kernel_size=3, |
|
stride=stride, |
|
padding=1, |
|
groups=in_channels, |
|
bias=False |
|
) |
|
self.bn1 = nn.BatchNorm2d(in_channels) |
|
self.relu1 = nn.ReLU(inplace=True) |
|
|
|
|
|
self.conv2 = nn.Conv2d( |
|
in_channels=in_channels, |
|
out_channels=out_channels, |
|
kernel_size=1, |
|
stride=1, |
|
padding=0, |
|
bias=False |
|
) |
|
self.bn2 = nn.BatchNorm2d(out_channels) |
|
self.relu2 = nn.ReLU(inplace=True) |
|
|
|
def forward(self, x): |
|
|
|
x = self.conv1(x) |
|
x = self.bn1(x) |
|
x = self.relu1(x) |
|
|
|
|
|
x = self.conv2(x) |
|
x = self.bn2(x) |
|
x = self.relu2(x) |
|
return x |
|
|
|
|
|
class MobileNet(nn.Module): |
|
'''MobileNet v1网络 |
|
|
|
Args: |
|
num_classes: 分类数量 |
|
alpha: 宽度乘子,用于控制网络宽度(默认1.0) |
|
beta: 分辨率乘子,用于控制输入分辨率(默认1.0) |
|
init_weights: 是否初始化权重 |
|
''' |
|
|
|
cfg = [64, (128,2), 128, (256,2), 256, (512,2), |
|
512, 512, 512, 512, 512, (1024,2), 1024] |
|
|
|
def __init__(self, num_classes=10, alpha=1.0, beta=1.0, init_weights=True): |
|
super(MobileNet, self).__init__() |
|
|
|
|
|
self.conv1 = nn.Sequential( |
|
nn.Conv2d(3, 32, kernel_size=3, stride=1, bias=False), |
|
nn.BatchNorm2d(32), |
|
nn.ReLU(inplace=True) |
|
) |
|
|
|
|
|
self.layers = self._make_layers(in_channels=32) |
|
|
|
|
|
self.avg = nn.AdaptiveAvgPool2d(1) |
|
self.linear = nn.Linear(1024, num_classes) |
|
|
|
|
|
if init_weights: |
|
self._initialize_weights() |
|
|
|
def _make_layers(self, in_channels): |
|
'''构建深度可分离卷积层 |
|
|
|
Args: |
|
in_channels: 输入通道数 |
|
''' |
|
layers = [] |
|
for x in self.cfg: |
|
out_channels = x if isinstance(x, int) else x[0] |
|
stride = 1 if isinstance(x, int) else x[1] |
|
layers.append(Block(in_channels, out_channels, stride)) |
|
in_channels = out_channels |
|
return nn.Sequential(*layers) |
|
|
|
def forward(self, x): |
|
|
|
x = self.conv1(x) |
|
|
|
|
|
x = self.layers(x) |
|
|
|
|
|
x = self.avg(x) |
|
x = x.view(x.size(0), -1) |
|
x = self.linear(x) |
|
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') |
|
if m.bias is not None: |
|
nn.init.zeros_(m.bias) |
|
elif isinstance(m, nn.BatchNorm2d): |
|
|
|
nn.init.ones_(m.weight) |
|
nn.init.zeros_(m.bias) |
|
elif isinstance(m, nn.Linear): |
|
|
|
nn.init.normal_(m.weight, 0, 0.01) |
|
nn.init.zeros_(m.bias) |
|
|
|
|
|
def test(): |
|
"""测试函数""" |
|
net = MobileNet() |
|
x = torch.randn(2, 3, 32, 32) |
|
y = net(x) |
|
print(y.size()) |
|
|
|
|
|
from torchinfo import summary |
|
device = 'cuda' if torch.cuda.is_available() else 'cpu' |
|
net = net.to(device) |
|
summary(net, (2, 3, 32, 32)) |
|
|
|
if __name__ == '__main__': |
|
test() |