当前位置:   article > 正文

学习基于pytorch的VGG图像分类 day2

学习基于pytorch的VGG图像分类 day2
注:本系列博客在于汇总CSDN的精华帖,类似自用笔记,不做学习交流,方便以后的复习回顾,博文中的引用都注明出处,并点赞收藏原博主.

目录

VGG网络搭建(模型文件)

        1.字典文件配置

         2.提取特征网络结构

        3. VGG类的定义

         4.VGG网络实例化


VGG网络搭建(模型文件)

        1.字典文件配置

  1. #字典文件,对应各个配置,数字对应卷积核的个数,'M'对应最大液化(即maxpool)
  2. cfgs = {
  3. 'vgg11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
  4. 'vgg13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
  5. 'vgg16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
  6. 'vgg19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
  7. }

         2.提取特征网络结构

  1. #提取特征网络结构
  2. def make_features(cfg: list): #传入对应的列表
  3. layers = [] #定义一个空列表,存放每层的结果
  4. in_channels = 3 #输入为RGB彩色图片,输入通道为3
  5. for v in cfg: #通过for循环遍历列表
  6. if v == "M": #maxpool size = 2,stride = 2
  7. layers += [nn.MaxPool2d(kernel_size=2, stride=2)] #创建最大池化下载量程,池化核为2,布局也为2
  8. else: #conv padding = 1,stride = 1
  9. conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1) #创建卷积操作(输入特征矩阵深度,输出特征矩阵深度(卷积核个数),卷积核为3,填充为1,stride默认为1(不用写))
  10. layers += [conv2d, nn.ReLU(True)] #使用ReLU激活函数
  11. in_channels = v #输出深度改变成v
  12. return nn.Sequential(*layers) #通过Sequential函数将列表以非关键字参数的形式传入(*代表非关键字传入)

        3. VGG类的定义

  1. class VGG(nn.Module):
  2. def __init__(self, features, num_classes=1000, init_weights=False): #(通过make_features生成的提取特征网络结构,分类的类别个数,是否对网络权重初始化)
  3. super(VGG, self).__init__()
  4. self.features = features
  5. self.classifier = nn.Sequential( #生成分类网络
  6. nn.Linear(512*7*7, 4096), #全连接层上下的节点个数
  7. nn.ReLU(True), #ReLU函数激活
  8. nn.Dropout(p=0.5), #Dropout函数减少过拟合,以50%的比例随机失活神经元
  9. nn.Linear(4096, 4096), #第一层和第二层
  10. nn.ReLU(True),
  11. nn.Dropout(p=0.5),
  12. nn.Linear(4096, num_classes) #第二层和第三层,总计3层全连接层,最后连接到输出层,输出num_classes的所需个数
  13. )
  14. if init_weights: #初始化权重函数
  15. self._initialize_weights()
  16. def forward(self, x): #正向传播 x就是输入的图像数据
  17. # N x 3 x 224 x 224
  18. x = self.features(x) #用features提取特征网络结构
  19. # N x 512 x 7 x 7
  20. x = torch.flatten(x, start_dim=1) #对输出进行一个展平处理,(start_dim定义从哪个维度开始展平处理)
  21. # N x 512*7*7
  22. x = self.classifier(x) #输入到分类网络结构
  23. return x
  24. def _initialize_weights(self):
  25. for m in self.modules(): #遍历网络的每一个子模块
  26. if isinstance(m, nn.Conv2d): #遍历到卷积层
  27. # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
  28. nn.init.xavier_uniform_(m.weight) #使用xavier函数初始化,初始化卷积核的权重
  29. if m.bias is not None: #卷积核采用偏置
  30. nn.init.constant_(m.bias, 0) #将偏执初始化为0
  31. elif isinstance(m, nn.Linear): #遍历到全连接层,下面同理
  32. nn.init.xavier_uniform_(m.weight)
  33. # nn.init.normal_(m.weight, 0, 0.01)
  34. nn.init.constant_(m.bias, 0)

         4.VGG网络实例化

  1. #实例化VGG网络结构
  2. def vgg(model_name="vgg16", **kwargs):
  3. assert model_name in cfgs, "Warning: model number {} not in cfgs dict!".format(model_name)
  4. cfg = cfgs[model_name]
  5. model = VGG(make_features(cfg), **kwargs) #通过VGG这个类实现实例化网络,(**可变长度的字典变量)
  6. return model

 内容参考来源:

 ​​​​​​使用pytorch搭建VGG网络_哔哩哔哩_bilibili

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/398627
推荐阅读
相关标签
  

闽ICP备14008679号