import torch as t
x = t.ones(1, requires_grad=True)
x.requires_grad #True
y = t.ones(1, requires_grad=True)
y.requires_grad #True
x = x.detach() #分离之后
x.requires_grad #False
y = x+y #tensor([2.])
y.requires_grad #我还是True
y.retain_grad() #y不是叶子张量,要加上这一行
z = t.pow(y, 2)
z.backward() #反向传播
y.grad #tensor([4.])
x.grad #None
API
Returns a new Tensor, detached from the current graph.
返回的Tensor和原来的Tensor共享相同的存储空间,但是返回的Tensor没有梯度
参考:
https://blog.csdn.net/qq_39463274/article/details/105157719
https://pytorch.org/docs/stable/autograd.html?highlight=detach#torch.Tensor.detach