捷徑

torch.Tensor.is_leaf

Tensor.is_leaf

所有具有 requires_grad 且為 False 的 Tensor,依照慣例將會是葉 Tensor。

對於具有 requires_grad 且為 True 的 Tensor,如果它們是由使用者建立的,則它們將會是葉 Tensor。 這表示它們不是運算的結果,因此 grad_fn 為 None。

只有葉 Tensor 會在呼叫 backward() 期間填入其 grad。 若要為非葉 Tensor 填入 grad,您可以使用 retain_grad()

範例

>>> a = torch.rand(10, requires_grad=True)
>>> a.is_leaf
True
>>> b = torch.rand(10, requires_grad=True).cuda()
>>> b.is_leaf
False
# b was created by the operation that cast a cpu Tensor into a cuda Tensor
>>> c = torch.rand(10, requires_grad=True) + 2
>>> c.is_leaf
False
# c was created by the addition operation
>>> d = torch.rand(10).cuda()
>>> d.is_leaf
True
# d does not require gradients and so has no operation creating it (that is tracked by the autograd engine)
>>> e = torch.rand(10).cuda().requires_grad_()
>>> e.is_leaf
True
# e requires gradients and has no operations creating it
>>> f = torch.rand(10, requires_grad=True, device="cuda")
>>> f.is_leaf
True
# f requires grad, has no operation creating it

文件

獲取 PyTorch 的完整開發者文件

檢視文件

教學

獲取為初學者和進階開發者提供的深度教學

檢視教學

資源

尋找開發資源並獲得問題解答

檢視資源