torch.Tensor.requires_grad_#
- Tensor.requires_grad_(requires_grad=True) Tensor #
更改此张量上的 autograd 是否应记录操作:原地设置此张量的
requires_grad
属性。返回此张量。requires_grad_()
的主要用例是告知 autograd 开始在张量tensor
上记录操作。如果tensor
的requires_grad=False
(因为它是由 DataLoader 提供的,或者需要预处理或初始化),则tensor.requires_grad_()
会使 autograd 开始在tensor
上记录操作。- 参数
requires_grad (bool) – 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])