vgg网络
vgg网络由于其具有较强的特征提取能力,被广泛作为一个基本的模块组合在其他的网络中,而pytorch对它的实现尤为简单,下面分析一下源码实现。
# A B D E网络分别表示vgg11, vgg13, vgg16, vgg19网络,其中vgg16和vgg19网络的使用最为频繁,由于vgg网络的基本组成单元较简单,所以其实现也具有优美的架构,其中卷积网络都是stride为1,kernel size为3,padding为1的卷积,该卷积输入输出保持不变,而池化层则使用的是最大池化层,stride为2,kernel size为2
cfg = {
'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'],
}
# VGG16 2*2+3*3+3=16
# make_layers构成了vgg网络的特征层,输入为上述cfg,比如vgg16为D,那么首先输入channels为RGB三通道图像,增加每一层使用nn.Sequential可以顺序连接这些网络
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)
由于VGG的不同类别仅仅在前面的特征层不同,剩下为三个全连接层,按照如下组合即可,那么这里与其他网络不同的是,这里的features和classifier并不是网络通用的,仅仅代表VGG网络前面的卷积特征层和最后的全连接分类层。
class VGG(nn.Module):
def __init__(self, features, num_classes=1000):
super(VGG, self).__init__()
self.features = features
# 此处因为VGG网络输入为224x224,所以分类器的输入为1x25088
# 如果输入为32x32,那么分类起flat为512*1*1,分类器4096也可以修改,根据具体的分类数据集可以修改更小比如512,最后的num_classes为分类的种类
self.classifier = nn.Sequential(
nn.Linear(512 * 7 * 7, 4096),
nn.ReLU(True),
nn.Dropout(),
nn.Linear(4096, 4096),
nn.ReLU(True),
nn.Dropout(),
nn.Linear(4096, num_classes),
)
self._initialize_weights()
def forward(self, x):
x = self.features(x)
# 第一项为batch size,其余应该叠加在一起,所以用-1表示
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
# 任何网络构造过程中同时需要进行初始化
def _initialize_weights(self):
for m in self.modules():
# 不同的网络类型初始化均不同,比如Conv2d卷积层的权值初始化为均值为0,偏置为0
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
if m.bias is not None:
m.bias.data.zero_()
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
m.weight.data.normal_(0, 0.01)
m.bias.data.zero_()
上面同样需要注意的是pytorch中卷积层的初始化和BatchNorm2d层的初始化。
下面是vgg16的示例构造
def vgg16(pretrained=False, **kwargs):
"""VGG 16-layer model (configuration "D")
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = VGG(make_layers(cfg['D']), **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['vgg16']))
return model
def vgg16_bn(pretrained=False, **kwargs):
"""VGG 16-layer model (configuration "D") with batch normalization
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = VGG(make_layers(cfg['D'], batch_norm=True), **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['vgg16_bn']))
return model