vgg.py 6.15 KB
Newer Older
1
import torch.nn as nn
2
from .utils import load_state_dict_from_url
3
4
5
6
7
8
9
10


__all__ = [
    'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn',
    'vgg19_bn', 'vgg19',
]


11
model_urls = {
12
13
14
15
    'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
    'vgg13': 'https://download.pytorch.org/models/vgg13-c768596a.pth',
    'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth',
    'vgg19': 'https://download.pytorch.org/models/vgg19-dcbb9e9d.pth',
16
17
18
19
    'vgg11_bn': 'https://download.pytorch.org/models/vgg11_bn-6002323d.pth',
    'vgg13_bn': 'https://download.pytorch.org/models/vgg13_bn-abd245e5.pth',
    'vgg16_bn': 'https://download.pytorch.org/models/vgg16_bn-6c64b313.pth',
    'vgg19_bn': 'https://download.pytorch.org/models/vgg19_bn-c79401a0.pth',
20
21
22
}


Soumith Chintala's avatar
Soumith Chintala committed
23
class VGG(nn.Module):
24

25
    def __init__(self, features, num_classes=1000, init_weights=True):
26
27
        super(VGG, self).__init__()
        self.features = features
28
        self.avgpool = nn.AdaptiveAvgPool2d((7, 7))
29
30
31
32
33
34
        self.classifier = nn.Sequential(
            nn.Linear(512 * 7 * 7, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(True),
35
            nn.Dropout(),
Karan Dwivedi's avatar
Karan Dwivedi committed
36
            nn.Linear(4096, num_classes),
37
        )
38
39
        if init_weights:
            self._initialize_weights()
40
41
42

    def forward(self, x):
        x = self.features(x)
43
        x = self.avgpool(x)
44
45
46
47
        x = x.view(x.size(0), -1)
        x = self.classifier(x)
        return x

48
49
50
    def _initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
51
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
52
                if m.bias is not None:
53
                    nn.init.constant_(m.bias, 0)
54
            elif isinstance(m, nn.BatchNorm2d):
55
56
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
57
            elif isinstance(m, nn.Linear):
58
59
                nn.init.normal_(m.weight, 0, 0.01)
                nn.init.constant_(m.bias, 0)
60

61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

def make_layers(cfg, batch_norm=False):
    layers = []
    in_channels = 3
    for v in cfg:
        if v == 'M':
            layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
        else:
            conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
            if batch_norm:
                layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]
            else:
                layers += [conv2d, nn.ReLU(inplace=True)]
            in_channels = v
    return nn.Sequential(*layers)


78
cfgs = {
79
80
81
82
83
84
85
    'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
    'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
}


86
87
88
89
90
91
92
93
94
95
96
97
def _vgg(arch, cfg, batch_norm, pretrained, progress, **kwargs):
    if pretrained:
        kwargs['init_weights'] = False
    model = VGG(make_layers(cfgs[cfg], batch_norm=batch_norm), **kwargs)
    if pretrained:
        state_dict = load_state_dict_from_url(model_urls[arch],
                                              progress=progress)
        model.load_state_dict(state_dict)
    return model


def vgg11(pretrained=False, progress=True, **kwargs):
98
99
100
101
    """VGG 11-layer model (configuration "A")

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
102
        progress (bool): If True, displays a progress bar of the download to stderr
103
    """
104
    return _vgg('vgg11', 'A', False, pretrained, progress, **kwargs)
105
106


107
def vgg11_bn(pretrained=False, progress=True, **kwargs):
108
109
110
111
    """VGG 11-layer model (configuration "A") with batch normalization

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
112
        progress (bool): If True, displays a progress bar of the download to stderr
113
    """
114
    return _vgg('vgg11_bn', 'A', True, pretrained, progress, **kwargs)
115
116


117
def vgg13(pretrained=False, progress=True, **kwargs):
118
119
120
121
    """VGG 13-layer model (configuration "B")

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
122
        progress (bool): If True, displays a progress bar of the download to stderr
123
    """
124
    return _vgg('vgg13', 'B', False, pretrained, progress, **kwargs)
125
126


127
def vgg13_bn(pretrained=False, progress=True, **kwargs):
128
129
130
131
    """VGG 13-layer model (configuration "B") with batch normalization

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
132
        progress (bool): If True, displays a progress bar of the download to stderr
133
    """
134
    return _vgg('vgg13_bn', 'B', True, pretrained, progress, **kwargs)
135
136


137
def vgg16(pretrained=False, progress=True, **kwargs):
138
139
140
141
    """VGG 16-layer model (configuration "D")

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
142
        progress (bool): If True, displays a progress bar of the download to stderr
143
    """
144
    return _vgg('vgg16', 'D', False, pretrained, progress, **kwargs)
145
146


147
def vgg16_bn(pretrained=False, progress=True, **kwargs):
148
149
150
151
    """VGG 16-layer model (configuration "D") with batch normalization

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
152
        progress (bool): If True, displays a progress bar of the download to stderr
153
    """
154
    return _vgg('vgg16_bn', 'D', True, pretrained, progress, **kwargs)
155
156


157
def vgg19(pretrained=False, progress=True, **kwargs):
158
159
160
161
    """VGG 19-layer model (configuration "E")

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
162
        progress (bool): If True, displays a progress bar of the download to stderr
163
    """
164
    return _vgg('vgg19', 'E', False, pretrained, progress, **kwargs)
165
166


167
def vgg19_bn(pretrained=False, progress=True, **kwargs):
168
169
170
171
    """VGG 19-layer model (configuration 'E') with batch normalization

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
172
        progress (bool): If True, displays a progress bar of the download to stderr
173
    """
174
    return _vgg('vgg19_bn', 'E', True, pretrained, progress, **kwargs)