【问题标题】:Pytorch gradients exist but weights not updatingPytorch 梯度存在但权重没有更新
【发布时间】:2018-12-08 19:41:53
【问题描述】:

所以,我有一个带有 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。

【问题讨论】:

    标签: python neural-network conv-neural-network lstm pytorch


    【解决方案1】:

    在初始化参数时,将它们包装在torch.nn.Parameter() 类中,以便优化器更新它们。如果您使用的是 pytorch 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 的值。

    【讨论】:

      【解决方案2】:

      https://discuss.pytorch.org/t/gradients-exist-but-weights-not-updating/20484/2?u=wr01 有我想要的答案。问题是 neuralnet.parameters() 没有克隆参数列表,所以当我更新权重时,权重在 before 变量中更新。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 1970-01-01
      • 1970-01-01
      • 2022-06-21
      • 2019-11-24
      • 2020-05-12
      • 1970-01-01
      相关资源
      最近更新 更多