基本的图像分类网络学习——MobileNetV2

本文深入解析了MobileNetV2的网络结构,包括其Inverted Residual Blocks的设计,并提供了详细的PyTorch实现代码。通过实例展示了如何构建和初始化模型参数,有助于读者理解和应用MobileNetV2。
摘要由CSDN通过智能技术生成

系列文章目录

提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加
例如:第一章 Python 机器学习入门之pandas的使用


提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

MobileNetV2是谷歌开发的移动端使用的神经网络,是一个系列的,V1,V2,V3,具体看这介绍,这里就着重讲解下MobileNetV2的结构,主要是这种图用的挺多的我一下是没看明白咋回事,这就仔细研究一下


提示:以下是本篇文章正文内容,下面案例可供参考

一、MobileNetV2 结构图

示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。

二、表格参数进行解释

Input : 输入数据的尺寸

Operator:操作

conv2d 33: 进行2维卷积,带有normal和Relu6的,默认内核大小33 CONV1D,2D,3D的区别
bottleneck: 见下面的图
conv2d 11
avgpool 7
7

t :表示了扩展的通道数,就是将通到用1*1卷积升到原来的几倍
c: 设置当前操作块的输出的通道数目
n:设置当前操作块的的个数
s: 设置当前操作块的步长,注意这个步长只是重复模块的第一个模块的步长其他模块步长都为1

bottleneck的解释

代码实现-pytorch版本

from torch import nn
import torch
from torchvision.ops import misc


def _make_divisible(ch, divisor=8, min_ch=None):
    """
    This function is taken from the original tf repo.
    It ensures that all layers have a channel number that is divisible by 8
    It can be seen here:
    https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
    """
    if min_ch is None:
        min_ch = divisor
    new_ch = max(min_ch, int(ch + divisor / 2) // divisor * divisor)
    # Make sure that round down does not go down by more than 10%.
    if new_ch < 0.9 * ch:
        new_ch += divisor
    return new_ch


class ConvBNReLU(nn.Sequential):
    def __init__(self, in_channel, out_channel, kernel_size=3, stride=1, groups=1, norm_layer=None):
        padding = (kernel_size - 1) // 2
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        super(ConvBNReLU, self).__init__(
            nn.Conv2d(in_channel, out_channel, kernel_size, stride, padding, groups=groups, bias=False),
            norm_layer(out_channel),
            nn.ReLU6(inplace=True)
        )


class InvertedResidual(nn.Module):
    def __init__(self, in_channel, out_channel, stride, expand_ratio, norm_layer=None):
        super(InvertedResidual, self).__init__()
        hidden_channel = in_channel * expand_ratio
        self.use_shortcut = stride == 1 and in_channel == out_channel
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d

        layers = []
        # 如果为扩展1倍的话可以省略该层,减少运算奥
        if expand_ratio != 1:
            # 1x1 pointwise conv
            layers.append(ConvBNReLU(in_channel, hidden_channel, kernel_size=1, norm_layer=norm_layer))
        layers.extend([
            # 3x3 depthwise conv
            ConvBNReLU(hidden_channel, hidden_channel, stride=stride, groups=hidden_channel, norm_layer=norm_layer),
            # 1x1 pointwise conv(linear)
            nn.Conv2d(hidden_channel, out_channel, kernel_size=1, bias=False),
            norm_layer(out_channel),
        ])

        self.conv = nn.Sequential(*layers)

    def forward(self, x):
        # 只用stride为1时候可以使用shotcut,桥接
        if self.use_shortcut:
            return x + self.conv(x)
        else:
            return self.conv(x)


class MobileNetV2(nn.Module):
    def __init__(self, num_classes=1000, alpha=1.0, round_nearest=8, weights_path=None, norm_layer=None):
        super(MobileNetV2, self).__init__()
        block = InvertedResidual
        # 把输出的通道扩展为8的整数倍
        input_channel = _make_divisible(32 * alpha, round_nearest)
        last_channel = _make_divisible(1280 * alpha, round_nearest)
        # 归一化层
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        # InvertedResidual的参数设置:t是扩展通道数,c输出通道数,n表示了模块个数,s表示第一个模块的步长为,其他的都为1
        inverted_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],
        ]
        # 定义特征层矩阵
        features = []
        # 第一层进行卷积 conv1 layer
        features.append(ConvBNReLU(3, input_channel, stride=2, norm_layer=norm_layer))
        # building inverted residual residual blockes
        # 进行到残差结构特征层添加
        for t, c, n, s in inverted_residual_setting:
            output_channel = _make_divisible(c * alpha, round_nearest)
            for i in range(n):
                stride = s if i == 0 else 1
                features.append(block(input_channel, output_channel, stride, expand_ratio=t, norm_layer=norm_layer))
                input_channel = output_channel
        # building last several layers
        # 使用1*1卷积核进行卷积
        features.append(ConvBNReLU(input_channel, last_channel, 1, norm_layer=norm_layer))
        # combine feature layers
        # 往sequential里传入各个层
        self.features = nn.Sequential(*features)
        # 池化
        # building classifier
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        # 分类
        self.classifier = nn.Sequential(
            nn.Dropout(0.2),
            nn.Linear(last_channel, num_classes)
        )

        if weights_path is None:
            # weight initialization
            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)
        else:
            self.load_state_dict(torch.load(weights_path))

    def forward(self, x):
        x = self.features(x)
        x = self.avgpool(x)
        x = torch.flatten(x, 1)
        x = self.classifier(x)
        return x
  • 实现网络结构可以分别继承(nn.Module)和(nn.Sequential)方法,nn.modoule需要实现forward方法,(nn.Sequential):只要初始化的时候传入层的数组就可以了
  • 当t=1时候可以忽略一个1*1卷积层,因为没有进行通道扩展,同时也可以减少模型复杂度
  • 可以在初始化的时候 self.modules()来初始化各个层的参数

总结

提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

不被定义的号

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

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

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

打赏作者

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

抵扣说明:

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

余额充值