How to get top n arg max/min in tensorflow?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Finding the top n largest or smallest values in a tensor is a common step in model post-processing, ranking, beam search, and feature analysis. In TensorFlow, the best tool depends on whether you need only the top results, all sorted indices, or control over the axis being processed.
Use tf.math.top_k for the Largest Values
If you need the indices of the largest n elements, tf.math.top_k is the most direct API. It returns both the values and the indices for the last dimension.
Typical output is:
That means the three largest values are at positions 1, 3, and 4.
tf.math.top_k is usually better than sorting the full tensor when you only need a small number of top results.
Get the Smallest Values with tf.argsort
For the smallest values, the most readable solution is often tf.argsort in ascending order, followed by slicing.
This returns the indices of the three smallest values, then gathers the values themselves.
You can also use tf.argsort(..., direction="DESCENDING")[:n] for the top maximum values if you want a single sorting-based pattern for both cases.
Using tf.math.top_k for Minimum Values
Another common trick is to negate the tensor. The smallest original values become the largest negated values.
This works well when you want the efficiency of top_k but for minimum values.
Working with Matrices and Batches
Both tf.math.top_k and tf.argsort operate along an axis. tf.math.top_k uses the last dimension, which is convenient for batched model outputs.
Each row gets its own top two entries. This is especially common in classification tasks where each row represents one example and each column represents one class.
If you need a different axis, tf.argsort is often more flexible because it accepts an axis parameter directly.
Which Function Should You Choose?
Use tf.math.top_k when:
- You only need the largest
nvalues - You want both values and indices
- The last axis is the correct axis
Use tf.argsort when:
- You need full sorted order
- You want ascending and descending with one API
- You need to slice along a custom axis more explicitly
Both are valid; the right one depends on your shape and performance requirements.
Common Pitfalls
A frequent mistake is forgetting that tf.math.top_k works on the last dimension. If your ranking dimension is elsewhere, the output can look wrong even though the operation is technically valid.
Another mistake is slicing values but forgetting to gather the original tensor when using tf.argsort. tf.argsort returns indices, not the values themselves.
A third mistake is using full sorting when only the top few entries are needed. That can be slower than tf.math.top_k, especially for large tensors.
Summary
- Use
tf.math.top_kto get the largestnvalues and indices efficiently. - Use
tf.argsortwhen you want sorted indices for minimum or maximum selection. - For smallest values, either sort ascending or apply
top_kto the negated tensor. - Pay attention to the axis, especially for batched tensors.
- Gather values explicitly when your workflow starts from indices.
Related reading
- How to get weight matrix of one layer at every epoch in LSTM model based on Keras?
- How to get weights in tf.layers.dense?
- How to give a constant input to keras
- How to handle large amouts of data in tensorflow?
- How to get value of a Keras tensor in TensorFlow 2?
- How to get VirtualEnv TensorFlow to work in PyCharm?
- How to get weights from .pb model in Tensorflow
- How to get weights from tensorflow fully_connected
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.