How to use tensor.item()

Hi,

My program has zero-dimension tensor like a

[1, 2, 3, ...]

I want to fetch one item from the tensor, so I did

scalar_val = val[index_val].item()

But it still makes same error of;

IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number

How to solve this issue?

Best,
S.Takano

Are you sure that val is not a Tensor with a single number already?

The dimension you defined is not correct according to the example. it must be 1-dimensional not 0-dimensional, so for accessing one dimension it is correct way to call “item” method

c = torch.tensor([1, 2, 3, 4])
print (c[0].item())
print (c.ndimension())

1
1

In Case of Zero Dimension Example

c = torch.tensor(20)
print (c.ndimension()) 
print (c.item())

0
20

I hope it makes clear to you