Pytorch源码学习之一: torchvision.models.alexnet

2023-05-16

Pytorch源码学习之一 torchvision.models.alexnet

torch中一行代码导入的alexnet配置如下:

64@11x11 stride=4 + ReLU + Maxpooling 3x3 stride=2
192@5x5 stride=1 + ReLU + MaxPooling 3x3 stride=2
384@3x3 stride=1 + ReLU
256@3x3 stride=1 + ReLU
256@3x3 stride=1 + ReLU + MaxPooling 3x3 stride=2
AvgPool => 6x6x256
Dropout
fc 6x6x256 => 4096 + ReLU + Dropout
fc 4096 => 4096 + ReLU
fc 4096 => num_classes

一、源码

参考地址torchvison.models.alexnet源码

#导入必要的pytorch包
import torch
import torch.nn as nn
class alexnet(nn.Module):
    
    def __init__(self, num_classes=1000):
        super(alexnet, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(64, 192, kernel_size=5, stride=1, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(192, 384, kernel_size=3, stride=1, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(384, 256, kernel_size=3, stride=1, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1),
            nn.ReLU(inplace=True)  ,  
            nn.MaxPool2d(kernel_size=3, stride=2)
        )
        self.avgpool = nn.AdaptiveAvgPool2d((6,6))
        self.classifier = nn.Sequential(
            nn.Dropout(),
            nn.Linear(6*6*256, 4096),
            nn.ReLU(inplace=True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(inplace=True),
            nn.Linear(4096, num_classes)
        )
    
    def forward(self, x):
        x = self.features(x)
        x = self.avgpool(x)
        x = x.view(x.size(0), -1)
        out = self.classifier(x)
        return out 

一些函数/类用法笔记

下面对复现过程中遇到的函数的用法进行回顾,有些用法虽然已经熟知,仍做简介

torch.nn.Module
#所有神经网络的基类,自己写的代码应该继承该类
#继承主要是两个函数
#一个是 __init__(self, ) 用来堆叠网络结构
#一个是forward 用来写前向传播,并返回输出值
super(alexnet, self).__init__()
#super()函数是用来调用父类(超类)的一个方法
#用来解决多重继承问题,直接用类名调用父类方法在使用单继承上没问题,但是如果使用多继承,会涉及查找顺序(MRO)、重复调用等问题.
#主要语法为
super(type[, object-or-type])
#type -- 类
#object-or-type --类, 一般是self
#该行代码含义即为:调用父类nn.Module的.__init__方法
nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=0, groups=1, bias=True)
#padding各个维度0填充的个数,默认是0;
#后三个参数暂时还没用到,待补充
nn.MaxPool2d(kernel_size, stride=1)
nn.ReLU(inplace=False)
#inplace即为是否覆盖原数据,若选择True,则节省空间
nn.Dropout(p=0.5, inplace=False)
#训练时引入dropout, p为将参数归0的比例,默认保留0.5
nn.linear(in_features, out_features, bias=True)
# 输入通道数, 输出通道数, 是否有bias项
torch.Tensor.view(*shape)
#返回同样数据,不同shape的Tensor,返回的Tenosr必须跟原来的Tensor有相同的元素数
x = x.view(x.size(0), -1)
#即将卷积网络输出reshape为(batch_size, fc_shape),即相当于flatten的工作
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Pytorch源码学习之一: torchvision.models.alexnet 的相关文章

随机推荐