Calling forward function without .forward()(在没有 .forward() 的情况下调用 forward 函数)
问题描述
在查看一些关于姿势估计的 pytorch 代码时 AlphaPose 我注意到一些不熟悉的语法:
While looking at some pytorch code on pose estimation AlphaPose I noticed some unfamiliar syntax:
基本上,我们定义了一个 Darknet
类,它继承了 nn.Module
属性,如下所示:class Darknet(nn.Module)
Basically, we define a Darknet
class which inherits nn.Module
properties like so: class Darknet(nn.Module)
这从一些配置文件中重新构建了神经网络,并定义了加载预训练权重和前向传递的函数
This re-constructs the neural net from some config file and also defines functions to load pre-trained weights and a forward pass
现在,前向传递采用以下参数:
Now, forward pass takes the following parameters:
def forward(self, x, CUDA)
我应该注意,在类定义中,forward 是唯一具有 CUDA 属性的方法(这在后面会变得很重要)
I should note that in class definition forward is the only method that has a CUDA attribute (this will become important later on)
在前向传递中,我们得到预测:
In the forward pass we get the predictions:
for i in range(number_of_modules):
x = self.module[i](x)
其中 module[i]
被构造为:
module = nn.Sequential()
conv = nn.Conv2d(prev_fileters, filters, kernel_size, stride, pad, bias=bias)
module.add_module("conv_{0}".format(index), conv)
然后我们调用 invoke 这个模型和(我假设)一个像这样的转发方法:
We then call invoke this model and (I presume) a forward method like so:
self.det_model = Darknet("yolo/cfg/yolov3-spp.cfg")
self.det_model.load_weights('models/yolo/yolov3-spp.weights')
self.det_model.cpu()
self.det_model.eval()
image = image.cpu()
prediction = self.det_model(img, CUDA = False)
我假设最后一行是前向传递的调用,但为什么不使用 .forward
?这是pytorch特定的语法还是我缺少一些基本的python原则?
I assume that the last line is the calling of the forward pass but why not use the .forward
? Is this a pytorch specific syntax or am I missing some basic python principles?
推荐答案
这不是火炬特定的.当您以 class_object(fn params)
的形式调用某些内容时,它会调用该类的 __call__
方法.
This is nothing torch specific. When you call something as class_object(fn params)
it invokes the __call__
method of that class.
如果你挖掘了torch的代码,特别是nn.Module
,你会看到__call__
在内部调用forward,但会处理pytorch允许的钩子和状态.所以当你调用 self.det_model(img, cuda)
时,你仍然在调用 forward.
If you dig the code of torch, specifically nn.Module
you will see that __call__
internally invokes forward but taking care of hooks and states that pytorch allows. So when you are calling self.det_model(img, cuda)
you are still calling forward.
查看 nn.module 的代码 此处一>.
See the code for nn.module here.
这篇关于在没有 .forward() 的情况下调用 forward 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在没有 .forward() 的情况下调用 forward 函数


基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01