【Pytorch】nn.Module基本骨架(3)

20240207周三

看代码的时候发现 y_pred = self.model(x_dict) 就能调用模型的运行了。

#深入探究# PyTorch中的 forward() 方法详解-CSDN博客

为什么呢?执行上面语句相当于调用forward(x)方法。定义类的是时候写了__call()___方法,call()中写了调用forward的过程,这样实现 “类+参数=实例.方法+参数” 的调用。

其次定义模型结构的时候,def forward(x)并不是只传一个x参数,这里x可以包括这种这样的数据。


torch.nn — PyTorch 2.2 documentation

CONTAINERS 给神经网络定义了一些骨架。将常用的层添加到骨架里。

CLASStorch.nn.Module

  • Base class for all neural network modules.
  • Your models should also subclass this class.
  • Modules can also contain other Modules, allowing to nest them in a tree structure. You can assign the submodules as regular attributes:
import torch.nn as nn
import torch.nn.functional as F

# 自定义的Model继承了nn.Module
#  
class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.conv1 = nn.Conv2d(1, 20, 5)
        self.conv2 = nn.Conv2d(20, 20, 5)

    # 输入是x
    def forward(self, x):
        x = F.relu(self.conv1(x))
        return F.relu(self.conv2(x))

创建一个简单的神经网络

# -*- coding: utf-8 -*-
import torch
from torch import nn


class Tudui(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, input):
        output = input + 1
        return output


tudui = Tudui()
x = torch.tensor(1.0)
output = tudui(x)
print(output) # tensor(2.)

打断点

ps

pycharm类重写,code->generate->

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值