pytorch中tensor转numpy

pytorch中tensor转numpy,第1张

cpu tensor转numpy:

#假定a为tensor

a.numpy()

gpu tensor转numpy:

gpu下的tensor不能直接转numpy,需要先转到cpu tensor后再转为numpy

a.cpu().numpy()

注:若tensor带有梯度,以上述方式转换时会报错:

RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead.

可以改用detach().numpy()方式

a.detach().numpy()
a.cpu().detach().numpy()

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/714996.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-25
下一篇2022-04-25

发表评论

登录后才能评论

评论列表(0条)

    保存