MCPcopy Create free account
hub / github.com/PaddlePaddle/Paddle / item

Function item

python/paddle/base/dygraph/tensor_patch_methods.py:838–896  ·  view source on GitHub ↗

Convert element at specific position in Tensor into Python scalars. If the position is not specified, the Tensor must be a single-element Tensor. Args: *args(int): The input coordinates. If it's single int, the data in the corresponding order of flattened Tensor

(self: Tensor, *args: int)

Source from the content-addressed store, hash-verified

836 self.clear_gradient()
837
838 def item(self: Tensor, *args: int) -> float | bool | complex:
839 """
840 Convert element at specific position in Tensor into Python scalars. If the position is not specified, the Tensor must be a
841 single-element Tensor.
842
843 Args:
844 *args(int): The input coordinates. If it's single int, the data in the corresponding order of flattened Tensor will be returned.
845 Default: None, and it must be in the case where Tensor has only one element.
846
847 Returns(Python scalar): A Python scalar, whose dtype is corresponds to the dtype of Tensor.
848
849 Raises:
850 ValueError: If the Tensor has more than one element, there must be coordinates.
851
852 Examples:
853 .. code-block:: pycon
854
855 >>> import paddle
856
857 >>> x = paddle.to_tensor(1)
858 >>> print(x.item())
859 1
860 >>> print(type(x.item()))
861 <class 'int'>
862
863 >>> x = paddle.to_tensor(1.0)
864 >>> print(x.item())
865 1.0
866 >>> print(type(x.item()))
867 <class 'float'>
868
869 >>> x = paddle.to_tensor(True)
870 >>> print(x.item())
871 True
872 >>> print(type(x.item()))
873 <class 'bool'>
874
875 >>> x = paddle.to_tensor(1 + 1j)
876 >>> print(x.item())
877 (1+1j)
878 >>> print(type(x.item()))
879 <class 'complex'>
880
881 >>> x = paddle.to_tensor([[1.1, 2.2, 3.3]])
882 >>> print(x.item(2))
883 3.299999952316284
884 >>> print(x.item(0, 2))
885 3.299999952316284
886
887 """
888 # resolve the error issue in scenario of pipeline parallel
889 # where some devices do not have self data, return None does not affect
890 # the execution result in those devices, so currently we return None
891 if self.is_dist() and not self._is_initialized():
892 return None
893 scalar = self._getitem_from_offset(*args)
894 if scalar.dtype == np.uint16:
895 return convert_uint16_to_float(scalar).item()

Callers 1

itemMethod · 0.85

Calls 3

convert_uint16_to_floatFunction · 0.90
is_distMethod · 0.80
itemMethod · 0.80

Tested by

no test coverage detected