站点图标 AI技术聚合

经典网络结构 (八):轻量化网络 (SqueezeNet, MobileNet, ShuffleNet)

SqueezeNet

Fire Module: Squeeze and Expand

均代表卷积层输出的通道数,Fire Module 默认

import torch
from torch import nn

class Fire(nn.Module):

    def __init__(self, inplanes, squeeze_planes, expand_planes):
    	# 不改变输入特征图的宽高,只改变通道数
    	# 输入通道数为 inplanes,压缩通道数为 squeeze_planes,输出通道数为 2 * expand_planes
        super(Fire, self).__init__()
        # Squeeze 层
        self.conv1 = nn.Conv2d(inplanes, squeeze_planes, kernel_size=1, stride=1)
        self.bn1 = nn.BatchNorm2d(squeeze_planes)
        self.relu1 = nn.ReLU(inplace=True)
        
        # Expand 层
        self.conv2 = nn.Conv2d(squeeze_planes, expand_planes, kernel_size=1, stride=1)
        self.bn2 = nn.BatchNorm2d(expand_planes)
        self.conv3 = nn.Conv2d(squeeze_planes, expand_planes, kernel_size=3, stride=1, padding=1)
        self.bn3 = nn.BatchNorm2d(expand_planes)
        self.relu2 = nn.ReLU(inplace=True)
    
    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu1(x)
        
        out1 = self.conv2(x)
        out1 = self.bn2(out1)
        out2 = self.conv3(x)
        out2 = self.bn3(out2)
        out = torch.cat([out1, out2], 1)
        out = self.relu2(out)
        return out

SqueezeNet

SqueezeNet 总结

MobileNet

深度可分离卷积 (Depthwise Separable Convolution)

标准卷积

深度可分离卷积

MobileNet v1

深度可分离卷积模块

MobileNet v1 整体结构

代表逐通道卷积 (深度分解卷积),其后需要跟一个卷积;代表步长为 2 的卷积,用于缩小特征图尺寸,起到与 Pooling 层一样的作用

from torch import nn

class MobileNet(nn.Module):
    def __init__(self):
        super(MobileNet, self).__init__()

		# 3 x 3 standard convolution
        def conv_bn(dim_in, dim_out, stride):
            return nn.Sequential(
                nn.Conv2d(dim_in, dim_out, 3, stride, 1, bias=False),
                nn.BatchNorm2d(dim_out),
                nn.ReLU(inplace=True)
            )

		# depthwise separable convolution
        def conv_dw(dim_in, dim_out, stride):
            return nn.Sequential(
            	# use group convolution in PyTorch to implement channel-wise convolution
                nn.Conv2d(dim_in, dim_in, 3, stride, 1, groups=dim_in, bias=False),
                nn.BatchNorm2d(dim_in),
                nn.ReLU(inplace=True),
                nn.Conv2d(dim_in, dim_out, 1, 1, 0, bias=False),
                nn.BatchNorm2d(dim_out),
                nn.ReLU(inplace=True),
            )
           
        self.model = nn.Sequential(
        	# input: 3 x 224 x 224
            conv_bn(  3,  32, 2), 	# 32 x 112 x 112
            conv_dw( 32,  64, 1), 	# 64 x 112 x 112
            conv_dw( 64, 128, 2), 	# 128 x 56 x 56
            conv_dw(128, 128, 1), 	# 128 x 56 x 56
            conv_dw(128, 256, 2), 	# 256 x 28 x 28
            conv_dw(256, 256, 1), 	# 256 x 28 x 28
            conv_dw(256, 512, 2), 	# 512 x 14 x 14
            conv_dw(512, 512, 1), 	# 512 x 14 x 14
            conv_dw(512, 512, 1), 	# 512 x 14 x 14
            conv_dw(512, 512, 1), 	# 512 x 14 x 14
            conv_dw(512, 512, 1), 	# 512 x 14 x 14
            conv_dw(512, 512, 1), 	# 512 x 14 x 14
            conv_dw(512, 1024, 2), 	# 1024 x 7 x 7
            conv_dw(1024, 1024, 1), # 1024 x 7 x 7
            nn.AvgPool2d(7),		# 1024 x 1 x 1
        )
        self.fc = nn.Linear(1024, 1000)

    def forward(self, x):
        x = self.model(x)
        x = x.view(-1, 1024)
        x = self.fc(x)
        return x

MobileNet v1 总结

MobileNet v2

Inverted Residual Block

去掉 ReLU6

import torch.nn as nn
import math

# 标准 3 x 3 卷积
def conv_bn(inp, oup, stride):
    return nn.Sequential(
        nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
        nn.BatchNorm2d(oup),
        nn.ReLU6(inplace=True)
    )

# 标准 1 x 1 卷积
def conv_1x1_bn(inp, oup):
    return nn.Sequential(
        nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
        nn.BatchNorm2d(oup),
        nn.ReLU6(inplace=True)
    )
class InvertedResidual(nn.Module):
    def __init__(self, inp, oup, stride, expand_ratio):
        super(InvertedResidual, self).__init__()
        self.stride = stride
        assert stride in [1, 2]

        hidden_dim = round(inp * expand_ratio)	# 中间扩展层的通道数
        self.use_res_connect = self.stride == 1 and inp == oup

        if expand_ratio == 1:
        	# 不进行升维
            self.conv = nn.Sequential(
                # dw (逐通道卷积)
                nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),
                nn.BatchNorm2d(hidden_dim),
                nn.ReLU6(inplace=True),
                # pw-linear (降维)
                nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
                nn.BatchNorm2d(oup),
            )
        else:
            self.conv = nn.Sequential(
                # pw (升维)
                nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False),
                nn.BatchNorm2d(hidden_dim),
                nn.ReLU6(inplace=True),
                # dw (逐通道卷积)
                nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),
                nn.BatchNorm2d(hidden_dim),
                nn.ReLU6(inplace=True),
                # pw-linear (降维)
                nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
                nn.BatchNorm2d(oup),
            )

    def forward(self, x):
        if self.use_res_connect:
            return x + self.conv(x)
        else:
            return self.conv(x)
class MobileNetV2(nn.Module):
    def __init__(self, n_class=1000, input_size=224, width_mult=1.):
        super(MobileNetV2, self).__init__()
        block = InvertedResidual
        input_channel = 32
        last_channel = 1280
        interverted_residual_setting = [
            # t, c, n, s
            [1, 16, 1, 1],
            [6, 24, 2, 2],
            [6, 32, 3, 2],
            [6, 64, 4, 2],
            [6, 96, 3, 1],
            [6, 160, 3, 2],
            [6, 320, 1, 1],
        ]

        # building first layer
        assert input_size % 32 == 0
        input_channel = int(input_channel * width_mult)
        self.last_channel = int(last_channel * width_mult) if width_mult > 1.0 else last_channel
        self.features = [conv_bn(3, input_channel, 2)]
        # building inverted residual blocks
        for t, c, n, s in interverted_residual_setting:
            output_channel = int(c * width_mult)
            for i in range(n):
                if i == 0:
                    self.features.append(block(input_channel, output_channel, s, expand_ratio=t))
                else:
                    self.features.append(block(input_channel, output_channel, 1, expand_ratio=t))
                input_channel = output_channel
        # building last several layers
        self.features.append(conv_1x1_bn(input_channel, self.last_channel))
        # make it nn.Sequential
        self.features = nn.Sequential(*self.features)

        # building classifier
        self.classifier = nn.Sequential(
            nn.Dropout(0.2),
            nn.Linear(self.last_channel, n_class),
        )

        self._initialize_weights()

    def forward(self, x):
        x = self.features(x)
        x = x.mean(3).mean(2)
        x = self.classifier(x)
        return x

    def _initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
                if m.bias is not None:
                    m.bias.data.zero_()
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
            elif isinstance(m, nn.Linear):
                n = m.weight.size(1)
                m.weight.data.normal_(0, 0.01)
                m.bias.data.zero_()

ShuffleNet

频道洗牌

def channel_shuffle(x, groups):
	batchsize, num_channels, height, width = x.data.size()  
	channels_per_group = num_channels // groups
	# Reshape
	x = x.view(batchsize, groups, channels_per_group, height, width)  
	# Transpose
	x = torch.transpose(x, 1, 2).contiguous()
	# Flatten
	x = x.view(batchsize, -1, height, width)
	return x

ShuffleNet v1

ShuffleNet v1 基本结构单元

ShuffleNet v1 网络整体结构

ShuffleNet v2

建立高性能网络的 4 个基本规则

ShuffleNet v1 的问题

以上述 4 个规则为基础,可以看出ShuffleNet v1 有 3 点违反了此规则:

ShuffleNet v2

参考

文章出处登录后可见!

已经登录?立即刷新
退出移动版