我会为你分解。如您所知,张量是多维矩阵。原始形式的参数是张量,即多维矩阵。它对变量类进行子类化。
与模块关联时,会出现变量和参数之间的差异。当参数与作为模型属性的模块关联时,它会自动添加到参数列表中,并且可以使用“参数”迭代器进行访问。
最初在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。
0
我是pytorch的新手,我很难理解
torch.nn.Parameter()
工作方式。我已经浏览了https://pytorch.org/docs/stable/nn.html中的文档,但是从中可能会很有用。
有人可以帮忙吗?
我正在处理的代码段: