argmax() finds the position of the maximum value along the given axis, rather than the value itself — for a model's output layer producing one score per possible class, argmax() along the class axis identifies which class received the highest score, the model's actual predicted class. Without specifying an axis, it defaults to operating on the last axis, unlike NumPy's np.argmax(), which defaults to flattening the entire array first, which conveniently matches the common case of a tensor shaped as (batch_size, num_classes), where the class scores are the last dimension.
1Understanding tf.argmax()
argmax() finds the position of the maximum value along the given axis, rather than the value itself — for a model's output layer producing one score per possible class, argmax() along the class axis identifies which class received the highest score, the model's actual predicted class. Without specifying an axis, it defaults to operating on the last axis, unlike NumPy's np.argmax(), which defaults to flattening the entire array first, which conveniently matches the common case of a tensor shaped as (batch_size, num_classes), where the class scores are the last dimension.
tf.argmax() defaults to operating along the last axis, unlike NumPy's np.argmax(), which defaults to flattening the whole array first — this default conveniently matches the common (batch_size, num_classes) shape of classification model outputs, letting you call it with no axis argument in that specific case.
import tensorflow as tf
scores = tf.constant([0.1, 0.7, 0.2])
print(tf.argmax(scores))2Practical Example
Here is a real-world application of tf.argmax() showing how it is used in production TensorFlow code.
import tensorflow as tf
batch_scores = tf.constant([[0.1, 0.7, 0.2], [0.6, 0.1, 0.3]])
predictions = tf.argmax(batch_scores, axis=1)
print(predictions)3Best Practices
Follow these guidelines when working with tf.argmax():
1. Use tf.argmax() to convert a model's per-class score/probability output into a single predicted class index, rather than manually scanning for the largest value
2. Rely on the default last-axis behavior for standard (batch_size, num_classes) shaped model outputs, but specify axis explicitly for anything with a different shape convention
3. Cast the result to a Python int, or compare it against integer labels with matching dtype, when checking predictions against ground-truth labels
Tip: tf.argmax() defaults to operating along the last axis, unlike NumPy's np.argmax(), which defaults to flattening the whole array first — this default conveniently matches the common (batch_size, num_classes) shape of classification model outputs, letting you call it with no axis argument in that specific case.
import tensorflow as tf
scores = tf.constant([0.1, 0.7, 0.2])
print(tf.argmax(scores))