item

paddle.Tensor. item ( self, *args )

Convert one element Tensor to a Python scalar.

Parameters

*args (int) – The input coordinates. If it’s single int, the data in the corresponding order of flattened Tensor will be returned. Default: None, and it must be in the case where Tensor has only one element.

Returns(Python scalar): A Python scalar, whose dtype is corresponds to the dtype of Tensor.

Raises

ValueError – If the Tensor has more than one element, there must be coordinates.

Examples

import paddle

x = paddle.to_tensor(1)
print(x.item())             #1
print(type(x.item()))       #<class 'int'>

x = paddle.to_tensor(1.0)
print(x.item())             #1.0
print(type(x.item()))       #<class 'float'>

x = paddle.to_tensor(True)
print(x.item())             #True
print(type(x.item()))       #<class 'bool'>

x = paddle.to_tensor(1+1j)
print(x.item())             #(1+1j)
print(type(x.item()))       #<class 'complex'>

x = paddle.to_tensor([[1.1, 2.2, 3.3]])
print(x.item(2))            #3.3
print(x.item(0, 2))         #3.3

x = paddle.to_tensor([1, 2])
x.item()               #ValueError: only one element tensor can be converted to Python scalar when no input coordinates.