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

Hello, anyone know whats wrong with my code?
I think i already add a img_tensor.cpu().data but its doesnt work

i have a code like this…

#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)
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

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

1 Like

its showing error on line

plot_image(imgs[i], preds[i])
    print("Target")
    plot_image(imgs[i], annotations[i])

Have you tried to add the recommended operations from the error message?
I.e.

plot_image(imgs[i].cpu().numpy(), preds[i].cpu().numpy())

might work.

1 Like

It doesnt work. It showing error message like this :

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-17-1241f3973b9b> in <module>()
      8   for i in range(len(imgs)):
      9     print("Prediction")
---> 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'

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