TypeError: can‘t convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to

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()” 的顺序,避免重复踩坑
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值