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

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

目录

VGG网络搭建(模型文件)

1.字典文件配置

2.提取特征网络结构

[3. VGG类的定义](#3. VGG类的定义)

4.VGG网络实例化


VGG网络搭建(模型文件)

1.字典文件配置

python 复制代码
#字典文件,对应各个配置,数字对应卷积核的个数,'M'对应最大液化(即maxpool)
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'],
}

2.提取特征网络结构

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

3. VGG类的定义

python 复制代码
class VGG(nn.Module):
    def __init__(self, features, num_classes=1000, init_weights=False): #(通过make_features生成的提取特征网络结构,分类的类别个数,是否对网络权重初始化)
        super(VGG, self).__init__()
        self.features = features
        self.classifier = nn.Sequential( #生成分类网络
            nn.Linear(512*7*7, 4096), #全连接层上下的节点个数
            nn.ReLU(True),  #ReLU函数激活
            nn.Dropout(p=0.5), #Dropout函数减少过拟合,以50%的比例随机失活神经元
            nn.Linear(4096, 4096), #第一层和第二层
            nn.ReLU(True),
            nn.Dropout(p=0.5),
            nn.Linear(4096, num_classes) #第二层和第三层,总计3层全连接层,最后连接到输出层,输出num_classes的所需个数
        )
        if init_weights: #初始化权重函数
            self._initialize_weights()

    def forward(self, x): #正向传播 x就是输入的图像数据 
        # N x 3 x 224 x 224
        x = self.features(x) #用features提取特征网络结构
        # N x 512 x 7 x 7
        x = torch.flatten(x, start_dim=1) #对输出进行一个展平处理,(start_dim定义从哪个维度开始展平处理)
        # 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) #使用xavier函数初始化,初始化卷积核的权重
                if m.bias is not None: #卷积核采用偏置
                    nn.init.constant_(m.bias, 0) #将偏执初始化为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)

4.VGG网络实例化

python 复制代码
#实例化VGG网络结构
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) #通过VGG这个类实现实例化网络,(**可变长度的字典变量)
    return model

内容参考来源:

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

相关推荐
aWty_3 小时前
实分析入门(11)--Cantor三分集
学习·数学·算法·实变函数
for_ever_love__10 小时前
UI学习:UISearchController基础了解和应用
学习·ui·ios·objective-c
心中有国也有家10 小时前
GE图引擎深度解析——CANN的计算图优化与执行引擎
人工智能·pytorch·python·学习·numpy
GHL28427109011 小时前
换脸工作流学习
学习·ai
_李小白12 小时前
【android opencv学习笔记】Day 28: 滤波算法之中值滤波器
android·opencv·学习
飞翔中文网13 小时前
Java学习笔记之抽象类与接口(设计思想)
java·笔记·学习
土星碎冰机14 小时前
xxljob学习(大白话版本)
学习·运维开发
瑶总迷弟14 小时前
使用 mis-tei 在昇腾310P上部署 bge-m3模型
pytorch·python·华为·语言模型·自然语言处理·cnn·unix
吃好睡好便好14 小时前
说说免疫力的维护
学习·生活
凉、介15 小时前
深入理解 ARMv8-A|处理器模式与寄存器
笔记·学习·嵌入式·arm