轻量化网络 Mobilenet V1/V2/V3(原理+pytorch代码)

参考视频

2016年直至现在,业内提出了SqueezeNet、ShuffleNet、NasNet、MnasNet以及MobileNet等轻量级网络模型。这些模型使移动终端、嵌入式设备运行神经网络模型成为可能。

V1(DW卷积)->V2(逆残差)->V3(SEattention)

1. 传统卷积

在这里插入图片描述

  • 输入特征in_channel=卷积核的channel
  • 输出特征图的out_channnel=卷积核的个数
    在这里插入图片描述
    计算量图像大小HW卷积核大小有关
    在这里插入图片描述
    在这里插入图片描述

2. Mobilenet V1

2个亮点:

  • DepthWise Separable卷积(深度可分离卷积)大大减少运算量:DW卷积+PW卷积
  • 增加超参数alpha(控制卷积核个数)和beta(控制输入图像大小WH)

2.1 DepthWise Separable卷积

D W 卷积 ( 增大感受野,缩小特征图 W H ) + P W 卷积 ( 缩放特征图通道数 C ) DW卷积(增大感受野,缩小特征图WH)+PW卷积(缩放特征图通道数C) DW卷积(增大感受野,缩小特征图WH)+PW卷积(缩放特征图通道数C)
Step1:逐通道独立卷积(DepthWise卷积)
一个卷积核负责一个通道

  • 卷积核个数 = 输入特征图的in_channel = 输出特征图的out_channel
  • 卷积核的channnel = 1
    在这里插入图片描述
    在这里插入图片描述

Step2:逐点卷积(Pointwise卷积)
卷积核1x1的普通卷积,省参数,N个卷积核得到N个特征图
在这里插入图片描述
Step3:串联DW卷积和PW卷积
两步走的Separable卷积效果普通卷积相似,但计算量大大减小
在这里插入图片描述

深度可分离卷积 VS 普通卷积
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.2 整体结构

在这里插入图片描述
mobilenet v1一路卷积到底(单分支DW卷积块串行),但训练后DW卷积核很多参数为0,效果不理想。

3. Mobilenet V2

在这里插入图片描述

3.1 逆残差

  • DW卷积:不改变通道数,但可缩小特征图WH
  • 1x1卷积:不改变特征图WH,但可缩放通道数C

在这里插入图片描述

  • 原始残差:先降维,后升维。两边厚,中间薄。
  • 逆残差:先升维,后降维。两部薄,中间厚。

在这里插入图片描述

激活函数使用ReLU6:对ReLU设置max(6)
在这里插入图片描述

3.2 Relu干了坏事

Relu使 低维特征 损失信息
在这里插入图片描述
逆残差块输出的是低位特征图(通道维度小),所以在输出时需要使用线性linear激活函数,避免信息损失,而在逆残差块其他部分,仍然使用ReLU6激活函数。
在这里插入图片描述

3.3 整体结构

此处的bottleneck就是逆残差块,单分支一路卷积到底,bottleneck内部可能有shortcut。
在这里插入图片描述

4. Mobilenet V3

亮点:

  • 更新bottleneck:引入SE attention,非线性激活函数NL将swish改为h-swish,用于替代relu6
  • 使用NAS搜索参数(Neural Architecture Search)
  • 重新设置耗时层(对搜索出来的网络逐层分析优化)

4.1 更新bottleneck

在这里插入图片描述

①SE Attention
在这里插入图片描述
在这里插入图片描述

Step1:求每个通道的权重值(1x1xc)(全局平均池化)
在这里插入图片描述

Step2:使用两个全连接层计算权重值的回归值sc(1x1xc),然后完成加权操作(每个通道权重回归值sc x 每个通道原始特征图uc)

在这里插入图片描述

②Switch激活函数
基于Switch提出h-Switch激活函数,用于替代mobilenetV2中的relu6。
S w i t c h ( x ) = x ∗ s i g m o i d ( x ) Switch(x)=x*sigmoid(x) Switch(x)=xsigmoid(x)
在这里插入图片描述
h − s i g m o i d ( x ) = r e l u 6 ( x + 3 ) / 6 h-sigmoid(x)=relu6(x+3)/6 hsigmoid(x)=relu6(x+3)/6

h − S w i t c h ( x ) = x ∗ h − s i g m o i d ( x ) = x ∗ r e l u 6 ( x + 3 ) / 6 h-Switch(x)=x*h-sigmoid(x)=x*relu6(x+3)/6 hSwitch(x)=xhsigmoid(x)=xrelu6(x+3)/6
在这里插入图片描述

4.2 重新设置耗时层

因为实验发现第一个卷积操作最后的卷积操作才是耗时性能瓶颈,所以减少了第一个卷积层的output channel从32到16,且减少最后两层卷积层数量
在这里插入图片描述

4.3 整体结构

在这里插入图片描述
在这里插入图片描述

5. Mobilenet V3 代码

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init



class hswish(nn.Module):
    def forward(self, x):
        out = x * F.relu6(x + 3, inplace=True) / 6
        return out


class hsigmoid(nn.Module):
    def forward(self, x):
        out = F.relu6(x + 3, inplace=True) / 6
        return out


class SeModule(nn.Module):
    def __init__(self, in_size, reduction=4):
        super(SeModule, self).__init__()
        self.se = nn.Sequential(
            nn.AdaptiveAvgPool2d(1),
            nn.Conv2d(in_size, in_size // reduction, kernel_size=1, stride=1, padding=0, bias=False),
            nn.BatchNorm2d(in_size // reduction),
            nn.ReLU(inplace=True),
            nn.Conv2d(in_size // reduction, in_size, kernel_size=1, stride=1, padding=0, bias=False),
            nn.BatchNorm2d(in_size),
            hsigmoid()
        )

    def forward(self, x):
        return x * self.se(x)


class Block(nn.Module):
    '''expand + depthwise + pointwise'''
    def __init__(self, kernel_size, in_size, expand_size, out_size, nolinear, semodule, stride):
        super(Block, self).__init__()
        self.stride = stride
        self.se = semodule

        self.conv1 = nn.Conv2d(in_size, expand_size, kernel_size=1, stride=1, padding=0, bias=False)
        self.bn1 = nn.BatchNorm2d(expand_size)
        self.nolinear1 = nolinear
        self.conv2 = nn.Conv2d(expand_size, expand_size, kernel_size=kernel_size, stride=stride, padding=kernel_size//2, groups=expand_size, bias=False)
        self.bn2 = nn.BatchNorm2d(expand_size)
        self.nolinear2 = nolinear
        self.conv3 = nn.Conv2d(expand_size, out_size, kernel_size=1, stride=1, padding=0, bias=False)
        self.bn3 = nn.BatchNorm2d(out_size)

        self.shortcut = nn.Sequential()
        if stride == 1 and in_size != out_size:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_size, out_size, kernel_size=1, stride=1, padding=0, bias=False),
                nn.BatchNorm2d(out_size),
            )

    def forward(self, x):
        out = self.nolinear1(self.bn1(self.conv1(x)))
        out = self.nolinear2(self.bn2(self.conv2(out)))
        out = self.bn3(self.conv3(out))
        if self.se != None:
            out = self.se(out)
        out = out + self.shortcut(x) if self.stride==1 else out
        return out


class MobileNetV3_Large(nn.Module):
    def __init__(self, num_classes=1000):
        super(MobileNetV3_Large, self).__init__()
        self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=2, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(16)
        self.hs1 = hswish()

        self.bneck = nn.Sequential(
            Block(3, 16, 16, 16, nn.ReLU(inplace=True), None, 1),
            Block(3, 16, 64, 24, nn.ReLU(inplace=True), None, 2),
            Block(3, 24, 72, 24, nn.ReLU(inplace=True), None, 1),
            Block(5, 24, 72, 40, nn.ReLU(inplace=True), SeModule(40), 2),
            Block(5, 40, 120, 40, nn.ReLU(inplace=True), SeModule(40), 1),
            Block(5, 40, 120, 40, nn.ReLU(inplace=True), SeModule(40), 1),
            Block(3, 40, 240, 80, hswish(), None, 2),
            Block(3, 80, 200, 80, hswish(), None, 1),
            Block(3, 80, 184, 80, hswish(), None, 1),
            Block(3, 80, 184, 80, hswish(), None, 1),
            Block(3, 80, 480, 112, hswish(), SeModule(112), 1),
            Block(3, 112, 672, 112, hswish(), SeModule(112), 1),
            Block(5, 112, 672, 160, hswish(), SeModule(160), 1),
            Block(5, 160, 672, 160, hswish(), SeModule(160), 2),
            Block(5, 160, 960, 160, hswish(), SeModule(160), 1),
        )


        self.conv2 = nn.Conv2d(160, 960, kernel_size=1, stride=1, padding=0, bias=False)
        self.bn2 = nn.BatchNorm2d(960)
        self.hs2 = hswish()
        self.linear3 = nn.Linear(960, 1280)
        self.bn3 = nn.BatchNorm1d(1280)
        self.hs3 = hswish()
        self.linear4 = nn.Linear(1280, num_classes)
        self.init_params()

    def init_params(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                init.kaiming_normal_(m.weight, mode='fan_out')
                if m.bias is not None:
                    init.constant_(m.bias, 0)
            elif isinstance(m, nn.BatchNorm2d):
                init.constant_(m.weight, 1)
                init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                init.normal_(m.weight, std=0.001)
                if m.bias is not None:
                    init.constant_(m.bias, 0)

    def forward(self, x):
        out = self.hs1(self.bn1(self.conv1(x)))
        out = self.bneck(out)
        out = self.hs2(self.bn2(self.conv2(out)))
        out = F.avg_pool2d(out, 7)
        out = out.view(out.size(0), -1)
        out = self.hs3(self.bn3(self.linear3(out)))
        out = self.linear4(out)
        return out



class MobileNetV3_Small(nn.Module):
    def __init__(self, num_classes=1000):
        super(MobileNetV3_Small, self).__init__()
        self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=2, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(16)
        self.hs1 = hswish()

        self.bneck = nn.Sequential(
            Block(3, 16, 16, 16, nn.ReLU(inplace=True), SeModule(16), 2),
            Block(3, 16, 72, 24, nn.ReLU(inplace=True), None, 2),
            Block(3, 24, 88, 24, nn.ReLU(inplace=True), None, 1),
            Block(5, 24, 96, 40, hswish(), SeModule(40), 2),
            Block(5, 40, 240, 40, hswish(), SeModule(40), 1),
            Block(5, 40, 240, 40, hswish(), SeModule(40), 1),
            Block(5, 40, 120, 48, hswish(), SeModule(48), 1),
            Block(5, 48, 144, 48, hswish(), SeModule(48), 1),
            Block(5, 48, 288, 96, hswish(), SeModule(96), 2),
            Block(5, 96, 576, 96, hswish(), SeModule(96), 1),
            Block(5, 96, 576, 96, hswish(), SeModule(96), 1),
        )


        self.conv2 = nn.Conv2d(96, 576, kernel_size=1, stride=1, padding=0, bias=False)
        self.bn2 = nn.BatchNorm2d(576)
        self.hs2 = hswish()
        self.linear3 = nn.Linear(576, 1280)
        self.bn3 = nn.BatchNorm1d(1280)
        self.hs3 = hswish()
        self.linear4 = nn.Linear(1280, num_classes)
        self.init_params()

    def init_params(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                init.kaiming_normal_(m.weight, mode='fan_out')
                if m.bias is not None:
                    init.constant_(m.bias, 0)
            elif isinstance(m, nn.BatchNorm2d):
                init.constant_(m.weight, 1)
                init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                init.normal_(m.weight, std=0.001)
                if m.bias is not None:
                    init.constant_(m.bias, 0)

    def forward(self, x):
        out = self.hs1(self.bn1(self.conv1(x)))
        out = self.bneck(out)
        out = self.hs2(self.bn2(self.conv2(out)))
        out = F.avg_pool2d(out, 7)
        out = out.view(out.size(0), -1)
        out = self.hs3(self.bn3(self.linear3(out)))
        out = self.linear4(out)
        return out



def test():
    net = MobileNetV3_Small()
    x = torch.randn(2,3,224,224)
    y = net(x)
    print(y.size())

test()
### 如何在 PyTorch 中实现 MobileNetV3 网络结构 为了构建 MobileNetV3,在 PyTorch 中可以定义一系列模块来表示网络的不同部分。下面是一个简化版的 `MobileNetV3` 实现,它基于已有的研究和开源项目[^1]。 #### 定义基础组件 首先定义一些必要的组件,比如卷积层、批量归一化以及激活函数 h-swish 和 ReLU: ```python import torch.nn as nn import torch class Hswish(nn.Module): def __init__(self, inplace=True): super(Hswish, self).__init__() self.inplace = inplace def forward(self, x): return x * F.relu6(x + 3., inplace=self.inplace) / 6. def conv_3x3_bn(inp, oup, stride): return nn.Sequential( nn.Conv2d(inp, oup, 3, stride, 1, bias=False), nn.BatchNorm2d(oup), Hswish() ) ``` #### 构建瓶颈 (Bottleneck) 接着创建一个类用于生成每个阶段内的瓶颈单元(bneck),这是 MobileNetV3 的核心组成部分之一: ```python class Bottleneck(nn.Module): def __init__(self, inp, oup, kernel, exp_size, se, nl, s): super(Bottleneck, self).__init__() assert s in [1, 2] hidden_dim = exp_size layers = [] # pw if inp != hidden_dim: layers.append(nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False)) layers.append(nn.BatchNorm2d(hidden_dim)) if nl == "RE": layers.append(nn.ReLU(inplace=True)) elif nl == "HS": layers.append(Hswish()) layers.extend([ # dw nn.Conv2d(hidden_dim, hidden_dim, kernel, s, kernel//2, groups=hidden_dim, bias=False), nn.BatchNorm2d(hidden_dim), # SE SELayer(hidden_dim) if se else nn.Identity(), # pw-linear nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False), nn.BatchNorm2d(oup), ]) if nl == "RE": layers.append(nn.ReLU(inplace=True)) elif nl == "HS": layers.append(Hswish()) self.conv = nn.Sequential(*layers) self.use_res_connect = s == 1 and inp == oup def forward(self, x): out = self.conv(x) if self.use_res_connect: return x + out else: return out ``` 这里还涉及到 Squeeze-and-Excitation(SE) 层的设计,这有助于提高模型性能[^4]: ```python class SELayer(nn.Module): def __init__(self, channel, reduction=4): super(SELayer, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequential( nn.Linear(channel, channel // reduction, bias=False), nn.ReLU(inplace=True), nn.Linear(channel // reduction, channel, bias=False), Hsigmoid() # or use sigmoid activation function ) def forward(self, x): b, c, _, _ = x.size() y = self.avg_pool(x).view(b, c) y = self.fc(y).view(b, c, 1, 1) return x * y.expand_as(x) ``` 最后组合上述所有部件完成整个 MobileNetV3 结构的搭建,并提供预训练权重加载功能以便快速上手使用[^2]。 ```python cfgs_large = [ # k, t, c, SE, NL, s [3, 16, 16, False, 'RE', 1], [3, 64, 24, False, 'RE', 2], ... ] class MobileNetV3_Large(nn.Module): def __init__(num_classes=1000): super(MobileNetV3_Large, self).__init__() self.features = make_layers(cfgs_large) self.classifier = nn.Sequential( nn.Linear(last_channel, num_classes), ) def forward(self, x): x = self.features(x) x = x.mean([2, 3]) # global average pooling x = self.classifier(x) return x def make_layers(cfgs): layers = [conv_3x3_bn(3, cfgs[0][1], 2)] for k, exp_size, c, use_se, nl, s in cfgs: output_channels = c layers.append(Bottleneck(input_channel, output_channels, k, exp_size, use_se, nl, s)) input_channel = output_channels return nn.Sequential(*layers) model = MobileNetV3_Large().to(device) pretrained_dict = torch.load('path_to_pretrained_weights.pth') model.load_state_dict(pretrained_dict) ``` 以上就是利用 PyTorch 来实现 MobileNetV3 大型版本的一个简单例子。实际应用中可能还需要考虑更多细节优化等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yuezero_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值