pythonpytorchtensor

How do I get the value of a tensor in PyTorch?


Printing a tensor x gives:

>>> x = torch.tensor([3])
>>> print(x)
tensor([3])

Indexing x.data gives:

>>> x.data[0]
tensor(3)

How do I get just a regular non-tensor value 3?


Solution

  • You can use x.item() to get a Python number from a Tensor that has one element.