pytorch中的forward()的使用与解释
2022/9/10 23:23:11
本文主要是介绍pytorch中的forward()的使用与解释,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
参考 pytorch中的forward()的使用与解释 - 云+社区 - 腾讯云
前言
最近在使用pytorch的时候,模型训练时,不需要使用forward,只要在实例化一个对象中传入对应的参数就可以自动调用 forward 函数
即:
forward 的使用
class Module(nn.Module):
def __init__(self):
super(Module, self).__init__()
# ......
def forward(self, x):
# ......
return x
data = ..... #输入数据
# 实例化一个对象
module = Module()
# 前向传播
module(data)
# 而不是使用下面的
# module.forward(data)
实际上
module(data)
是等价于
module.forward(data)
forward 使用的解释
等价的原因是因为 python calss 中的__call__和__init__方法.
class A():
def __call__(self):
print('i can be called like a function')
a = A()
a()
out:
i can be called like a function
- __call__里调用其他的函数
class A():
def __call__(self, param):
print('i can called like a function')
print('传入参数的类型是:{} 值为: {}'.format(type(param), param))
res = self.forward(param)
return res
def forward(self, input_):
print('forward 函数被调用了')
print('in forward, 传入参数类型是:{} 值为: {}'.format( type(input_), input_))
return input_
a = A()
input_param = a('i')
print("对象a传入的参数是:", input_param)
out: i can called like a function 传入参数的类型是:<class ‘str’> 值为: i forward 函数被调用了 in forward, 传入参数类型是:<class ‘str’> 值为: i 对象a传入的参数是: i
这篇关于pytorch中的forward()的使用与解释的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-27易优如何解除绑定微信公众号-icode9专业技术文章分享
- 2024-07-27安装 Eyoucms安装使用-icode9专业技术文章分享
- 2024-07-26TtpeScript学习手记
- 2024-07-26SendGrid 中单个类别(标签)名称的长度限制通常为 128 个字符。 怎么写-icode9专业技术文章分享
- 2024-07-26SendGrid 怎么设置回复邮箱-icode9专业技术文章分享
- 2024-07-26response, err := s.sd.SendWithContext(ctx, m) 怎么获取到唯一ID 请求ID-icode9专业技术文章分享
- 2024-07-26sendgrid 是一个APIKEY 代表一个发送域名吗, 还是多个-icode9专业技术文章分享
- 2024-07-26mailgun和 sendgrid 批量发送邮件, 最多支持给多少人发送 1000个?-icode9专业技术文章分享
- 2024-07-26mailgun 发送邮件 怎么批量发送给多个人-icode9专业技术文章分享
- 2024-07-25TtpeScript学习手记