TensorFlow using a tensor to index another tensor
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
Using one tensor to index another is a normal TensorFlow operation, but the exact API depends on what kind of indexing you need. For simple row or element selection, use tf.gather; for multi-dimensional coordinates, use tf.gather_nd; and for condition-based filtering, use tf.boolean_mask.
Indexing with tf.gather
tf.gather is the closest TensorFlow equivalent to selecting elements by integer index.
Output:
This is the right choice when you have one tensor of positions and want items from another tensor along a single axis.
Gathering Rows from a Matrix
The same function works for higher-rank tensors. By default, it gathers along axis 0.
Output:
If you want to gather columns instead, change the axis:
Multi-Dimensional Coordinates with tf.gather_nd
If each index is a full coordinate, use tf.gather_nd.
Output:
Each row in coords points to one element in the source tensor.
Filtering with tf.boolean_mask
When the index tensor is boolean rather than integer, use tf.boolean_mask.
Output:
This is often the cleanest way to express "select all entries matching a condition."
Why Plain Python Indexing Is Not Always Enough
In eager mode, some simple indexing expressions work naturally:
But for graph-friendly, batched, or dynamic index tensors, the TensorFlow gather APIs are more explicit and more reliable. They also map cleanly to GPU-accelerated kernels and shape inference.
Choosing the Right Operation
Use this rule of thumb:
- '
tf.gatherfor integer indices along one axis' - '
tf.gather_ndfor full multi-axis coordinates' - '
tf.boolean_maskfor boolean selection'
That distinction usually removes the confusion.
Batch Shapes Matter
Indexing bugs in TensorFlow are often shape bugs in disguise. If your source tensor is batched, confirm whether you want to index inside each batch element or across the batch axis itself. Printing tensor.shape before the gather step usually saves time because tf.gather and tf.gather_nd are both strict about how index shapes map to result shapes.
When the index values are produced by a model step such as tf.argmax, it is also worth checking the dtype. Gather operations expect integer index tensors, so accidental casting to floating point will fail even if the numeric values look correct.
Common Pitfalls
- Passing floating-point indices instead of integer tensors.
- Using
tf.gatherwhen the index tensor actually contains full coordinates andtf.gather_ndis required. - Forgetting the
axisargument and gathering along the wrong dimension. - Expecting boolean masks and integer indices to behave like the same operation.
Summary
- TensorFlow supports tensor-based indexing directly, but through specific APIs.
- Use
tf.gatherfor standard integer indexing. - Use
tf.gather_ndfor coordinate-based selection. - Use
tf.boolean_maskfor condition-based filtering. - Picking the right indexing primitive is the main step; the rest is mostly shape management.
Related reading
- Tensorflow Using Adam optimizer
- TensorFlow using LSTMs for generating text
- Tensorflow Using neural network to classify positive or negative phrases
- Tensorflow Using tf.slice to split the input
- Tensorflow v1.10 why is an input serving receiver function needed when checkpoints are made without it?
- TensorFlow ValueError Cannot feed value of shape 64, 64, 3 for Tensor u''Placeholder0'', which has shape ''?, 64, 64, 3''
- Test empty string in mongodb and pymongo
- The best way to sync ActiveRecord structure between rails apps

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the 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.