Convert class scores into predicted class indices
Classification
PyTorch · Function
Returns the indices of maximum values in a tensor, either globally or across a selected dimension. If maxima are tied, it returns the first maximal index.
torch.argmax reduces a tensor to the index of its largest value. Without dim, it searches the flattened tensor; with dim, it returns one index per slice along that dimension, optionally retaining the reduced dimension with keepdim.
torch.argmax(input, dim=None, keepdim=False) → LongTensor| Name | Type | Description |
|---|---|---|
input | Tensor | Input tensor to examine. |
dim | int, optional | Dimension over which to perform the reduction. |
keepdim | bool, optional; default=False | Whether to retain the reduced dimension with size one. |
LongTensor containing the indices of maximum values.
import torch
scores = torch.tensor([[0.2, 0.8, 0.5], [0.9, 0.1, 0.4]])
predicted_classes = torch.argmax(scores, dim=1)
print(predicted_classes) # tensor([1, 0])Selects the highest-scoring class index independently for each row.
Classification
Reduction
Feature analysis
It returns a LongTensor containing indices rather than the maximum values themselves. With no dim, the result identifies the maximum among all elements; with dim, it identifies a maximum within each slice along that dimension.
Follow-up: How would you obtain both values and indices? Use torch.max(), whose second returned value is the corresponding index tensor.
dim specifies the dimension to reduce. For a two-dimensional tensor, dim=1 computes one index per row, while dim=0 computes one index per column.
Follow-up: What changes when keepdim=True? The reduced dimension is retained with size one, preserving the output's dimensional structure.
When multiple elements share the maximum value, argmax chooses the first maximal element's index. Therefore, it does not return all tied positions.
Follow-up: How can all tied positions be found? Compare the tensor with its maximum value and inspect the matching coordinates, rather than relying on argmax alone.
torch.maxtorch.Tensor.argmax