Retrieve Tensor as scalar value with `Tensor.data` not working

This question refers to latest version in master branch.

When we define a Tensor object, what is the best way to retrieve one of element as scalar value ?

x = torch.Tensor([2, 3])
  • x.data[0] still returns Tensor type

  • x.numpy()[0] gives scalar value, but with type numpy.int64 which sometimes leads to problems

  • x.tolist()[0] returns int type.

Seems for now tolist() works well. The question is, why x.data does not return int type ?

2 Likes

Hi,

If you want to get the value as a python number, you can use the .item() method: x[0].item() in your example.

5 Likes

Cool ! Thanks for the help. btw, is item() documented already ? I cannot manage to find it here

Doesn’t look like so idd.
This is weird, because it is actually listed in the code doc here not sure what happened here :confused:
@smth is that a doc generation issue? Or something I’m missing here with the doc?

Thanks for pointing that out. We need to add it to docs/source/tensors.rst as well.

1 Like

Made a PR already.