TypeError: can’t convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first
AttributeError: ‘builtin_function_or_method’ object has no attribute ‘numpy’
这两种错误的原因
尝试直接将 GPU(cuda:0)上的 PyTorch 张量转换为 NumPy 数组,但 NumPy 只能处理 CPU 内存中的数据,无法直接读取 GPU 数据。结合你之前的代码修正情况,大概率是部分代码仍遗漏了 “将 GPU 张量转移到 CPU” 的步骤
解决方法
1. 找到所有 “张量转 NumPy” 的代码行
在 Plot.py
中搜索所有包含 .numpy()
的语句,确保每个语句都满足:GPU 张量 → (可选)detach 脱离计算图 → cpu () 转移到 CPU → numpy () 转换
2. 正确的代码格式(分两种场景)
# 错误写法(缺cpu()或括号)
数组名[0][0,:].detach().numpy() # 没转CPU
数组名[0][0,:].detach().cpu.numpy() # cpu漏了括号
# 正确写法
数组名[0][0,:].detach().cpu().numpy() # 先detach,再转CPU,最后转NumPy
关键提醒
- 只要张量是在 GPU 上(通过
tensor.device
可查看,显示cuda:0
即 GPU),转 NumPy 前必须加.cpu()
。 - 若后续新增绘图代码,记得保持 “
cpu()
+numpy()
” 的顺序,避免重复踩坑