Random Choice with Pytorch?
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
PyTorch does not have a single drop-in function that behaves exactly like numpy.random.choice in every case, but it does provide the building blocks you usually need. The right tool depends on whether you want to sample indices uniformly, sample values from a tensor, shuffle without replacement, or perform weighted random sampling.
In practice, the most useful APIs are torch.randint, torch.randperm, and torch.multinomial. Once you understand the difference between them, “random choice” in PyTorch becomes straightforward.
Use torch.randint for Uniform Sampling with Replacement
If you want random indices where the same index can appear more than once, torch.randint is the simplest option.
This is uniform sampling with replacement. Each draw is independent, so duplicates are allowed.
Use torch.randperm to Shuffle Without Replacement
When you want a random ordering of all positions, use torch.randperm.
If you only need k unique choices, slice the permutation:
This is the usual answer when you need random unique elements.
Use torch.multinomial for Choice-Like Sampling
torch.multinomial is the closest PyTorch equivalent to “choose items according to probabilities.” It works with a tensor of non-negative weights.
The code above shows the sampling step, but PyTorch tensors cannot store Python strings directly in this form. In real code, keep labels in a Python list and sample indices:
If replacement=False, each index can appear at most once, assuming you do not request more samples than there are positive-weight entries.
Sample Rows from a Tensor
A very common use case is randomly selecting rows from a dataset tensor.
This pattern is useful for quick experiments, small custom training loops, or subsampling data for visualization.
Reproducibility Matters
If you want stable results for debugging, set a seed with torch.manual_seed.
Without a seed, repeated runs will generate different samples, which is usually what you want in training but not always what you want in tests.
Which Function Should You Use?
Use torch.randint when repeated picks are fine and you want raw random indices. Use torch.randperm when you need a shuffled order or unique samples. Use torch.multinomial when some choices should be more likely than others.
That mapping is more useful than searching for one magical “PyTorch choice” function, because the correct semantics matter more than the name.
Common Pitfalls
One common mistake is expecting torch.randperm to support weighted sampling. It does not; it simply returns a uniform random permutation.
Another issue is forgetting the difference between sampling with and without replacement. If duplicates appear unexpectedly, check whether you used replacement=True.
People also sometimes try to store strings in a numeric tensor and then wonder why the example fails. PyTorch tensors are numeric containers, so sampling labels usually means sampling indices first and then mapping those indices back to Python objects or another structure.
Finally, if your weights tensor contains negative values or all zeros, torch.multinomial will fail. Validate the weights before sampling.
Summary
- PyTorch random choice is usually built from
torch.randint,torch.randperm, ortorch.multinomial. - Use
torch.randintfor uniform sampling with replacement. - Use
torch.randpermfor shuffling or unique sampling without replacement. - Use
torch.multinomialfor weighted sampling. - Set
torch.manual_seedwhen you need reproducible random results.
Related reading
- Remove downloaded tensorflow and pytorchHugging face models
- return_sequences False equivalent in pytorch LSTM
- Run Identical model on multiple GPUs, but send different user data to each GPU
- RuntimeError Attempting to deserialize object on a CUDA device
- Random forest class_weight and sample_weight parameters
- Random Forest Feature Importances vs Correlation Matrix
- Random Forest Regression - How do I analyse its performance? - python, sklearn
- Random Forest with bootstrap False in scikit-learn python
.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.