gpt4 book ai didi

python - Pytorch:从矩阵元素的总和反向传播到叶变量

转载 作者:太空宇宙 更新时间:2023-11-04 01:59:51 28 4
gpt4 key购买 nike

我试图更好地理解 pytorch 中的反向传播。我有一个代码片段成功地从输出 d 反向传播到叶变量 a,但是如果我添加 reshape 步骤,反向传播不再为输入提供梯度。

我知道 reshape 不合适,但我仍然不确定如何将其置于上下文中。

有什么想法吗?

谢谢。

#Works
a = torch.tensor([1.])
a.requires_grad = True
b = torch.tensor([1.])
c = torch.cat([a,b])
d = torch.sum(c)
d.backward()

print('a gradient is')
print(a.grad) #=> Tensor([1.])

#Doesn't work
a = torch.tensor([1.])
a.requires_grad = True
a = a.reshape(a.shape)
b = torch.tensor([1.])
c = torch.cat([a,b])
d = torch.sum(c)
d.backward()

print('a gradient is')
print(a.grad) #=> None

最佳答案

编辑:

这里是对正在发生的事情的详细解释(“这本身不是一个错误,但它绝对是一个困惑的根源”):https://github.com/pytorch/pytorch/issues/19778

所以一个解决方案是特别要求保留 grad for now non-leaf a:

a = torch.tensor([1.])
a.requires_grad = True
a = a.reshape(a.shape)
a.retain_grad()
b = torch.tensor([1.])
c = torch.cat([a,b])
d = torch.sum(c)
d.backward()

旧答案:

如果你在 reshape 之后移动 a.requires_grad = True,它会起作用:

a = torch.tensor([1.])
a = a.reshape(a.shape)
a.requires_grad = True
b = torch.tensor([1.])
c = torch.cat([a,b])
d = torch.sum(c)
d.backward()

似乎是 PyTorch 中的错误,因为在此之后 a.requires_grad 仍然为真。

a = torch.tensor([1.])
a.requires_grad = True
a = a.reshape(a.shape)

这似乎与 a 在您的“不起作用”示例中不再是叶子,但在其他情况下仍然是叶子的事实有关(打印 a.is_leaf 检查)。

关于python - Pytorch:从矩阵元素的总和反向传播到叶变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55942423/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com