PyTorch张量在添加到列表后具有相同的值

2024-04-19 04:21:43 发布

您现在位置:Python中文网/ 问答频道 /正文

在Pytorch学习梯度和优化过程时,我想用图表计算损失函数值与权重值的变化。当我试图绘制图表时,我同时使用了numpytorch,因为我想进行比较。在存储grad列表的过程中。和损失函数值。 它在numpy工作:

def gradient(x,y, y_predicted):
  return np.dot(2*x, y_predicted-y).mean() 

dw = gradient(x,y,y_pred)
dw_list.append(dw)

[-120.0, -112.8, -106.032, -99.67008, -93.68988, -88.06848, -82.78437, -77.81731, -73.14827, -68.75938]

它在火炬上不起作用:

  for epoch in range(n_iters):
    # prediction = forward pass
    y_pred = forward(x)
    
    # loss
    l = loss(y, y_pred)
    loss_list.append(l)
    print('loss')
    print(l_list)
    # gradients = backward pass
    l.backward()  # calculate w.grad = dl/dw   and cumulative 
    
    # update weights
    with torch.no_grad():
        w -= learning_rate * w.grad
    print(f'w.grad before zero setting = {w.grad}')
    dw_list.append(w.grad) 
    print(dw_list)
    #print(f'w.grad before zero setting = {w.grad}')
    # zero gradients
    w.grad.zero_()

[tensor(-6.9485), tensor(-6.9485), tensor(-6.9485), tensor(-6.9485), tensor(-6.9485), tensor(-6.9485), tensor(-6.9485), tensor(-6.9485), tensor(-6.9485), tensor(-6.9485)]

为什么dw_list.append(dw)在numpy工作,而dw_list.append(w.grad)在torch不工作

为什么每次国际热核实验堆的整个阵列中都只填充了新的梯度值。火炬张量


Tags: 函数numpy过程torchlist梯度tensorprint
1条回答
网友
1楼 · 发布于 2024-04-19 04:21:43

w.grad是张量;它(相同的张量)在每次迭代时被追加到列表中,因此列表包含相同张量的副本,而不是您可能希望的每个时间点的值的副本

处理此问题的标准方法是使用:

dw_list.append(w.grad.detach().cpu().numpy()) 

请查看此讨论,了解为什么需要分离(): https://discuss.pytorch.org/t/should-it-really-be-necessary-to-do-var-detach-cpu-numpy/35489/6

相反,np.mean()每次调用时都返回一个新的python float对象,因此最后的值是不同的。list append()在这两种情况下没有任何不同

另外,我认为这也会起作用:

dw_list.append(w.grad.clone())

但是,它会将克隆的张量保留在图形中(如果原始张量在gpu上,则保留在gpu上)。这可能不是你想要的

相关问题 更多 >