Download VGG-CIFAR10/Classification-normal/scripts/model.py from code-philia/mtpnet_image_models: direct link, hf CLI and curl.
- Browser
- Download file 6.35 kB
-
https://huggingface.co/datasets/code-philia/mtpnet_image_models/resolve/main/VGG-CIFAR10/Classification-normal/scripts/model.py
- Command line
-
hf download hf://datasets/code-philia/mtpnet_image_models/VGG-CIFAR10/Classification-normal/scripts/model.py
-
curl -L -o model.py https://huggingface.co/datasets/code-philia/mtpnet_image_models/resolve/main/VGG-CIFAR10/Classification-normal/scripts/model.py
6.35 kB
| ''' | |
| 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 feature(self, x): | |
| # 特征提取 | |
| x = self.features(x) | |
| return x | |
| def prediction(self, 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() |