美文网首页
torch.nn.Patameter()详解

torch.nn.Patameter()详解

作者: 马尔代夫Maldives | 来源:发表于2022-09-12 16:26 被阅读0次

    torch.nn.Parameter是torch.Tensor的子类。
    其主要作用是将不可训练的tensor变成可训练的参数,并将其绑定到module里面
    它与torch.Tensor的区别就是nn.Parameter的对象会被被加入到module自带的parameter()这个迭代器中去(见后面Linear例子);而module中非nn.Parameter对象的普通tensor是不在parameter()这个迭代器中的。
    注意:nn.Parameter的对象的requires_grad属性的默认值是True,即可被训练的,这与torth.Tensor对象的默认值相反。

    用法:
    torch.nn.Parameter(Tensor data, bool requires_grad)
    其中:data为传入Tensor类型参数,requires_grad默认值为True,表示可训练,False表示不可训练。

    在nn.Module类中,也是使用nn.Parameter来对每一个module的参数进行初始化的,以torch.nn.Linear类为例:

    class Linear(Module):
        r"""Applies a linear transformation to the incoming data: :math:`y = xA^T + b`
        Args:
            in_features: size of each input sample
            out_features: size of each output sample
            bias: If set to ``False``, the layer will not learn an additive bias.
                Default: ``True``
        Shape:
            - Input: :math:`(N, *, H_{in})` where :math:`*` means any number of
              additional dimensions and :math:`H_{in} = \text{in\_features}`
            - Output: :math:`(N, *, H_{out})` where all but the last dimension
              are the same shape as the input and :math:`H_{out} = \text{out\_features}`.
        Attributes:
            weight: the learnable weights of the module of shape
                :math:`(\text{out\_features}, \text{in\_features})`. The values are
                initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`, where
                :math:`k = \frac{1}{\text{in\_features}}`
            bias:   the learnable bias of the module of shape :math:`(\text{out\_features})`.
                    If :attr:`bias` is ``True``, the values are initialized from
                    :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
                    :math:`k = \frac{1}{\text{in\_features}}`
        Examples::
            >>> m = nn.Linear(20, 30)
            >>> input = torch.randn(128, 20)
            >>> output = m(input)
            >>> print(output.size())
            torch.Size([128, 30])
        """
        __constants__ = ['in_features', 'out_features']
     
        def __init__(self, in_features, out_features, bias=True):
            super(Linear, self).__init__()
            self.in_features = in_features
            self.out_features = out_features
            self.weight = Parameter(torch.Tensor(out_features, in_features))
            if bias:
                self.bias = Parameter(torch.Tensor(out_features))
            else:
                self.register_parameter('bias', None)
            self.reset_parameters()
     
        def reset_parameters(self):
            init.kaiming_uniform_(self.weight, a=math.sqrt(5))
            if self.bias is not None:
                fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
                bound = 1 / math.sqrt(fan_in)
                init.uniform_(self.bias, -bound, bound)
     
        def forward(self, input):
            return F.linear(input, self.weight, self.bias)
     
        def extra_repr(self):
            return 'in_features={}, out_features={}, bias={}'.format(
                self.in_features, self.out_features, self.bias is not None
            )
    

    可见,在初始化函数__init__()中,代码:
    self.weight = Parameter(torch.Tensor(out_features, in_features))
    通过nn.Parameter()对象对weights进行了初始化,bias也是一样。
    (与torch.tensor([1,2,3],requires_grad=True)的区别,这个只是将参数变成可训练的,并没有绑定在module的parameter()列表中。)

    我们生成一个Linear对象模型,看看其parameter列表中是否含有weigs和bias这两个可训练参数:

    import torch.nn as nn
    
    my_linear = nn.Linear(2,3)  # 生成一个线性层对象(这也是一个完整的module)
    for i in my_linear.named_parameters():  # 查看该module包含多少个可训练的参数(也可用*.parameters())
        print(i)
    
    输出:
    ('weight', Parameter containing:
    tensor([[-0.2682, -0.5847],
            [ 0.6815, -0.4122],
            [ 0.2677,  0.2913]], requires_grad=True))
    ('bias', Parameter containing:
    tensor([ 0.0536, -0.3389, -0.6452], requires_grad=True))
    

    参考:
    https://zhuanlan.zhihu.com/p/368808794

    相关文章

      网友评论

          本文标题:torch.nn.Patameter()详解

          本文链接:https://www.haomeiwen.com/subject/bbacortx.html