我是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)
Run Code Online (Sandbox Code Playgroud)
Ast*_*rma 55
我会为你分解它.您可能知道,张量是多维矩阵.参数以其原始形式是张量,即多维矩阵.它对Variable类进行子类化.
当与模块关联时,变量和参数之间的差异就会出现.当参数与模块关联作为模型属性时,它会自动添加到参数列表中,并可使用"参数"迭代器进行访问.
最初在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)
Run Code Online (Sandbox Code Playgroud)
现在,检查与此模型关联的参数列表 -
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])
"""
Run Code Online (Sandbox Code Playgroud)
或试试,
list(net.parameters())
Run Code Online (Sandbox Code Playgroud)
这可以轻松地提供给您的优化器 -
opt = Adam(net.parameters(), learning_rate=0.001)
Run Code Online (Sandbox Code Playgroud)
另请注意,默认情况下参数的require_grad已设置.
最近的PyTorch版本中仅包含张量,因此不建议使用Variable的概念。
参数只是限于定义的模块(在模块构造函数__init__方法中)的张量。
它们会出现在里面module.parameters()。当您构建自定义模块时,这非常方便,这得益于这些参数的梯度下降。
因为参数是张量,所以对于PyTorch张量而言,任何适用于参数的情况都适用。
此外,如果模块转到GPU,参数也将转到。如果模块被保存,参数也将被保存。
有一个类似的概念可以对称为缓冲区的参数进行建模。
这些张量在模块内部被称为张量,但是这些张量并不是要通过梯度下降来学习的,相反,您可以认为它们就像变量一样。您将根据需要更新模块内部的命名缓冲区forward()。
对于缓冲区,它们也将随模块一起进入GPU,并且将与模块一起保存也是正确的。