"""
当对设置requires_grad=True的张量使用numpy函数进行转化时,会出现以下报错:
Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead.
此时需要使用detach函数将张量分离,再使用numpy函数
注意:detach之后会产生一个新的张量,新的张量作为叶子结点,并且该张量和原来的张量共享数据,但是分离后的张量不需要计算梯度。
"""
import torch
#1.演示错误
def test01():
x=torch.tensor([10,20],requires_grad=True,dtype=torch.float64)
#print(x.numpy())
#RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead.
#下面是正确做法
print(x.detach().numpy())
#2共享数据
def test02():
x1=torch.tensor([10,20],requires_grad=True,dtype=torch.float64)
#使用detach函数分离出一个新的张量
x2=x1.detach().numpy()
#修改分离后产生的新的张量
x2[0]=100
print(x1)
print(x2)
#tensor([100., 20.], dtype=torch.float64, requires_grad=True) [100. 20.]
#结果表明:x2不存在requires_grad=True
#表示:对x1的任何计算都会影响到x1的梯度计算,但对x2的任何计算不会影响到x1的梯度计算
print(x1.requires_grad)
#print(x2.requires_grad)
if __name__=='__main__':
test02()
梯度计算注意事项(pytorch)
最新推荐文章于 2024-08-14 16:39:36 发布