You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyPlot绘图报错TypeError:无法将CUDA张量转换为numpy数组

解决Matplotlib绘图时CUDA张量转numpy的TypeError问题

错误原因

Matplotlib依赖numpy数组进行绘图,但你的train_accuracy和test_accuracy是存储在GPU(cuda:0)上的PyTorch张量列表,无法直接转换为numpy数组,必须先将张量复制到CPU内存。

解决方案

方案1:绘图前转换张量列表

遍历张量列表,将每个CUDA张量转移到CPU后,转换为numpy数组或提取标量值:

# 转换为CPU上的numpy数组列表
train_acc_np = [acc.cpu().numpy() for acc in train_accuracy]
test_acc_np = [acc.cpu().numpy() for acc in test_accuracy]

# 绘图
plt.plot(train_acc_np, label='training accuracy')
plt.plot(test_acc_np, label='validation accuracy')
plt.title('Accuracy at the end of each epoch')
plt.legend();

如果每个张量都是标量(如示例中的单个精度值),可以直接提取Python数值,更高效:

# 提取标量值
train_acc_vals = [acc.cpu().item() for acc in train_accuracy]
test_acc_vals = [acc.cpu().item() for acc in test_accuracy]

# 绘图
plt.plot(train_acc_vals, label='training accuracy')
plt.plot(test_acc_vals, label='validation accuracy')
plt.title('Accuracy at the end of each epoch')
plt.legend();

方案2:训练时直接存储CPU数值

在训练循环中记录精度时,就将CUDA张量转移到CPU并提取数值,避免后续重复处理:

train_accuracy = []
test_accuracy = []

for epoch in range(num_epochs):
    # ... 执行训练/验证步骤 ...
    # 计算训练精度(得到CUDA张量)
    train_acc = get_train_accuracy()
    # 直接存储CPU上的数值
    train_accuracy.append(train_acc.cpu().item())
    
    # 计算测试精度(得到CUDA张量)
    test_acc = get_test_accuracy()
    # 直接存储CPU上的数值
    test_accuracy.append(test_acc.cpu().item())

# 直接用存储的数值绘图
plt.plot(train_accuracy, label='training accuracy')
plt.plot(test_accuracy, label='validation accuracy')
plt.title('Accuracy at the end of each epoch')
plt.legend();

注意事项

  • 若张量是批量数据(非单个标量),使用.cpu().numpy()转换为numpy数组;
  • 若张量是单个标量,使用.cpu().item()直接提取Python数值,性能更优。

内容的提问来源于stack exchange,提问作者sccomp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 03:22:39