Search notes:

torch.Tensor: item() / tolist()

item()

The method item() of a torch.Tensor returns a Python scalar value (float, int etc.) if the tensor has exactly one element.
If the tensor has more than one elements, torch throws the RuntimeError a Tensor with … elements cannot be converted to Scalar

tolist()

tolist() returns the elements of a tensor as a nested list) except if the tensor has only one element in which case tolist() behaves like item().

Example

from torch import tensor

t_1x1 = tensor([ 2 ])

t_3x2 = tensor([ [ 1 , 2 ],
                 [ 3 , 4 ],
                 [ 5 , 6 ]
              ])

print(t_1x1.item())
#
# 2

# RuntimeError: a Tensor with 6 elements cannot be converted to Scalar
# print(t_3x2.item())

print(t_3x2[2,1].item())
#
# 6


for row in t_3x2.tolist():
    for item in row:
        print(item, end = ' ')
    print('')
#
# 1 2
# 3 4
# 5 6

Index