Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

PyTorch · Function

torch.argmax

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.

How it works

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.

Syntax

torch.argmax(input, dim=None, keepdim=False) → LongTensor

Parameters

NameTypeDescription
inputTensorInput tensor to examine.
dimint, optionalDimension over which to perform the reduction.
keepdimbool, optional; default=FalseWhether to retain the reduced dimension with size one.

Returns

LongTensor containing the indices of maximum values.

Key points

  • With only input, it returns the index of the global maximum.
  • Providing dim performs a reduction independently across that dimension.
  • Its index output corresponds to the indices returned as the second result of torch.max().
  • The dimension-aware overload defaults keepdim to False and returns a LongTensor.

Common mistakes

  • Ties are resolved by returning the index of the first maximum.

Example: Per-row maximum indices

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.

When to use it

Convert class scores into predicted class indices

Classification

Locate the largest element in a tensor

Reduction

Find the strongest feature independently across a chosen axis

Feature analysis

Interview questions

QWhat does torch.argmax return?

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.

QHow do dim and keepdim affect the result?

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.

QHow are ties handled?

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.max
  • torch.Tensor.argmax

Source: torch.argmax — PyTorch main documentation. Checked 2026-10-16.