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

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

问题详解

can‘t convert cuda:0 device type tensor to numpy.Use Tensor.cpu() to copy the tensor to host memory_第1张图片源代码

plt.plot(history['train_acc'], label='train accuracy')
plt.plot(history['dev_acc'], label='dev accuracy')
plt.title('Training history')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend()
plt.ylim([0, 1])

本意是想画出训练集和验证集上准确率的对比图,然而令人费解的是loss图都可以出来,acc图却画不出来,参考其他文章发现数据acc以torch的tensor形式出现而不是单纯的列表形式,如图所示
can‘t convert cuda:0 device type tensor to numpy.Use Tensor.cpu() to copy the tensor to host memory_第2张图片

can‘t convert cuda:0 device type tensor to numpy.Use Tensor.cpu() to copy the tensor to host memory_第3张图片

解决方案

所以代码可修改为

plt.plot(torch.tensor(history["train_acc"], device='cpu'), label='train accuracy')
plt.plot(torch.tensor(history["dev_acc"], device='cpu'), label='dev accuracy')

可以出结果啦!!!

你可能感兴趣的:(python,深度学习)