iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >Pytorch中怎么调用forward()函数
  • 762
分享到

Pytorch中怎么调用forward()函数

2023-07-05 04:07:09 762人浏览 独家记忆
摘要

这篇文章主要讲解了“PyTorch中怎么调用forward()函数”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Pytorch中怎么调用forward()函数”吧!Pytorch调用forw

这篇文章主要讲解了“PyTorch中怎么调用forward()函数”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Pytorch中怎么调用forward()函数”吧!

Pytorch调用forward()函数

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

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

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

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

前向计算也即正向传播。

import torchfrom torch import nn class MLP(nn.Module):    # 声明带有模型参数的层,这里声明了两个全连接层    def __init__(self, **kwargs):        # 调用MLP父类Module的构造函数来进行必要的初始化。这样在构造实例时还可以指定其他函数        # 参数,如“模型参数的访问、初始化和共享”一节将介绍的模型参数params        super(MLP, self).__init__(**kwargs)        self.hidden = nn.Linear(784, 256) # 隐藏层        self.act = nn.ReLU()        self.output = nn.Linear(256, 10)  # 输出层      # 定义模型的前向计算,即如何根据输入x计算返回所需要的模型输出    def forward(self, x):        a = self.act(self.hidden(x))        return self.output(a)  X = torch.rand(2, 784)net = MLP()print(net)net(X)

输出:

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__()函数

Pytorch函数调用的问题和源码解读

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

# torch._C._VariableFunctionstorch.softmax(x, dim=-1)
# classsoftmax = torch.nn.Softmax(dim=-1)x=softmax(x)
# functionx = torch.nn.functional.softmax(x, dim=-1)

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

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

class Softmax(Module):    r"""Applies the Softmax function to an n-dimensional input Tensor    rescaling them so that the elements of the n-dimensional output Tensor    lie in the range [0,1] and sum to 1.    Softmax is defined as:    .. math::        \text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}    When the input Tensor is a sparse tensor then the unspecifed    values are treated as ``-inf``.    Shape:        - Input: :math:`(*)` where `*` means, any number of additional          dimensions        - Output: :math:`(*)`, same shape as the input    Returns:        a Tensor of the same dimension and shape as the input with        values in the range [0, 1]    Args:        dim (int): A dimension along which Softmax will be computed (so every slice            along dim will sum to 1).    .. note::        This module doesn't work directly with NLLLoss,        which expects the Log to be computed between the Softmax and itself.        Use `LogSoftmax` instead (it's faster and has better numerical properties).    Examples::        >>> m = nn.Softmax(dim=1)        >>> input = torch.randn(2, 3)        >>> output = m(input)    """    __constants__ = ['dim']    dim: Optional[int]    def __init__(self, dim: Optional[int] = None) -> None:        super(Softmax, self).__init__()        self.dim = dim    def __setstate__(self, state):        self.__dict__.update(state)        if not hasattr(self, 'dim'):            self.dim = None    def forward(self, input: Tensor) -> Tensor:        return F.softmax(input, self.dim, _stacklevel=5)    def extra_repr(self) -> str:        return 'dim={dim}'.fORMat(dim=self.dim)

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

def softmax(input: Tensor, dim: Optional[int] = None, _stacklevel: int = 3, dtype: Optional[DType] = None) -> Tensor:    r"""Applies a softmax function.    Softmax is defined as:    :math:`\text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}`    It is applied to all slices along dim, and will re-scale them so that the elements    lie in the range `[0, 1]` and sum to 1.    See :class:`~torch.nn.Softmax` for more details.    Args:        input (Tensor): input        dim (int): A dimension along which softmax will be computed.        dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.          If specified, the input tensor is casted to :attr:`dtype` before the operation          is performed. This is useful for preventing data type overflows. Default: None.    .. note::        This function doesn't work directly with NLLLoss,        which expects the Log to be computed between the Softmax and itself.        Use log_softmax instead (it's faster and has better numerical properties).    """    if has_torch_function_unary(input):        return handle_torch_function(softmax, (input,), input, dim=dim, _stacklevel=_stacklevel, dtype=dtype)    if dim is None:        dim = _get_softmax_dim("softmax", input.dim(), _stacklevel)    if dtype is None:        ret = input.softmax(dim)    else:        ret = input.softmax(dim, dtype=dtype)    return ret

那么不如直接调用 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()函数”的内容了,经过本文的学习后,相信大家对Pytorch中怎么调用forward()函数这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!

--结束END--

本文标题: Pytorch中怎么调用forward()函数

本文链接: https://www.lsjlt.com/news/349300.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Pytorch中怎么调用forward()函数
    这篇文章主要讲解了“Pytorch中怎么调用forward()函数”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Pytorch中怎么调用forward()函数”吧!Pytorch调用forw...
    99+
    2023-07-05
  • Pytorch中如何调用forward()函数
    目录Pytorch调用forward()函数Pytorch函数调用的问题和源码解读总结Pytorch调用forward()函数 Module类是nn模块里提供的一个模型构造类,是所有...
    99+
    2023-02-17
    Pytorch调用forward函数 Pytorch forward函数 Pytorch forward()函数
  • __init__、forward、__call__三者怎么在pytorch中使用
    本篇文章给大家分享的是有关__init__、forward、__call__三者怎么在pytorch中使用,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。1)__init__主要...
    99+
    2023-06-06
  • pytorch中torch.topk()函数怎么用
    这篇文章主要介绍“pytorch中torch.topk()函数怎么用”,在日常操作中,相信很多人在pytorch中torch.topk()函数怎么用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”pytorch...
    99+
    2023-06-29
  • 如何在pytorch中使用forward 方法
    这篇文章将为大家详细讲解有关如何在pytorch中使用forward 方法,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。forward 的使用class Module(nn.Mod...
    99+
    2023-06-06
  • C++11中如何使用forward函数
    本篇文章给大家分享的是有关C++11中如何使用forward函数,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。传值函数模板假设有一组函数,根据两个输入值进行工作,例如下面的ad...
    99+
    2023-06-19
  • PyTorch中torch.matmul()函数怎么使用
    这篇文章主要介绍了PyTorch中torch.matmul()函数怎么使用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇PyTorch中torch.matmul()函数怎么使用文章都会有所收获,下面我们一起来看...
    99+
    2023-07-06
  • pytorch中Parameter函数怎么使用
    这篇文章主要介绍了pytorch中Parameter函数怎么使用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇pytorch中Parameter函数怎么使用文章都会有所收获,下面我们一起来看看吧。用法介绍pyt...
    99+
    2023-06-29
  • Pytorch中的torch.gather()函数怎么用
    这篇文章将为大家详细讲解有关Pytorch中的torch.gather()函数怎么用,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。参数说明以官方说明为例,gather()函数需要三个参数,输入input,...
    99+
    2023-06-25
  • pytorch中的torch.nn.Conv2d()函数怎么用
    这篇文章主要为大家展示了“pytorch中的torch.nn.Conv2d()函数怎么用”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“pytorch中的torch.nn.Conv2d()函数怎么...
    99+
    2023-06-29
  • pytorch中的view()函数怎么使用
    这篇文章主要介绍了pytorch中的view()函数怎么使用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇pytorch中的view()函数怎么使用文章都会有所收获,下面我们一起来看看吧。一、普通用法 (手动调...
    99+
    2023-06-29
  • python中forward怎么使用
    在Python中,我们可以使用`forward()`方法来控制海龟绘图中的移动方向。首先,我们需要导入`turtle`模块,并创建一...
    99+
    2023-10-11
    python
  • pytorch中BatchNorm2d函数的参数怎么使用
    本篇内容主要讲解“pytorch中BatchNorm2d函数的参数怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“pytorch中BatchNorm2d函数的参数怎么使用”吧!BN原理、作...
    99+
    2023-07-04
  • Python中怎么调用函数
    Python中怎么调用函数,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。函数function是什么?函数的作用函数是可以实现一些特定功能的小方法或是小程序。在Python中...
    99+
    2023-06-19
  • c++中函数怎么调用
    c++ 中的函数调用涉及以下步骤:定义函数。在使用位置声明函数。使用函数名及其参数调用函数。根据需要选择参数传递方式(值传递或引用传递)。 如何在 C++ 中调用函数 C++ 中的函数...
    99+
    2024-05-01
    c++
  • Pytorch中backward()多个loss函数怎么用
    这篇文章主要介绍Pytorch中backward()多个loss函数怎么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!Pytorch的backward()函数假若有多个loss函数,如何进行反向传播和更新呢?&nb...
    99+
    2023-06-15
  • JavaScript中怎么调用函数
    这期内容当中小编将会给大家带来有关JavaScript中怎么调用函数,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。首先让我们创建一个简单的函数,这个函数将在将在下文中使用...
    99+
    2024-04-02
  • pytorch中forwod函数在父类中的调用方式解读
    目录pytorch forwod函数在父类中的调用问题背景pytorch forward方法调用原理总结pytorch forwod函数在父类中的调用 问题背景 最近在研究Detet...
    99+
    2023-02-17
    pytorch forwod函数 forwod在父类中调用 pytorch函数forwod
  • Pytorch中的backward()多个loss函数怎么用
    这篇文章主要介绍了Pytorch中的backward()多个loss函数怎么用,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。Pytorch的backward()函数假若有多个...
    99+
    2023-06-15
  • 怎么在python中调用函数
    这篇文章将为大家详细讲解有关怎么在python中调用函数,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。python可以做什么Python是一种编程语言,内置了许多有效的工具,Python几乎...
    99+
    2023-06-14
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作