在Google Colab中切换回CPU使用

我在Google Colab上运行一个模型。我希望完成的最后一步是打印一张图片,并展示模型的前5个分类预测结果。以下是代码:

image = process_image(imgpath)index = 17plot = 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() 

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注