Print or record a scalar metric as a Python value.
Logging
PyTorch · Module
Converts a one-element tensor into its value as a standard Python number. The operation is not differentiable and is intended for scalar extraction.
Call item() on a tensor containing exactly one element to obtain its value as a regular Python number. The conversion is intended for scalar extraction and does not participate in automatic differentiation.
torch.Tensor.item() → numberA standard Python number containing the value of the one-element tensor.
import torch
x = torch.tensor([1.0])
value = x.item()
print(value) # 1.0Converts a one-element tensor into a standard Python number.
Logging
Interop
Control flow
Tensor.item() converts a one-element tensor into a standard Python number. It is useful when an ordinary Python scalar is required instead of a tensor.
Follow-up: What happens for a tensor with several elements? item() is not the appropriate operation; use indexing, reduction, or tolist() depending on the intended result.
The tensor must contain exactly one element. A tensor with more than one element cannot be converted by item().
Follow-up: How can a collection of values be converted instead? Use tolist(), which is the alternative identified by the documentation for other cases.
item() is not differentiable, so its result does not preserve an autograd path. Use it when leaving tensor-based computation is intentional.
Follow-up: Why might calling item() inside a training computation be undesirable? It extracts a Python value and therefore cannot support gradient propagation through that value.
torch.Tensor.tolisttorch.Tensor