File size: 6,051 Bytes
bdbd148 |
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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 |
'''
VGG Networks in PyTorch
VGG是由牛津大学Visual Geometry Group提出的一个深度卷积神经网络模型。
主要特点:
1. 使用小卷积核(3x3)代替大卷积核,降低参数量
2. 深层网络结构,多个卷积层叠加
3. 使用多个3x3卷积层的组合来代替大的感受野
4. 结构规整,易于扩展
网络结构示例(VGG16):
input
└─> [(Conv3x3, 64) × 2, MaxPool]
└─> [(Conv3x3, 128) × 2, MaxPool]
└─> [(Conv3x3, 256) × 3, MaxPool]
└─> [(Conv3x3, 512) × 3, MaxPool]
└─> [(Conv3x3, 512) × 3, MaxPool]
└─> [AvgPool, Flatten]
└─> FC(512, num_classes)
参考论文:
[1] K. Simonyan and A. Zisserman, "Very Deep Convolutional Networks for Large-Scale Image Recognition,"
arXiv preprint arXiv:1409.1556, 2014.
'''
import torch
import torch.nn as nn
# VGG配置参数
# M表示MaxPool层,数字表示输出通道数
cfg = {
'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 ConvBlock(nn.Module):
"""VGG的基本卷积块
包含: Conv2d -> BatchNorm -> ReLU
使用3x3卷积核,步长为1,padding为1以保持特征图大小不变
Args:
in_channels (int): 输入通道数
out_channels (int): 输出通道数
batch_norm (bool): 是否使用BatchNorm,默认为True
"""
def __init__(self, in_channels, out_channels, batch_norm=True):
super(ConvBlock, self).__init__()
layers = []
# 3x3卷积,padding=1保持特征图大小不变
layers.append(
nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=1,
padding=1
)
)
# 添加BatchNorm
if batch_norm:
layers.append(nn.BatchNorm2d(out_channels))
# ReLU激活函数
layers.append(nn.ReLU(inplace=True))
self.block = nn.Sequential(*layers)
def forward(self, x):
"""前向传播
Args:
x (torch.Tensor): 输入特征图
Returns:
torch.Tensor: 输出特征图
"""
return self.block(x)
class VGG(nn.Module):
"""VGG网络模型
Args:
vgg_name (str): VGG变体名称,可选VGG11/13/16/19
num_classes (int): 分类数量,默认为10
batch_norm (bool): 是否使用BatchNorm,默认为True
init_weights (bool): 是否初始化权重,默认为True
"""
def __init__(self, vgg_name='VGG16', num_classes=10, batch_norm=True, init_weights=True):
super(VGG, self).__init__()
# 特征提取层
self.features = self._make_layers(cfg[vgg_name], batch_norm)
# 全局平均池化
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
# 分类器
self.classifier = nn.Sequential(
nn.Linear(512, num_classes)
)
# 初始化权重
if init_weights:
self._initialize_weights()
def _make_layers(self, cfg, batch_norm=True):
"""构建VGG的特征提取层
Args:
cfg (List): 网络配置参数
batch_norm (bool): 是否使用BatchNorm
Returns:
nn.Sequential: 特征提取层序列
"""
layers = []
in_channels = 3
for x in cfg:
if x == 'M': # 最大池化层
layers.append(nn.MaxPool2d(kernel_size=2, stride=2))
else: # 卷积块
layers.append(ConvBlock(in_channels, x, batch_norm))
in_channels = x
return nn.Sequential(*layers)
def forward(self, x):
"""前向传播
Args:
x (torch.Tensor): 输入图像张量,[N,3,H,W]
Returns:
torch.Tensor: 输出预测张量,[N,num_classes]
"""
# 特征提取
x = self.features(x)
# 全局平均池化
x = self.avgpool(x)
# 展平
x = torch.flatten(x, 1)
# 分类
x = self.classifier(x)
return x
def _initialize_weights(self):
"""初始化模型权重
采用论文中的初始化方法:
- 卷积层: xavier初始化
- BatchNorm: weight=1, bias=0
- 线性层: 正态分布初始化(std=0.01)
"""
for m in self.modules():
if isinstance(m, nn.Conv2d):
# VGG论文中使用了xavier初始化
nn.init.xavier_normal_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, nn.BatchNorm2d):
nn.init.ones_(m.weight)
nn.init.zeros_(m.bias)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
nn.init.zeros_(m.bias)
def test():
"""测试函数
创建VGG模型并进行前向传播测试,打印模型结构和参数信息
"""
# 创建模型
net = VGG('VGG16')
print('Model Structure:')
print(net)
# 测试前向传播
x = torch.randn(2, 3, 32, 32)
y = net(x)
print('\nInput Shape:', x.shape)
print('Output Shape:', y.shape)
# 打印模型信息
from torchinfo import summary
device = 'cuda' if torch.cuda.is_available() else 'cpu'
net = net.to(device)
summary(net, (2, 3, 32, 32))
if __name__ == '__main__':
test() |