【发布时间】:2018-01-02 13:38:42
【问题描述】:
我正在尝试了解 autograd 在 PyTorch 中的工作原理。在下面的简单程序中,我不明白为什么loss w.r.t W1 和W2 的渐变是None。 据我从文档中了解到, 是这样吗?我的意思是,我怎么不能对中间节点的损失求导?谁能解释一下我在这里缺少什么?W1 和 W2 是不稳定的,因此无法计算梯度。
import torch
import torch.autograd as tau
W = tau.Variable(torch.FloatTensor([[0, 1]]), requires_grad=True)
a = tau.Variable(torch.FloatTensor([[2, 2]]), requires_grad=False)
b = tau.Variable(torch.FloatTensor([[3, 3]]), requires_grad=False)
W1 = W + a * a
W2 = W1 - b * b * b
Z = W2 * W2
print 'W:', W
print 'W1:', W1
print 'W2:', W2
print 'Z:', Z
loss = torch.sum((Z - 3) * (Z - 3))
print 'loss:', loss
# free W gradient buffer in case you are running this cell more than 2 times
if W.grad is not None: W.grad.data.zero_()
loss.backward()
print 'W.grad:', W.grad
# all of them are None
print 'W1.grad:', W1.grad
print 'W2.grad:', W2.grad
print 'a.grad:', a.grad
print 'b.grad:', b.grad
print 'Z.grad:', Z.grad
【问题讨论】:
标签: pytorch