系列文章目录
提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加
例如:第一章 Python 机器学习入门之pandas的使用
提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
MobileNetV2是谷歌开发的移动端使用的神经网络,是一个系列的,V1,V2,V3,具体看这介绍,这里就着重讲解下MobileNetV2的结构,主要是这种图用的挺多的我一下是没看明白咋回事,这就仔细研究一下
提示:以下是本篇文章正文内容,下面案例可供参考
一、MobileNetV2 结构图
二、表格参数进行解释
Input : 输入数据的尺寸
Operator:操作
conv2d 33: 进行2维卷积,带有normal和Relu6的,默认内核大小33 CONV1D,2D,3D的区别
bottleneck: 见下面的图
conv2d 11
avgpool 77t :表示了扩展的通道数,就是将通到用1*1卷积升到原来的几倍
c: 设置当前操作块的输出的通道数目
n:设置当前操作块的的个数
s: 设置当前操作块的步长,注意这个步长只是重复模块的第一个模块的步长其他模块步长都为1
代码实现-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提供了大量能使我们快速便捷地处理数据的函数和方法。