shuffling two tensors in the same order
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
If two tensors represent aligned data, such as features and labels, they must be shuffled with the same permutation. Shuffling them independently breaks the correspondence and silently corrupts the dataset. The correct pattern is simple: generate one index order, then apply it to both tensors.
The Core Idea
Suppose x[i] belongs with y[i]. After shuffling, those two items must still travel together. The safest method is:
- create a permutation of row indices
- reorder both tensors with that permutation
That works in NumPy, PyTorch, TensorFlow, and most other array libraries.
TensorFlow Example
Here is a direct TensorFlow solution:
The same indices tensor is used in both tf.gather calls, so row alignment is preserved.
PyTorch Example
In PyTorch, the equivalent pattern uses torch.randperm:
Again, one permutation drives both reorderings.
Dataset APIs Can Be Even Better
If you are already using a dataset abstraction, let it keep the pairs together for you. In TensorFlow:
This is often cleaner in training pipelines because the pair structure is preserved from the start.
Reproducibility
If you need reproducible shuffles, fix the random seed. The exact API depends on the framework:
- NumPy uses
np.random.seed(...) - TensorFlow offers
tf.random.set_seed(...) - PyTorch uses
torch.manual_seed(...)
Be aware that full training reproducibility can require more than just one seed, but synchronized shuffling at least starts with a deterministic permutation.
Why Independent Shuffle Calls Fail
This is wrong:
Both tensors are shuffled, but not by the same order. The data may still look random, which makes the bug easy to miss. Model accuracy then drops for mysterious reasons because the labels no longer match the inputs.
When More Than Two Tensors Are Involved
The same rule scales naturally. If you have inputs, labels, sample weights, masks, or metadata arrays, apply the same permutation to all of them:
The permutation is the source of truth.
Common Pitfalls
The most common mistake is calling a shuffle function on each tensor separately. That breaks alignment immediately.
Another mistake is shuffling along the wrong axis. For supervised learning, you usually want to shuffle rows, not columns or feature dimensions.
A third issue is forgetting that shuffling may happen inside a data loader already. Double shuffling is not always wrong, but it can make debugging harder.
Summary
- To shuffle paired tensors correctly, generate one permutation and apply it to both.
- '
tf.gatherandtorch.randpermare the standard tools for this.' - Dataset APIs can keep pairs together automatically.
- Independent shuffle calls on features and labels are incorrect.
- Use fixed seeds when you need repeatable shuffle order.
Related reading
- Siamese Neural Network in TensorFlow
- significance of trainable and training flag in tf.layers.batch_normalization
- Simple Keras Network in GradientTape LookupError No gradient defined for operation 'IteratorGetNext' op type IteratorGetNext
- Simple Keras neural network isn't learning
- Shut down server in TensorFlow
- Shut down server in TensorFlow
- Sibling package imports
- Simple argparse example wanted 1 argument, 3 results
.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.