Classification predictions
Choose the winning class for each item from model scores.
PyTorch · Function
Returns the maximum value of a tensor, either globally or along a chosen dimension. Dimension-wise reduction also returns the index of each maximum.
torch.max reduces a tensor either across every element or along one selected dimension. With no dimension, it returns one maximum tensor; with a dimension, it returns named values and indices, optionally preserving the reduced dimension.
torch.max(input, *, out=None) → Tensor
torch.max(input, dim, keepdim=False, *, out=None) → (Tensor, LongTensor)| Name | Type | Description |
|---|---|---|
input | Tensor | Input tensor to reduce. |
dim | int, optional | Dimension to reduce. If omitted, all dimensions are reduced; explicit None is unsupported. |
keepdim | bool, optional | Whether to retain the reduced dimension. Defaults to False. |
out | Tensor or tuple, optional | Optional output tensor or tuple of output tensors, depending on the overload. |
Without dim, a tensor containing the maximum of all input elements. With dim, a namedtuple (values, indices), where values contains dimension-wise maxima and indices contains their locations.
import torch
x = torch.tensor([[1.0, 4.0, 2.0], [5.0, 3.0, 5.0]])
values, indices = torch.max(x, dim=1)
print(values) # tensor([4., 5.])
print(indices) # tensor([1, 0])Reduces each row and returns both its maximum value and the index of that value.
Choose the winning class for each item from model scores.
Collapse spatial, temporal, or batch axes while retaining optional singleton dimensions.
Retrieve both best scores and their positions for downstream selection.
With only input, torch.max returns the maximum over all elements as a scalar tensor. Supplying dim changes the result to a named tuple containing values and indices for each reduced slice.
Follow-up: How do you retain the reduced axis? Pass keepdim=True, which leaves that dimension at size one.
keepdim=False is the default, so the reduced dimension is removed from both outputs. With keepdim=True, the outputs retain the input rank and use size one along dim.
Follow-up: What happens if dim is omitted? All dimensions are reduced, producing a single maximum value.
For a dimension-wise reduction, values contains the maxima and indices contains their locations along dim. If equal maxima occur, indices selects the first maximal value.
Follow-up: Which related operation returns only locations? torch.argmax returns maximum-value indices.
torch.argmaxtorch.squeezetorch.Tensor.max