- 情况: 在对tensor进行计算时报错:
TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
-
报错原因:
不能直接对tensor变量进行array的运算;
requires_grad=True时不能调用numpy() -
解决方法:
参考网上教程, 在对应变量后添加.cpu().numpy()
运行后,报错:
RuntimeError: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() instead.
在原始变量后添加.cpu().detach().numpy()
- 感悟: 问题需要一个一个解决
本文详细解析了在使用PyTorch中Tensor转换为NumPy数组时遇到的TypeError及RuntimeError错误,阐述了.requires_grad属性对转换的影响,并提供了.cpu().detach().numpy()的解决方案。

6752

被折叠的 条评论
为什么被折叠?



