shufflenetv1 pytorch代码
时间: 2023-09-03 11:15:51 浏览: 66
以下是ShuffleNetV1的PyTorch代码实现,包括ShuffleNetV1的网络结构和训练代码:
```python
import torch.nn as nn
import math
__all__ = ['ShuffleNetV1', 'shufflenetv1']
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock(nn.Module):
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ShuffleNetV1(nn.Module):
def __init__(self, num_classes=1000, groups=3, width_mult=1):
super(ShuffleNetV1, self).__init__()
self.groups = groups
self.stage_repeats = [3, 7, 3]
if groups == 1:
self.stage_out_channels = [-1, 24, 144, 288, 576]
elif groups == 2:
self.stage_out_channels = [-1, 24, 200, 400, 800]
elif groups == 3:
self.stage_out_channels = [-1, 24, 240, 480, 960]
elif groups == 4:
self.stage_out_channels = [-1, 24, 272, 544, 1088]
elif groups == 8:
self.stage_out_channels = [-1, 24, 384, 768, 1536]
else:
raise ValueError("""{} groups is not supported for
1x1 Grouped Convolutions""".format(num_groups))
# building first layer
input_channels = 3
output_channels = self.stage_out_channels[1]
output_channels = int(output_channels * width_mult)
self.conv1 = nn.Conv2d(input_channels, output_channels, kernel_size=3, stride=2, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(output_channels)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
# building stages
self.stage2 = self._make_stage(2, width_mult)
self.stage3 = self._make_stage(3, width_mult)
self.stage4 = self._make_stage(4, width_mult)
# building last several layers
self.conv_last = nn.Conv2d(self.stage_out_channels[-2], self.stage_out_channels[-1], kernel_size=1, stride=1, padding=0, bias=False)
self.globalpool = nn.AvgPool2d(7)
self.fc = nn.Linear(self.stage_out_channels[-1], num_classes)
def _make_stage(self, stage, width_mult):
modules = OrderedDict()
stage_name = "ShuffleUnit_Stage{}".format(stage)
# stage_repeats = self.stage_repeats[stage]
unit1 = ShuffleUnit(self.stage_out_channels[stage-1], self.stage_out_channels[stage], 2, groups=self.groups, width_mult=width_mult)
modules[stage_name+"_unit1"] = unit1
for i in range(self.stage_repeats[stage-2]):
name = stage_name + "_unit" + str(i+2)
module = ShuffleUnit(self.stage_out_channels[stage], self.stage_out_channels[stage], 1, groups=self.groups, width_mult=width_mult)
modules[name] = module
return nn.Sequential(modules)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.stage2(x)
x = self.stage3(x)
x = self.stage4(x)
x = self.conv_last(x)
x = self.globalpool(x)
x = x.view(-1, self.stage_out_channels[-1])
x = self.fc(x)
return x
class ShuffleUnit(nn.Module):
def __init__(self, in_channels, out_channels, stride, groups=3, width_mult=1):
super(ShuffleUnit, self).__init__()
if stride != 1 or in_channels != out_channels:
self.use_res_connect = False
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=stride, padding=1, groups=in_channels, bias=False),
nn.BatchNorm2d(in_channels),
nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
)
else:
self.use_res_connect = True
self.shortcut = nn.Sequential()
self.groups = groups
mid_channels = int(out_channels / 4 * width_mult)
self.conv1 = nn.Conv2d(in_channels, mid_channels, kernel_size=1, stride=1, padding=0, bias=False)
self.bn1 = nn.BatchNorm2d(mid_channels)
self.conv2 = nn.Conv2d(mid_channels, mid_channels, kernel_size=3, stride=stride, padding=1, groups=groups, bias=False)
self.bn2 = nn.BatchNorm2d(mid_channels)
self.conv3 = nn.Conv2d(mid_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=False)
self.bn3 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU(inplace=True)
def _channel_shuffle(self, x, groups):
batchsize, num_channels, height, width = x.data.size()
channels_per_group = num_channels // groups
x = x.view(batchsize, groups, channels_per_group, height, width)
x = torch.transpose(x, 1, 2).contiguous()
x = x.view(batchsize, -1, height, width)
return x
def forward(self, x):
if self.use_res_connect:
shortcut = x
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.relu(x)
x = self._channel_shuffle(x, self.groups)
x = self.conv3(x)
x = self.bn3(x)
if self.use_res_connect:
shortcut = self.shortcut(shortcut)
x += shortcut
x = self.relu(x)
return x
def shufflenetv1(**kwargs):
"""
Constructs a ShuffleNetV1 model
"""
return ShuffleNetV1(**kwargs)
```
在使用ShuffleNetV1时,可以通过以下方式进行实例化:
```python
import torch
from shufflenetv1 import shufflenetv1
model = shufflenetv1(groups=3, width_mult=1)
input = torch.randn(1, 3, 224, 224)
output = model(input)
print(output.shape)
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)