您当前的位置: 首页 >  ar

惊鸿一博

暂无认证

  • 2浏览

    0关注

    535博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

深度学习_pytorch中的forward()的使用与解释

惊鸿一博 发布时间:2021-11-04 14:23:59 ,浏览量:2

说明

最近在使用pytorch的时候,模型训练时,不需要使用forward,只要在实例化一个对象中传入对应的参数就可以自动调用 forward 函数. (model(args-list) 等价于 model.forward(args-list))

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
    传入参数的类型是: 值为: i
    forward 函数被调用了
    in forward, 传入参数类型是: 值为: i
    对象a传入的参数是: i

 

关注
打赏
1663399408
查看更多评论
立即登录/注册

微信扫码登录

0.0371s