How to cast a 1-d IntTensor to int in Pytorch

Ruben picture Ruben · Dec 1, 2017 · Viewed 28.6k times · Source

I get a 1-D IntTensor,but i want to convert it to a integer. I try it by this method:

print(dictionary[IntTensor.int()])

but got an error:

KeyError: Variable containing:
 423
[torch.IntTensor of size 1]

Thanks~

Answer

Marcin picture Marcin · Oct 21, 2018

The simplest and cleanest method I know:

IntTensor.item()

From PyTorch docs:

"Returns the value of this tensor as a standard Python number. This only works for tensors with one element. For other cases, see :meth:~Tensor.tolist"