我在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()