Random numbers are everywhere in machine learning: splitting data, initialising neural network weights, shuffling, and simulations. NumPy’s modern random API uses a Generator object created with np.random.default_rng().
Prerequisites
Create a Generator
import numpy as np
rng = np.random.default_rng(seed=42)
Explanation: The seed makes results repeatable: the same seed always gives the same numbers. Use a seed whenever you want reproducible experiments.
np.random.rand(), np.random.randint() and np.random.seed(). They still work, but NumPy recommends the Generator API for new code.Random Integers
print(rng.integers(1, 7, size=5)) # dice rolls
print(rng.integers(0, 100, size=(2, 3)))
Explanation: integers(low, high, size): high is excluded. Exact numbers depend on the seed.
Random Floats
print(rng.random(3)) # 0 to 1
print(rng.uniform(10, 20, size=3)) # 10 to 20
Normal Distribution
heights = rng.normal(loc=165, scale=8, size=1000)
print(heights.mean().round(1), heights.std().round(1))
Explanation: loc is the mean and scale the standard deviation. With 1000 samples, the results come out close to 165 and 8.
Choice, Shuffle and Permutation
colors = np.array(['red', 'green', 'blue'])
print(rng.choice(colors, size=4))
print(rng.choice(colors, size=2, replace=False))
a = np.arange(10)
rng.shuffle(a) # in place
print(a)
print(rng.permutation(5)) # new shuffled array
Practical: Train/Test Split by Hand
X = np.arange(20)
idx = rng.permutation(len(X))
train, test = X[idx[:16]], X[idx[16:]]
print(len(train), len(test))
16 4
Old vs New API
| Legacy | Generator API |
|---|---|
| np.random.seed(0) | rng = np.random.default_rng(0) |
| np.random.rand(3) | rng.random(3) |
| np.random.randint(0, 10, 5) | rng.integers(0, 10, 5) |
| np.random.randn(3) | rng.standard_normal(3) |
| np.random.shuffle(a) | rng.shuffle(a) |
Common Errors
| Problem | Cause and fix |
|---|---|
| Different results on every run | Set a seed when creating the generator. |
AttributeError: Generator has no attribute randint |
In the new API the method is called integers(). |
Practice Exercises
- Simulate 1000 coin flips and count heads.
- Generate 5 random 2D points between 0 and 10.
Interview Questions
Q: Why set a random seed?
For reproducible results across runs.
Q: shuffle vs permutation?
shuffle changes the array in place; permutation returns a shuffled copy.
Summary
Create rng = np.random.default_rng(seed) and use integers, random, uniform, normal, choice and permutation.
Next: Math Functions · Slicing and Indexing
Machine Learning Tutorials, Courses and Certifications