学习基于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

相关推荐
计算机学姐1 小时前
基于SpringBoot+Vue的在线投票系统
java·vue.js·spring boot·后端·学习·intellij-idea·mybatis
彤银浦1 小时前
python学习记录7
python·学习
少女忧1 小时前
51单片机学习第六课---B站UP主江协科技
科技·学习·51单片机
邓校长的编程课堂2 小时前
助力信息学奥赛-VisuAlgo:提升编程与算法学习的可视化工具
学习·算法
missmisslulu3 小时前
电容笔值得买吗?2024精选盘点推荐五大惊艳平替电容笔!
学习·ios·电脑·平板
yunhuibin3 小时前
ffmpeg面向对象——拉流协议匹配机制探索
学习·ffmpeg
hengzhepa3 小时前
ElasticSearch备考 -- Search across cluster
学习·elasticsearch·搜索引擎·全文检索·es
蜡笔小新星4 小时前
Python Kivy库学习路线
开发语言·网络·经验分享·python·学习
攸攸太上4 小时前
JMeter学习
java·后端·学习·jmeter·微服务
Ljubim.te5 小时前
Linux基于CentOS学习【进程状态】【进程优先级】【调度与切换】【进程挂起】【进程饥饿】
linux·学习·centos