title: Convert CUDA tensor to NumPy
body: <p>First of all, I tried those solutions: <a href="https://stackoverflow.com/questions/53467215/convert-pytorch-tensor-to-numpy-array-using-cuda">1</a>, <a href="https://stackoverflow.com/questions/41035617/how-to-convert-tensor-to-numpy-array">2</a>, <a href="https://stackoverflow.com/questions/50931333/convert-tensor-to-numpy-array">3</a>, and <a href="https://stackoverflow.com/questions/52148590/convert-tensor-to-numpy-without-a-session">4</a>, but did not work for me.</p>
  
  <p>After training and testing the neural network, I am trying to show some examples to verify my work. I named the method <strong>predict</strong> which I pass the image to it to predict for which class it belongs:</p>
  
  <pre><code>def predict(model, image_path, topk=5):
  ''' Predict the class (or classes) of an image using a trained deep learning model.
  '''
  
  output = process_image(image_path)
  output.unsqueeze_(0)
  output = output.cuda().float()
  
  model.eval()
  
  with torch.no_grad():
      score = model(output)
      prob, idxs = torch.topk(score, topk)
  
      # Convert indices to classes
      idxs = np.array(idxs)
      idx_to_class = {val:key for key, val in model.class_to_idx.items()}
      classes = [idx_to_class[idx] for idx in idxs[0]]
  
      # Map the class name with collected topk classes
      names = []
      for cls in classes:
          names.append(cat_to_name[str(cls)])
  
      return prob, names
  </code></pre>
  
  <p>Then there is the final step which displays the final result based on the training of the neural network and done like this:</p>
  
  <pre><code># TODO: Display an image along with the top 5 classes
  x_pos, y_pos = predict(model, img_pil, topk=5)
  
  ax_img = imshow(output)
  ax_img.set_title(y_pos[0])
  
  plt.figure(figsize=(4,4))
  plt.barh(range(len(y_pos)), np.exp(x_pos[0]))
  plt.yticks(range(len(y_pos)), y_pos)
  
  plt.show()
  </code></pre>
  
  <p>The error is:</p>
  
  <pre><code>---------------------------------------------------------------------------
  TypeError                                 Traceback (most recent call last)
  &lt;ipython-input-45-e3f9951e9804&gt; in &lt;module&gt;()
  ----&gt; 1 x_pos, y_pos = predict(model, img_pil, topk=5)
        2
        3 ax_img = imshow(output)
        4 ax_img.set_title(y_pos[0])
        5
  
  1 frames
  &lt;ipython-input-44-d77500f31561&gt; in predict(model, image_path, topk)
       14
       15         # Convert indices to classes
  ---&gt; 16         idxs = np.array(idxs)
       17         idx_to_class = {val:key for key, val in model.class_to_idx.items()}
       18         classes = [idx_to_class[idx] for idx in idxs[0]]
  
  /usr/local/lib/python3.6/dist-packages/torch/tensor.py in __array__(self, dtype)
      456     def __array__(self, dtype=None):
      457         if dtype is None:
  --&gt; 458             return self.numpy()
      459         else:
      460             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.
  </code></pre>
  
  <p><strong>How do I solve this?</strong></p>
  
  <p>I tried to change idx to <code>idxs = idxs.cpu().numpy()</code> and the error is:</p>
  
  <p></p>
  
  <pre><code>TypeError                                 Traceback (most recent call last)
  &lt;ipython-input-62-e3f9951e9804&gt; in &lt;module&gt;()
        5
        6 plt.figure(figsize=(4,4))
  ----&gt; 7 plt.barh(range(len(y_pos)), np.exp(x_pos[0]))
        8 plt.yticks(range(len(y_pos)), y_pos)
        9
  
  /usr/local/lib/python3.6/dist-packages/torch/tensor.py in __array__(self, dtype)
      456     def __array__(self, dtype=None):
      457         if dtype is None:
  --&gt; 458             return self.numpy()
      459         else:
      460             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.
  </code></pre>