pytorch框架学习第五次作业——模型创建步骤与nn.Module

本文详细介绍了使用PyTorch构建神经网络模型的过程,包括LeNet和AlexNet的实现。通过step into调试方法,展示了网络模型构建的具体步骤,以及如何使用sequential容器为AlexNet的每一层增加名称。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 采用步进(Step into)的调试方法从创建网络模型开始(net = LeNet(classes=2))进入到每一个被调用函数,观察net的_modules字段何时被构建并且赋值,记录其中所有进入的类与函数

第一步:net = LeNet(classes=2)
第二步:LeNet类,init(),super(LeNet, self).init()
第三步: Module类, init(),self._construct()
第四步: Module类, _construct(),构建_modules
第五步:Conv2d类,init(),super(Conv2d, self).init()
第六步:_ConvNd类,init(),super(_ConvNd, self).init()
第七步:Module类, init(),self._construct()
第八步:Module类, _construct()
第九步:Module类, __setattr(),对_modules赋值
第十步:执行完所有网络层的构建
第十一步:返回net

2. 采用sequential容器,改写Alexnet,给features中每一个网络层增加名字,并通过下面这行代码打印出来print(alexnet._modules[‘features’]._modules.keys())。

改写代码如下

from collections import OrderedDict
class AlexNet(nn.Module):

    def __init__(self, num_classes=1000):
        super(AlexNet, self).__init__()
        self.features = nn.Sequential(OrderedDict({
            'conv1': nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
            'relu1': nn.ReLU(inplace=True),
            'pool1': nn.MaxPool2d(kernel_size=3, stride=2),
            'conv2': nn.Conv2d(64, 192, kernel_size=5, padding=2),
            'relu2': nn.ReLU(inplace=True),
            'pool2': nn.MaxPool2d(kernel_size=3, stride=2),
            'conv3': nn.Conv2d(192, 384, kernel_size=3, padding=1),
            'relu3': nn.ReLU(inplace=True),
            'conv4': nn.Conv2d(384, 256, kernel_size=3, padding=1),
            'relu4': nn.ReLU(inplace=True),
            'conv5': nn.Conv2d(256, 256, kernel_size=3, padding=1),
            'relu5': nn.ReLU(inplace=True),
            'pool3': nn.MaxPool2d(kernel_size=3, stride=2),
        }))
        self.avgpool = nn.AdaptiveAvgPool2d((6, 6))
        self.classifier = nn.Sequential(OrderedDict({
            'drop1': nn.Dropout(),
            'fc1': nn.Linear(256 * 6 * 6, 4096),
            'relu6': nn.ReLU(inplace=True),
            'drop2': nn.Dropout(),
            'fc2': nn.Linear(4096, 4096),
            'relu7': nn.ReLU(inplace=True),
            'fc3': nn.Linear(4096, num_classes),
        }))

    def forward(self, x):
        x = self.features(x)
        x = self.avgpool(x)
        x = torch.flatten(x, 1)
        x = self.classifier(x)
        return x

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Aidanmomo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值