Python / Data Science Essentials Interview Questions
How do you generate reproducible random data with NumPy?
Reproducibility is a core requirement of data science — experiments, train/test splits, and simulations must produce the same result every run so that results can be verified and shared. NumPy's random number generation is the building block for all of this.
import numpy as np # --- Legacy API (still common in older code) --- np.random.seed(42) np.random.rand(3) # [0.374, 0.951, 0.732] â same every time # --- Modern API: Generator (preferred since NumPy 1.17) --- rng = np.random.default_rng(seed=42) # Using a Generator is thread-safe and has better statistical properties rng.random(5) # uniform [0, 1) rng.standard_normal(5) # N(0, 1) rng.normal(loc=170, scale=10, size=1000) # N(mean, std) rng.integers(0, 100, size=10) # random ints in [0, 100) rng.choice(['a','b','c'], size=5, replace=True) # random sampling rng.shuffle(arr) # in-place shuffle rng.permutation(arr) # shuffled copy # --- Distributions used in ML simulations --- rng.binomial(n=10, p=0.3, size=100) # number of successes in n trials rng.poisson(lam=5, size=100) # events per interval rng.exponential(scale=2, size=100) # time between Poisson events rng.uniform(low=0, high=10, size=100) # uniform distribution
The modern Generator API (np.random.default_rng) is preferred over np.random.seed because: the generator is a first-class object you can pass around (not a global state), it is thread-safe, and it uses the PCG64 algorithm which passes more statistical tests than the Mersenne Twister used by the legacy API.
More Related questions...