Pytorch——forward()前向传播的理解
简介
我们在使用Pytorch的时候,模型训练时,不需要调用forward这个函数,只需要在实例化一个对象中传入对应的参数就可以自动调用 forward 函数。
示例
在pytorch中,使用torch.nn包来构建神经网络,我们定义的网络继承自nn.Module类。而一个nn.Module包含神经网络的各个层(放在__init__里面)和前向传播方式(放在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)
实际上model(data)是等价于model.forward(data)。
解释:__call__语法
class Student:
def __call__(self):
print('hello world')
a = Student()
a() #hello world
由上面的__call__函数可知,我们可以将forward函数放到__call__函数中进行调用:
class Student:
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 = Student()
input_param = a('data')
print("对象a传入的参数是:", input_param)
#I can called like a function
#传入参数的类型是:<class 'str'> 值为: data
#forward 函数被调用了
#in forward, 传入参数类型是:<class 'str'> 值为: data
#对象a传入的参数是: data
到这里我们就可以明白了为什么model(data)等价于model.forward(data),是因为__call__函数中调用了forward函数。

浙公网安备 33010602011771号