Pytorch中怎么调用forward()函数(forward,pytorch,开发技术)

时间:2024-03-29 02:56:22 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

    Pytorch%E4%B8%AD%E6%80%8E%E4%B9%88%E8%B0%83%E7%94%A8forward%28%29%E5%87%BD%E6%95%B0

Module类是nn模块里提供的一个模型构造类,是所有神经网络模块的基类,我们可以继承它来定义我们想要的模型。

下面继承Module类构造本节开头提到的多层感知机。

这里定义的MLP类重载了Module类的__init__函数和forward函数。

它们分别用于创建模型参数和定义前向计算。

前向计算也即正向传播。

输出:

MLP( (hidden): Linear(in_features=784, out_features=256, bias=True) (act): ReLU() (output): Linear(in_features=256, out_features=10, bias=True) ) tensor([[-0.1798, -0.2253, 0.0206, -0.1067, -0.0889, 0.1818, -0.1474, 0.1845, -0.1870, 0.1970], [-0.1843, -0.1562, -0.0090, 0.0351, -0.1538, 0.0992, -0.0883, 0.0911, -0.2293, 0.2360]], grad_fn=<ThAddmmBackward>)

为什么会调用forward()呢,是因为Module中定义了__call__()函数,该函数调用了forward()函数,当执行net(x)的时候,会自动调用__call__()函数

最近用到 softmax 函数,但是发现 softmax 的写法五花八门,记录如下

简单测试了一下,用 torch.nn.Softmax 类是最慢的,另外两个差不多

torch.nn.Softmax 源码如下,可以看到这是个类,而他这里的 return F.softmax(input, self.dim, _stacklevel=5) 调用的是 torch.nn.functional.softmax

torch.nn.functional.softmax 函数源码如下,可以看到 ret = input.softmax(dim) 实际上调用了 torch._C._VariableFunctions 中的 softmax 函数

那么不如直接调用 built-in C 的函数?

但是有个博客 A selective excursion into the internals of PyTorch 里说

Note: That bilinear is exported as torch.bilinear is somewhat accidental. Do use the documented interfaces, here torch.nn.functional.bilinear whenever you can!

意思是说 built-in C 能被 torch.xxx 直接调用是意外的,强烈建议使用 torch.nn.functional.xxx 这样的接口

看到最新的 transformer 官方代码里也用的是 torch.nn.functional.softmax,还是和他们一致更好。

本文:Pytorch中怎么调用forward()函数的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:Android Coil和Glide实例对比分析下一篇:

4 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18