Mobilenetv2
时间: 2025-03-02 11:59:54 浏览: 103
### MobilenetV2架构
MobilenetV2是一种高效的卷积神经网络,专为移动设备设计,在保持高精度的同时显著减少了计算量和参数数量。该网络引入了倒残差结构(Inverted Residuals)和线性瓶颈(Linear Bottlenecks),这些特性使得模型更加轻量化且易于部署[^4]。
#### 架构特点
- **倒残差模块**:传统残差连接位于较宽层之后,而MobilenetV2则相反,将窄层置于更宽的膨胀层之前。
- **逐点卷积与深度可分离卷积组合**:通过先执行1×1卷积再做3×3深度可分离卷积的方式减少运算次数。
- **ReLU6激活函数**:为了防止数值溢出并加速收敛速度,采用ReLU6作为默认激活器。
```python
import torch.nn as nn
class ConvBNReLU(nn.Sequential):
def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, groups=1):
padding = (kernel_size - 1) // 2
super(ConvBNReLU, self).__init__(
nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, bias=False),
nn.BatchNorm2d(out_planes),
nn.ReLU6(inplace=True)
)
```
### 实现代码
以下是使用PyTorch框架构建MobilenetV2的一个简化版本:
```python
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
"""
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down by more than 10%.
if new_v < 0.9 * v:
new_v += divisor
return new_v
class InvertedResidual(nn.Module):
def __init__(self, inp, oup, stride, expand_ratio):
super(InvertedResidual, self).__init__()
hidden_dim = int(round(inp * expand_ratio))
self.use_res_connect = stride == 1 and inp == oup
layers = []
if expand_ratio != 1:
# pw
layers.append(ConvBNReLU(inp, hidden_dim, kernel_size=1))
layers.extend([
# dw
ConvBNReLU(hidden_dim, hidden_dim, stride=stride, groups=hidden_dim),
# pw-linear
nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
nn.BatchNorm2d(oup),
])
self.conv = nn.Sequential(*layers)
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, num_classes=1000, width_mult=1.0):
super(MobileNetV2, self).__init__()
block = InvertedResidual
input_channel = 32
last_channel = 1280
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],
]
# building first layer
input_channel = _make_divisible(input_channel * width_mult, 8)
self.last_channel = _make_divisible(last_channel * max(1.0, width_mult), 8)
features = [ConvBNReLU(3, input_channel, stride=2)]
# building inverted residual blocks
for t, c, n, s in inverted_residual_setting:
output_channel = _make_divisible(c * width_mult, 8)
for i in range(n):
stride = s if i == 0 else 1
features.append(block(input_channel, output_channel, stride, expand_ratio=t))
input_channel = output_channel
# building last several layers
features.append(ConvBNReLU(input_channel, self.last_channel, kernel_size=1))
# make it nn.Sequential
self.features = nn.Sequential(*features)
# building classifier
self.classifier = nn.Sequential(
nn.Dropout(0.2),
nn.Linear(self.last_channel, num_classes),
)
# 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)
def forward(self, x):
x = self.features(x)
x = x.mean([2, 3]) # global average pooling
x = self.classifier(x)
return x
```
### 预训练模型下载
对于希望直接利用已有的预训练权重来加快开发进度或提高性能的研究者来说,可以直接从官方资源获取预训练好的MobilenetV2模型。例如,在PyTorch环境中可以通过`torchvision.models.mobilenet_v2(pretrained=True)`轻松加载ImageNet上预先训练过的模型实例[^2]。
### 使用教程
当获得了一个预训练的MobilenetV2模型后,可以根据具体应用场景调整最后一层全连接层以适应新的类别数,并继续微调整个网络或者仅冻结前面几层只更新新增加的部分。此外还可以探索其他高级技巧如数据增强、正则化方法等进一步提升泛化能力。
阅读全文
相关推荐

















