TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu()

Iskandar_Zulkarnaen: <p>Hello, anyone know whats wrong with my code?<br>
I think i already add a img_tensor.cpu().data but its doesnt work</p>
<p>i have a code like this…</p>
<pre><code class="lang-auto">#Define plot function
def plot_image(img_tensor, annotation, block=True):
  fig,ax = plt.subplots(1)
  img = img_tensor.cpu().data

  # Display the image
  ax.imshow( np.array( img.permute(1, 2, 0) ) )
  
  for box, label in zip( annotation["boxes"], annotation["labels"] ):
    xmin, ymin, xmax, ymax = box
    # Create a Rectangle patch
    if label==1:
      rect = patches.Rectangle((xmin,ymin),(xmax-xmin),(ymax-ymin),linewidth=1,edgecolor='g',facecolor='none')
    elif label==2:
      rect = patches.Rectangle((xmin,ymin),(xmax-xmin),(ymax-ymin),linewidth=1,edgecolor='r',facecolor='none')
    elif label==3:
      rect = patches.Rectangle((xmin,ymin),(xmax-xmin),(ymax-ymin),linewidth=1,edgecolor='y',facecolor='none')
    
    # Add the patch to the Axes
    ax.add_patch(rect)
    ax.axis("off")
    
  plt.show(block=block)
</code></pre>
<pre><code class="lang-auto">count=0
model.eval()
for imgs, annotations in test_loader:
  imgs = list(img.to(device) for img in imgs)
  annotations = [{k: v.to(device) for k, v in t.items()} for t in annotations]
  preds = model(imgs)

  for i in range(len(imgs)):
    print("Prediction")
    plot_image(imgs[i], preds[i])
    print("Target")
    plot_image(imgs[i], annotations[i])
  count += 1
  if count == 20:#We will check 20 images in test set.
    break
</code></pre>

ptrblck: <p>Could you post the full error message which should show the line of code raising the error?<br>
Additionally add a <code>print</code> statement before executing the problematic line of code and check the <code>.device</code> attribute of the used tensor to make sure it’s on the CPU.</p>

Iskandar_Zulkarnaen: <p>its showing error on line</p>
<pre><code class="lang-auto">plot_image(imgs[i], preds[i])
    print("Target")
    plot_image(imgs[i], annotations[i])
</code></pre>

ptrblck: <p>Have you tried to add the recommended operations from the error message?<br>
I.e.</p>
<pre><code class="lang-python">plot_image(imgs[i].cpu().numpy(), preds[i].cpu().numpy())
</code></pre>
<p>might work.</p>

Iskandar_Zulkarnaen: <aside class="quote no-group" data-username="ptrblck" data-post="4" data-topic="153368">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/48/1823_2.png" class="avatar"> ptrblck:</div>
<blockquote>
<p><code>plot_image(imgs[i].cpu().numpy(), preds[i].cpu().numpy())</code></p>
</blockquote>
</aside>
<p>It doesnt work. It showing error message like this :</p>
<pre><code class="lang-auto">---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
&lt;ipython-input-17-1241f3973b9b&gt; in &lt;module&gt;()
      8   for i in range(len(imgs)):
      9     print("Prediction")
---&gt; 10     plot_image(imgs[i].cpu().numpy(), preds[i].cpu().numpy())
     11     print("Target")
     12     plot_image(imgs[i], annotations[i])

AttributeError: 'dict' object has no attribute 'cpu'
</code></pre>

ptrblck: <p>Oh, right. <code>plot_image</code> expects a <code>dict</code> as the <code>annoation</code> argument, so use the calls only of the <code>img_tensor</code> (you could also change the code inside the <code>plot_image</code> function).</p>