Pytorch实现VGGNet

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/9/14 13:33
# @Author : Seven
# @Site :
# @File : VGG.py
# @Software: PyCharm

import torch.nn as nn

model = {
'VGG11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'VGG13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
'VGG19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
}


class VGG(nn.Module):
def __init__(self, vgg_name):
super(VGG, self).__init__()
self.features = self._make_layers(model[vgg_name])
self.classifier = nn.Linear(512, 10)

def forward(self, x):
network = self.features(x)
network = network.view(network.size(0), -1)
out = self.classifier(network)
return out, network

@staticmethod
def _make_layers(models):
layers = []
in_channels = 3
for layer in models:
if layer == 'M':
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
else:
layers += [nn.Conv2d(in_channels, layer, kernel_size=3, padding=1),
nn.BatchNorm2d(layer),
nn.ReLU(inplace=True)]
in_channels = layer
layers += [nn.AvgPool2d(kernel_size=1, stride=1)]
return nn.Sequential(*layers)

转载请注明:Seven的博客

本文标题:Pytorch实现VGGNet

文章作者:Seven

发布时间:2018年09月15日 - 00:00:00

最后更新:2018年12月11日 - 22:16:15

原始链接:http://yoursite.com/2018/09/15/2018-09-15-Pytorch-VGGNet/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

------ 本文结束------
坚持原创技术分享,您的支持将鼓励我继续创作!
0%