requires_grad()
requires_grad
是一个张量的属性,用于标识该张量是否需要计算梯度。默认情况下,张量的 requires_grad
属性为 False
,表示该张量不需要计算梯度。如果需要计算梯度,需要将 requires_grad
属性设置为 True
。
import torch
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
requires_grad_()
requires_grad_
是一个张量的方法,用于原地修改该张量的requires_grad
属性。它的作用与 requires_grad
属性相同,但是它是一个原地操作,可以修改张量本身的属性。
import torch
x = torch.tensor([1.0, 2.0, 3.0])
x.requires_grad_()