这是来自这里的后续问题。我已经获得了一个张量,例如带有梯度的
d
。现在我有另一个张量数组,比如 e
,我需要从中选择第一个 d
元素。 MWE如下。
import torch
a = torch.tensor([4.], requires_grad=True)
b = torch.tensor([5.])
c = torch.tensor([6.])
d = a.min(b).min(c)
e = torch.arange(10)
f = e[:d] # Throws error "TypeError: only integer tensors of a single element can be converted to an index"
根据here的答案,以下行有效。
f = e[:d.to(dtype=torch.long)]
但是,梯度会丢失。有什么办法可以传递梯度或者这个操作根本不可微分吗?非常感谢。
看起来您正在尝试制作没有梯度的张量
e
的切片,因此张量f
也不应该有梯度。在张量 a
中创建的梯度保留在 d
中,但不会影响 e
或 f
。切片后,f
仅保留来自e
的梯度。