File size: 4,982 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
'''
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__()
        
        # 深度卷积 - 每个通道单独进行3x3卷积
        self.conv1 = nn.Conv2d(
            in_channels=in_channels,
            out_channels=in_channels,
            kernel_size=3,
            stride=stride,
            padding=1,
            groups=in_channels,  # groups=in_channels 即为深度可分离卷积
            bias=False
        )
        self.bn1 = nn.BatchNorm2d(in_channels)
        self.relu1 = nn.ReLU(inplace=True)

        # 逐点卷积 - 1x1卷积用于通道混合
        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: 是否初始化权重
    '''
    # 网络配置: (输出通道数, 步长),步长默认为1
    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)  # 自适应平均池化,输出大小为1x1
        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):
                # 使用kaiming初始化卷积层
                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):
                # 初始化BN层
                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()