I am trying to get a numerical value out of a tensor. If I print it, I get
Variable containing:
0.9546
[torch.cuda.FloatTensor of size 1 (GPU 0)]
How can I get just the 0.9546 ?
I am trying to get a numerical value out of a tensor. If I print it, I get
Variable containing:
0.9546
[torch.cuda.FloatTensor of size 1 (GPU 0)]
How can I get just the 0.9546 ?
You first need to get tensor out of the variable using .data
Then you need to move the tensor to cpu using .cpu()
After that you can convert tensor to numpy using .numpy()
And you probably know the rest… So basically a.data.cpu().numpy()[0]
will give you just the value
You don’t need either the .cpu or the .numpy.
Thanks, seems to work with a.data[0]
Note that this only works if the tensor is 1-dimensional. Consider the following 2-dimensional tensor:
In [16]: y
Out[16]:
Variable containing:
0.8057 0.4009 0.0189
0.8005 0.0217 0.7259
[torch.FloatTensor of size 2x3]
In [17]: y.data
Out[17]:
0.8057 0.4009 0.0189
0.8005 0.0217 0.7259
[torch.FloatTensor of size 2x3]
In [18]: y.data[0]
Out[18]:
0.8057
0.4009
0.0189
[torch.FloatTensor of size 3]
if you want only numerical,Ithink you can do like this.
Variable.data---->tensor
Variable.data.tolist()---->list
Variable.data.tolist()[0]---->folat
Use variable.item() when the tensor holds a single value like in your example.
This is deprecated and will soon disappear from the API. Consider using variable.item()
instead for 0-dim tensors. For higher-dimensional variables, use variable.tolist()
.
Thanks for simple suggestion
Assume the tensor_x is the tensor tensor([0.9546]) u got, and x is the value 0.9546 u want. Each way of tensor_x.item() and (float)(tensor_x.cpu().detach().numpy()) and (float)(tensor_x.data.cpu().numpy()[0]) can solve ur problem.
thanks. this really helped me.