python - 使用 Google Colab 改回 CPU

标签 python matplotlib machine-learning deep-learning pytorch

我正在 Google Colab 上运行模型。我想做的最后一步是打印图像,并显示模型的前 5 个分类预测。这是代码:

image = process_image(imgpath)

index = 17
plot = imshow(image, ax = plt)
plot.axis('off')
plot.title(cat_to_name[str(index)])
plot.show()

axes = predict(image, model)

yaxis = [cat_to_name[str(i)] for i in np.array(axes[1][0])]
y_pos = np.arange(len(yaxis))
xaxis = np.array(axes[0][0])   

plt.barh(y_pos, xaxis)
plt.xlabel('probability')
plt.yticks(y_pos, yaxis)
plt.title('probability of flower classification')

plt.show()

运行此单元格时出现此错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-19-d0bb6f461eec> in <module>()
     11 axes = predict(image, model)
     12 
---> 13 yaxis = [cat_to_name[str(i)] for i in np.array(axes[1][0])]
     14 y_pos = np.arange(len(yaxis))
     15 xaxis = np.array(axes[0][0])

/usr/local/lib/python3.6/dist-packages/torch/tensor.py in __array__(self, dtype)
    447     def __array__(self, dtype=None):
    448         if dtype is None:
--> 449             return self.numpy()
    450         else:
    451             return self.numpy().astype(dtype, copy=False)

TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

有没有办法在 Google Colab 上以及在此特定步骤中临时使用 CPU?我真的不需要切换回 GPU,因为这是我代码中的最后一步。

最佳答案

尝试以下操作:

yaxis = [cat_to_name[str(i)] for i in axes[1][0].cpu()]
xaxis = axes[0][0].cpu().numpy() 

关于python - 使用 Google Colab 改回 CPU,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59635097/

相关文章:

python - 使用 Airflow 传感器启动 DAG 运行

python - 使用 assertRaise 测试异常消息

python - 不使用 Matplotlib 表示半个像素

python - 如何在 3D 曲面图中绘制 x、y、z 的 numpy 数组?

image-processing - 使用机器学习创建植物健康分类器

python - 使用 Psycopg2 保持 Python 和 Postgresql 之间持续连接的最佳/最佳实践

python - 缺少 1 个必需的位置参数 : 'msg'

Python Pandas MultiIndex Plot 图例的颜色不正确

machine-learning - 如何在 sklearn::LGBMClassifier() 中的 LightGBM 分类器的 feature_importances_ 中将 'gain' 设置为特征重要性度量

machine-learning - 有没有办法可以上传某种分辨率的新图像并将其提供给模型以获得双倍分辨率的图像?