Choose per-row maxima
Selecting the winning class or option for each row of a score matrix.
NumPy · Function
Returns the integer indices of maximum values in an array, either globally or along a chosen axis. Ties select the first occurrence, and keepdims can preserve reduced dimensions.
Pass an array-like object to select the position of its largest value. With no axis, NumPy conceptually flattens the input; with an axis, it returns one index per slice, and optional keepdims preserves reduced axes as length-one dimensions.
numpy.argmax(a, axis=None, out=None, *, keepdims=<no value>)| Name | Type | Description |
|---|---|---|
a | array_like | Input array. |
axis | int, optional | Axis along which to search; when omitted, indexing is relative to the flattened array. |
out | array, optional | Destination array for the result; it must have an appropriate shape and dtype. |
keepdims | bool, optional | Whether reduced axes remain as dimensions of size one. |
index_array: ndarray of ints. It contains indices into the input, with the selected axis removed, or retained at size one when keepdims=True.
import numpy as np
x = np.array([[1, 9, 3], [8, 2, 7]])
print(np.argmax(x))
print(np.argmax(x, axis=0))
print(np.argmax(x, axis=1, keepdims=True))Computes the flattened index, column-wise indices, and row-wise indices while retaining the reduced dimension.
Selecting the winning class or option for each row of a score matrix.
Finding the location of the largest value in an n-dimensional array.
Producing shape-compatible index arrays for later broadcasting.
With the default axis=None, argmax returns an integer index into the flattened array. Supplying an axis computes indices independently along that dimension.
Follow-up: How can the multidimensional coordinates of the global maximum be recovered? Use np.unravel_index on the flattened argmax result and the input shape.
The output shape removes the selected axis, so each remaining position receives the index of its maximum along that axis. With keepdims=True, the reduced axis remains with size one.
Follow-up: Why might keepdims=True be useful? It preserves dimensional alignment, allowing the result to broadcast against the original array.
The function returns an ndarray of integer indices. An optional out array can receive the result, but it must have the appropriate shape and dtype.
Follow-up: What happens with tied maxima? NumPy returns the index corresponding to the first occurrence.
numpy.ndarray.argmaxnumpy.argminnumpy.amaxnumpy.unravel_index