快捷键

torch.Tensor.requires_grad_

Tensor.requires_grad_(requires_grad=True) Tensor

改变是否应该记录此张量上的操作:在原地设置此张量的 requires_grad 属性。返回此张量。

requires_grad_() 的主要用途是告诉 autograd 开始记录 Tensor tensor 上的操作。如果 tensorrequires_grad=False (因为它是通过 DataLoader 获得的,或者需要预处理或初始化), tensor.requires_grad_() 将使 autograd 开始记录 tensor 上的操作。

参数:

requires_grad(布尔值)- 如果 autograd 应该记录此张量上的操作。默认值: True

示例:

>>> # Let's say we want to preprocess some saved weights and use
>>> # the result as new weights.
>>> saved_weights = [0.1, 0.2, 0.3, 0.25]
>>> loaded_weights = torch.tensor(saved_weights)
>>> weights = preprocess(loaded_weights)  # some function
>>> weights
tensor([-0.5503,  0.4926, -2.1158, -0.8303])

>>> # Now, start to record operations done to weights
>>> weights.requires_grad_()
>>> out = weights.pow(2).sum()
>>> out.backward()
>>> weights.grad
tensor([-1.1007,  0.9853, -4.2316, -1.6606])

© 版权所有 PyTorch 贡献者。

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

文档

PyTorch 的全面开发者文档

查看文档

教程

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

查看教程

资源

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

查看资源