python - 了解 torch.nn.Parameter

标签 python pytorch

torch.nn.Parameter() 怎么样?工作吗?

最佳答案

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

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

最初在 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)

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

关于python - 了解 torch.nn.Parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50935345/

相关文章:

python - 将 Spark DataFrame 从 Python 迁移到 Scala whithn Zeppelin

python - 解构赋值和 "normal"赋值有什么区别?

python - django多对多保存管理

python - 从多维列表 Python 中获取项目

python - 禁止在 PyTorch 神经网络的 CrossEntropyLoss 中使用 Softmax

python - 属性错误 : 'GPT2Model' object has no attribute 'gradient_checkpointing'

python - 如何将 Pandas 数据框转换为 PyTorch 张量?

python - SublimeREPL 无法识别 python 库

deep-learning - 如何有效地计算 PyTorch 中的批量成对距离

python - Huggingface Transformer - GPT2 从保存的检查点恢复训练