解决TypeError: can‘t convert cuda:0 device type tensor to numpy. Use Tensor.cpu()
报错:
(图片来源网络,侵删)
TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
产生原因:
这个错误表明尝试将一个位于 CUDA 设备上(如 cuda:0)的 PyTorch 张量直接转换为 NumPy 数组,但 PyTorch 不允许直接将 GPU 上的张量转换为 NumPy 数组。为了解决这个问题,你可以使用 .cpu() 方法将张量复制到主机内存(CPU 上)然后再转换为 NumPy 数组
import torch # 假设 tensor 是一个位于 GPU 上的张量 tensor_gpu = torch.randn(3, 3).to("cuda:0") # 将张量移动到 CPU 上 tensor_cpu = tensor_gpu.cpu() # 转换为 NumPy 数组 numpy_array = tensor_cpu.numpy()
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。