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

参考资料

(1条消息)pytorch 之 call, init,forward - Every moment of My life !!! - CSDN博客
https://blog.csdn.net/xxboy61/article/details/88101192

(1条消息)PyTorch之前向传播函数forward - 鹊踏枝-码农的专栏 - CSDN博客
https://blog.csdn.net/u011501388/article/details/84062483

  • 149
    点赞
  • 358
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值