首页 > 解决方案 > Pytorch 梯度存在但权重没有更新

问题描述

所以,我有一个带有 lstm 层的深度卷积网络,在 ltsm 层之后,它分裂以计算两个不同的函数(使用两个不同的线性层),然后将其结果加在一起形成最终的网络输出。

当我计算网络的损失以便我可以让它计算梯度并更新权重时,我让它做一些操作,然后让它计算派生值和计算的目标值之间的损失。

def update(output, target):
    # target output is calculated outside the function
    # operations on output
    loss(output, target).backward()
    self.optimizer.step()

网络有一些损失(有时在一个非常小的数量级,但有时也在更高的数量级),例如一些损失:

tensor(1.00000e-04 *
   5.7420)
tensor(2.7190)
tensor(0.9684)

它还具有此处计算的梯度:

for param in self.parameters():
    print(param.grad.data.sum())

哪个输出:

tensor(1.00000e-03 *
   1.9996)
tensor(1.00000e-03 *
   2.6101)
tensor(1.00000e-02 *
   -1.3879)
tensor(1.00000e-03 *
   -4.5834)
tensor(1.00000e-02 *
   2.1762)
tensor(1.00000e-03 *
   3.6246)
tensor(1.00000e-03 *
   6.6234)
tensor(1.00000e-02 *
   2.9373)
tensor(1.00000e-02 *
   1.2680)
tensor(1.00000e-03 *
   1.8791)
tensor(1.00000e-02 *
   1.7322)
tensor(1.00000e-02 *
   1.7322)
tensor(0.)
tensor(0.)
tensor(1.00000e-03 *
   -6.7885)
tensor(1.00000e-02 *
   9.7793)

和:

tensor(2.4620)
tensor(0.9544)
tensor(-26.2465)
tensor(0.2280)
tensor(-219.2602)
tensor(-2.7870)
tensor(-50.8203)
tensor(3.2548)
tensor(19.6163)
tensor(-18.6029)
tensor(3.8564)
tensor(3.8564)
tensor(0.)
tensor(0.)
tensor(0.8040)
tensor(-0.1157)

但是当我比较运行优化器之前和之后的权重时,我得到的结果是权重彼此相等。

查看权重是否发生变化的代码:

before = list(neuralnet.parameters())
neuralnet.update()
after = list(neuralnet.parameters())
for i in range(len(before)):
    print(torch.equal(before[i].data, after[i].data))

以上为每次迭代返回 True 。

标签: pythonneural-networkconv-neural-networklstmpytorch

解决方案


在初始化参数时,确实将它们包装在torch.nn.Parameter()类中,以便优化器更新它们。如果您使用的是 pytorch < 0.4,请尝试使用torch.autograd.Variable(). 例如:

import torch
import torch.utils.data
from torch import nn, optim
from torch.nn import functional as F

class TEMP(nn.Module):

    # Whole architecture
    def __init__(self):
        super(TEMP, self).__init__()
        self.input = nn.Parameter(torch.ones(1,requires_grad = True)) # <----wrap it like this


    def forward(self,x):
        wt = self.input
        y = wt*x 
        return y

model = TEMP()
optimizer = optim.Adam(model.parameters(), lr=0.001)
x = torch.randn(100)
y = 5*x
loss = torch.sum((y - model(x)).pow(2))
optimizer.zero_grad()
loss.backward()
optimizer.step()
print(model.input)

请注意,如果您在 pytorch >= 0.4 中初始化张量,请更改requires_grad = True如果您希望更新该变量的值。


推荐阅读