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

Question:

How do I convert a 1-D IntTensor to an integer? This:

IntTensor.int()

Gives an error:

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

||

Answers:

You can use:

print(dictionary[IntTensor.data[0]])

The key you’re using is an object of type autograd.Variable.
.data gives the tensor and the index 0 can be used to access the element.

Answered By: skb

The simplest and cleanest method I know:

IntTensor.item()

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

Answered By: Marcin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.