VGG網路:網路改造的首選基礎網路
阿新 • • 發佈:2021-01-29
技術標籤:Image Models
import torch.nn as nn
import torch
class VGG(nn.Module):
def __init__(self, features, num_classes=1000, init_weights=False):
super(VGG, self).__init__()
self.features = features
self.classifier = nn.Sequential(
nn.Dropout(p=0.5),
nn. Linear(512 * 7 * 7, 2048),
nn.ReLU(True),
nn.Dropout(p=0.5),
nn.Linear(2048, 2048),
nn.ReLU(True),
nn.Linear(2048, num_classes)
)
if init_weights:
self._initialize_weights()
def forward(self, x):
# N x 3 x 224 x 224
x = self.features(x)
# N x 512 x 7 x 7
x = torch.flatten(x, start_dim=1)
# N x 512*7*7
x = self.classifier(x)
return x
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
# nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
nn.init.xavier_uniform_(m.weight) # 初始化權重引數
if m.bias is not None: # 如果採用了偏置的話,置為0
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.xavier_uniform_(m.weight)
# nn.init.normal_(m.weight, 0, 0.01)
nn.init.constant_(m.bias, 0)
def make_features(cfg: list): # 注意這裡是 用一個函式把卷積層和池化層堆疊到layers中
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)
layers += [conv2d, nn.ReLU(True)]
in_channels = v
return nn.Sequential(*layers)
cfgs = {
'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'],
}
def vgg(model_name="vgg16", **kwargs):
try:
cfg = cfgs[model_name]
except:
print("Warning: model number {} not in cfgs dict!".format(model_name))
exit(-1)
model = VGG(make_features(cfg), **kwargs)
return model
VGG 是 Visual Geometry Group 的縮寫,是這個網路建立者的隊名,作者來自牛津大學。
VGG 最大的特點就是它在之前的網路模型上,通過比較徹底地採用 3x3 尺寸的卷積核來堆疊神經網路,從而加深整個神經網路的層級。
3x3 卷積核是能夠感受到上下、左右、重點的最小的感受野尺寸。
VGG19:
VGGNet改進點總結
一、使用了更小的33卷積核,和更深的網路。兩個33卷積核的堆疊相對於55卷積核的視野,三個33卷積核的堆疊相當於77卷積核的視野。這樣一方面可以有更少的引數(3個堆疊的33結構只有77結構引數數量的(333)/(77)=55%);另一方面擁有更多的非線性變換,增加了CNN對特徵的學習能力。
二、在VGGNet的卷積結構中,引入1*1的卷積核,在不影響輸入輸出維度的情況下,引入非線性變換,增加網路的表達能力,降低計算量。