Tensor to Numpy, display issue [tensor(0.996515)...]


(Jose Silvestre Rodriguez Ortiz) #1

I am trying to convert two different Tensors to numpy arrays, same way to construct the array, but one display as a Numpy array, and the other one displays a kind of odd format with the word tensor follow by the value in parenthesis, “Tensor(value)”.
-----------------------------CODE--------------------------------
prob, index = output.topk(5)
index_top5 = np.array([index[0][0], index[0][1],index[0][2], index[0][3],index[0][4]])
prob_top5 = np.array([prob[0][0], prob[0][1],prob[0][2], prob[0][3],prob[0][4]])

-----------------------------Results--------------------------------
<class ‘torch.Tensor’>
tensor([[0.996515, 0.003395, 0.000041, 0.000018, 0.000013]])

<class ‘torch.Tensor’>
tensor([[ 94, 55, 77, 1, 83]])

<class ‘numpy.ndarray’>
[94 55 77 1 83]

<class ‘numpy.ndarray’>
[tensor(0.996515) tensor(1.00000e-03 *
3.394803)
tensor(1.00000e-05 *
4.111325)
tensor(1.00000e-05 *
1.837573)
tensor(1.00000e-05 *
1.340192)]


(Alban D) #2

Hi,

You should use torch.from_numpy() and your_tensor.numpy() to convert from and to numpy arrays.
In your case, you can do index[0].numpy() and prob[0].numpy().


(Jose Silvestre Rodriguez Ortiz) #3

@albanD

I tried to convert the Tensor to numpy with the var[0].numpy(), but I get this error .

“RuntimeError: Can’t call numpy() on Variable that requires grad. Use var.detach().numpy() instead.”

Even when I am using torch.no_grad(), that did not solved the issue. do you know if, is there a way to eliminate the grad when converting from Tensor to Numpy?


(Jose Silvestre Rodriguez Ortiz) #4

I was able to solve it, a classmate in Udacity suggested me to do this, var.detach().numpy().item(0) for the first item, and it worked.

Thank you so much for your help! @albanD


(Alban D) #5

Or as the error message suggest, you can just add a detacht before the numpy call: prob[0].detach().numpy(). Both will work.