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)
12345678910111213141516
实际上
module(data)
1
是等价于
module.forward(data)
1
forward 使用的解释
等价的原因是因为 python calss 中的__call__和__init__方法.
class A():
def __call__(self):
print('i can be called like a function')
a = A()
a()
1234567
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)
123456789101112131415161718192021222324
out:
i can called like a function
传入参数的类型是:<class ‘str’> 值为: i
forward 函数被调用了
in forward, 传入参数类型是:<class ‘str’> 值为: i
对象a传入的参数是: i
在声明网络架构是,常常使用class RegionProposalNetwork(nn.Module),其中nn.Module中包含了__call__函数,在函数中调用了forward,由于继承关系,对于RegionProposalNetwork同样具备__call__函数的功能。
参考:https://blog.csdn.net/qq_23981335/article/details/103683737包含的nn.Module源码理解
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)