How do I get value of a tensor in PyTorch?

vainraxe picture vainraxe · Aug 30, 2019 · Viewed 30.2k times · Source
x = torch.tensor([3])

I have a tensor object when I

print(x)

it gives tensor([3])

x.data[0] gives tensor(3) How do I get just 3?

Answer

Vimal Thilak picture Vimal Thilak · Aug 30, 2019

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