快捷方式

torch.Tensor.is_leaf

Tensor.is_leaf

約定上,所有 requires_gradFalse 的 Tensor 都是葉子 Tensor。

對於 requires_gradTrue 的 Tensor,如果它們是由使用者建立的,則它們是葉子 Tensor。這意味著它們不是某個操作的結果,因此 grad_fn 為 None。

只有葉子 Tensor 的 grad 會在呼叫 backward() 期間被填充。要為非葉子 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 全面的開發者文件

檢視文件

教程

獲取面向初學者和高階開發者的深度教程

檢視教程

資源

查詢開發資源並獲得問題解答

檢視資源