快捷键

torch.Tensor.is_leaf

Tensor.is_leaf

所有具有 requires_grad 且为 False 的 Tensor 都将按照惯例成为叶子 Tensor。

对于具有 requires_grad 的 Tensors,如果它们是由用户创建的,则它们将是叶子 Tensors。这意味着它们不是操作的结果,因此 grad_fn 为 None。

只有叶张量在调用 backward() 时才会填充 grad 。要为非叶张量填充 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 贡献者。

使用 Sphinx 构建,并使用 Read the Docs 提供的主题。

文档

PyTorch 的全面开发者文档

查看文档

教程

深入了解初学者和高级开发者的教程

查看教程

资源

查找开发资源并获得您的疑问解答

查看资源