model_urls = {
'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'
}
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( # 是否需要展平?多维的输入一维化,常用在从卷积层到全连接层的过渡。Flatten不影响batch的大小
nn.Linear(512*7*7, 4096),
nn.ReLU(True),
nn.Dropout(p=0.5), #以一定概率随机失活 防止过拟合
nn.Linear(4096, 4096),
nn.ReLU(True),
nn.Dropout(p=0.5),
nn.Linear(4096, 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) #第0 个维度是batch,所以从第二个维度进行展平
# 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:
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) #偏置置为0
def make_features(cfg: list): #传入的就是配置变量
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) #以非关键字形式传入参数
#M 最大池化
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): #实例化
# assert model_name in cfgs, "Warning: model number {} not in cfgs dict!".format(model_name)
# cfg = cfgs[model_name]
#
# model = VGG(make_features(cfg), **kwargs)
try:
cfg = cfgs[model_name]
except:
print("Warning: model number {} not in cfgs dict!".format(model_name))
exit(-1)
#features 是通过该函数的生成的 可变长度的字典变量
model = VGG(make_features(cfg), **kwargs)
return model
深度学习_VGG网络
最新推荐文章于 2023-03-06 16:31:28 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)