Calculating precision gives error: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first

I am getting this error while returning the precision_score:

 from sklearn.metrics import  precision_score
 def calculate_precision(outputs, targets):
      batch_size = targets.size(0)

     _, pred = outputs.topk(1, 1, True)
     pred = pred.t()
     return  precision_score(targets.view(-1), pred.view(-1), average = 'macro')

Please help, I am new to pytorch. Thanks!

Hi,

The problem is that your code tries to convert a cuda tensor to numpy. I guess in your case, it’s the sklearn function that actually try to do the conversion.
Unfortunately, numpy does not support cuda but only cpu tensors.
So you need to change the cuda tensor to a cpu tensor first, then you can convert it to numpy.
You can do this as:

return  precision_score(targets.view(-1).cpu(), pred.view(-1).cpu(), average = 'macro')

Note that you can also do the numpy conversion before calling the sklearn function if you have any more issue with conversion:

np_target = targets.view(-1).cpu().numpy()
np_pred = pred.view(-1).cpu().numpy()
return  precision_score(np_target, np_pred, average = 'macro')
1 Like

Thanks a lot @albanD