Random Numbers

Generate random data for simulations, sampling and reproducible experiments.

Syntaxrng = np.random.default_rng(seed=42)

Machine learning uses randomness constantly: shuffling data, initialising weights, sampling. NumPy's random module supplies it.

Reproducibility

Set a seed so the 'random' numbers come out the same every run — essential for repeatable experiments.

Example

Example · python
import numpy as np

rng = np.random.default_rng(seed=42)

print(rng.random(3))          # 3 floats in [0, 1)
print(rng.integers(1, 7, 5))  # 5 dice rolls
print(rng.normal(0, 1, 3))    # 3 samples, normal dist
# Same seed -> same numbers every time

When to use it

  • An ML researcher seeds the numpy random generator before shuffling a dataset split to ensure the train/test partition is reproducible across runs.
  • A simulation engineer uses np.random.normal to generate synthetic Gaussian noise added to sensor readings for data augmentation.
  • A statistician uses np.random.choice to sample without replacement from a dataset to build bootstrap confidence intervals.

More examples

Reproducible random seed

Creates a seeded random Generator so every run produces the same sequence of numbers, making experiments reproducible.

Example · python
import numpy as np

rng = np.random.default_rng(seed=42)
samples = rng.random(5)
print(samples)   # same values on every run

Normal and uniform distributions

Generates 100 Gaussian noise samples and 100 uniform samples, showing the two most common distributions in ML data augmentation.

Example · python
import numpy as np

rng = np.random.default_rng(0)
noise  = rng.normal(loc=0, scale=1, size=(100,))   # Gaussian
uniform = rng.uniform(low=0, high=1, size=(100,))  # uniform
print(noise.mean(), noise.std())
print(uniform.min(), uniform.max())

Random integer indices for sampling

Draws 32 unique random indices into a dataset to form a mini-batch, mimicking a stochastic gradient descent sampling step.

Example · python
import numpy as np

rng = np.random.default_rng(7)
dataset_size = 1000
batch_size = 32

idx = rng.choice(dataset_size, size=batch_size, replace=False)
print(idx[:10])   # 10 of the 32 random indices

Discussion

  • Be the first to comment on this lesson.