首页 > 解决方案 > 了解 torch.nn.Parameter

问题描述

我是 pytorch 的新手,我很难理解它是如何torch.nn.Parameter()工作的。

我已经阅读了https://pytorch.org/docs/stable/nn.html中的文档,但可能对此知之甚少。

有人可以帮忙吗?

我正在处理的代码片段:

def __init__(self, weight):
    super(Net, self).__init__()
    # initializes the weights of the convolutional layer to be the weights of the 4 defined filters
    k_height, k_width = weight.shape[2:]
    # assumes there are 4 grayscale filters
    self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False)
    self.conv.weight = torch.nn.Parameter(weight)

标签: pythonpytorch

解决方案


我会为你分解它。您可能知道,张量是多维矩阵。原始形式的参数是张量,即多维矩阵。它是变量类的子类。

当与模块关联时,变量和参数之间的区别就出现了。当参数作为模型属性与模块关联时,它会自动添加到参数列表中,并且可以使用“参数”迭代器进行访问。

最初在 Torch 中,变量(例如可能是中间状态)也会在分配时作为模型的参数添加。后来确定了一些用例,其中确定了需要缓存变量而不是将它们添加到参数列表中。

如文档中所述,其中一种情况是 RNN,您需要保存最后一个隐藏状态,这样您就不必一次又一次地传递它。需要缓存一个变量而不是让它作为参数自动注册到模型中,这就是为什么我们有一种显式的方式将参数注册到我们的模型中,即 nn.Parameter 类。

例如,运行以下代码 -

import torch
import torch.nn as nn
from torch.optim import Adam

class NN_Network(nn.Module):
    def __init__(self,in_dim,hid,out_dim):
        super(NN_Network, self).__init__()
        self.linear1 = nn.Linear(in_dim,hid)
        self.linear2 = nn.Linear(hid,out_dim)
        self.linear1.weight = torch.nn.Parameter(torch.zeros(in_dim,hid))
        self.linear1.bias = torch.nn.Parameter(torch.ones(hid))
        self.linear2.weight = torch.nn.Parameter(torch.zeros(in_dim,hid))
        self.linear2.bias = torch.nn.Parameter(torch.ones(hid))

    def forward(self, input_array):
        h = self.linear1(input_array)
        y_pred = self.linear2(h)
        return y_pred

in_d = 5
hidn = 2
out_d = 3
net = NN_Network(in_d, hidn, out_d)

现在,检查与此模型相关的参数列表 -

for param in net.parameters():
    print(type(param.data), param.size())

""" Output
<class 'torch.FloatTensor'> torch.Size([5, 2])
<class 'torch.FloatTensor'> torch.Size([2])
<class 'torch.FloatTensor'> torch.Size([5, 2])
<class 'torch.FloatTensor'> torch.Size([2])
"""

或者试试,

list(net.parameters())

这可以很容易地提供给您的优化器 -

opt = Adam(net.parameters(), learning_rate=0.001)

另外,请注意参数默认设置了 require_grad 。


推荐阅读