本文介绍: 在PyTorch中,nn.X都有对应函数版本F.X,但是并不是所有的F.X均可以用于forward或其它代码段中,因为当网络模型训练完毕存储model时,forward中的F.X函数中的参数是无法保存的。也就是说,在forward中,使用的F.X函数一般均没有状态参数nn.ReLU()创建一个nn.Module,这意味着你可以添加nn.Sequential中。而nn.functional.relu只是对 relu 函数API的调用。一般来说,用模块还是简单函数调用,取决于你的编码风格

先来看看nn.ReLU的源码可以看到其实forward中nn.relu调用了F.relu函数的:

class ReLU(Module):
    r"""Applies the rectified linear unit function element-wise:

    :math:`text{ReLU}(x) = (x)^+ = max(0, x)`

    Args:
        inplace: can optionally do the operation in-place. Default: ``False``

    Shape:
        - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
        - Output: :math:`(*)`, same shape as the input.

    .. image:: ../scripts/activation_images/ReLU.png

    Examples::

        >>> m = nn.ReLU()
        >>> input = torch.randn(2)
        >>> output = m(input)


      An implementation of CReLU - https://arxiv.org/abs/1603.05201

        >>> m = nn.ReLU()
        >>> input = torch.randn(2).unsqueeze(0)
        >>> output = torch.cat((m(input),m(-input)))
    """
    __constants__ = ['inplace']
    inplace: bool

    def __init__(self, inplace: bool = False):
        super(ReLU, self).__init__()
        self.inplace = inplace

    def forward(self, input: Tensor) -> Tensor:
        return F.relu(input, inplace=self.inplace)

    def extra_repr(self) -> str:
        inplace_str = 'inplace=True' if self.inplace else ''
        return inplace_str

nn.ReLU()创建一个nn.Module,这意味着你可以添加到nn.Sequential中。而nn.functional.relu只是对 relu 函数API的调用。一般来说,用模块还是简单的函数调用,取决于你的编码风格
在PyTorch中,nn.X都有对应的函数版本F.X,但是并不是所有的F.X均可以用于forward或其它代码段中,因为当网络模型训练完毕存储model时,forward中的F.X函数中参数是无法保存的。也就是说,在forward中,使用的F.X函数一般均没有状态参数。

原文地址:https://blog.csdn.net/qq_41776136/article/details/134764378

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_36036.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注