20201112-Pytorch-forward函数

2020-11-16  本文已影响0人  野山羊骑士

转载:https://blog.csdn.net/xu380393916/article/details/97280035

前言

最近在使用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 class中的 callinit方法

class A():
    def __call__(self):
        print('i can be called like a function')
a = A()
a()

out

i can be called like a function

实例二

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

上一篇 下一篇

猜你喜欢

热点阅读