Lesson 16 of 16 · Distributions
Sampling in Python
Sample from distributions with Python's random module and NumPy's default_rng: seeds, sampling with and without replacement, Monte Carlo and train/test splits.
- 8 min read
- Intermediate
- Reviewed
- Draw random numbers and choices with Python's random module
- Sample from common distributions with NumPy's default_rng
- Use seeds to make random results reproducible
- Tell sampling with replacement apart from sampling without replacement
- Estimate quantities by Monte Carlo simulation, and know how accurate they are
- Make a reproducible train/test split
Randomness on a computer
Every simulation in this course used random numbers. Computers usually make them with a pseudo-random number generator: a formula that produces a sequence of numbers that look random and pass statistical tests, but are completely determined by a starting value.
The random module
Python's built-in random module covers most everyday needs:
import random
random.seed(42) # same seed, same "random" results every run
print("random(): ", round(random.random(), 4)) # a float from 0 up to (not including) 1
print("randint: ", random.randint(1, 6)) # a whole number from 1 to 6, both included
print("uniform: ", round(random.uniform(0, 15), 2))
print("gauss: ", round(random.gauss(170, 8), 1)) # a normal value: mean 170, sd 8
print("choice: ", random.choice(["red", "green", "blue"]))
# choices: WITH replacement, optionally weighted
print("choices: ", random.choices(["spam", "ham"], weights=[0.2, 0.8], k=8))
# sample: WITHOUT replacement, so no repeats
print("sample: ", random.sample(range(1, 50), k=6))
deck = ["A", "K", "Q", "J", "10"]
random.shuffle(deck) # shuffles the list in place
print("shuffled: ", deck)Run it again and you'll get exactly the same output, because of random.seed(42). Delete the seed line and every run will differ.
NumPy's random generator
For data science, NumPy's generator is faster and can draw thousands of values at once. Create one with np.random.default_rng(seed), then call a method for each distribution. Here are distributions from this course, with 100,000 draws each:
import numpy as np
rng = np.random.default_rng(seed=16) # NumPy's recommended random generator
size = 100_000
samples = {
"binomial(20, 0.3)": (rng.binomial(20, 0.3, size), 20 * 0.3, 20 * 0.3 * 0.7),
"poisson(4)": (rng.poisson(4, size), 4, 4),
"normal(170, 8)": (rng.normal(170, 8, size), 170, 8 ** 2),
"exponential(rate 2)": (rng.exponential(scale=1 / 2, size=size), 1 / 2, 1 / 4), # scale = 1 / rate
}
print(f"{'distribution':20} {'sample mean':>12} {'theory':>8} {'sample var':>11} {'theory':>8}")
for name, (x, mean, var) in samples.items():
print(f"{name:20} {x.mean():12.3f} {mean:8.3f} {x.var():11.3f} {var:8.3f}")
print("one die, 10 rolls:", rng.integers(1, 7, size=10)) # the upper limit is excludedEvery sample mean and variance lands close to the formulas from lessons 11 to 15.
| Distribution | random module | NumPy generator rng |
|---|---|---|
| Uniform whole numbers | randint(1, 6) (6 included) | rng.integers(1, 7) (7 excluded) |
| Uniform 0 to 1 | random() | rng.random() |
| Normal | gauss(mu, sigma) | rng.normal(mu, sigma) |
| Binomial | binomialvariate(n, p) | rng.binomial(n, p) |
| Poisson | not built in | rng.poisson(lam) |
| Exponential | expovariate(rate) | rng.exponential(scale=1/rate) |
| Pick from a list | choice, choices, sample | rng.choice(items, size, replace, p) |
| Shuffle | shuffle(items) | rng.permutation(items) |
Monte Carlo simulation
When a probability is hard to calculate, you can simulate it many times and count. That's called Monte Carlo simulation, after the famous casino. It can even estimate π: throw random points into a square, and the share that lands inside a quarter circle is π/4.
import numpy as np
rng = np.random.default_rng(seed=8)
# Monte Carlo: throw random points into a 1 x 1 square. The share that lands inside
# the quarter circle of radius 1 is pi/4, so 4 x (that share) estimates pi.
for n in (100, 10_000, 1_000_000):
x, y = rng.random(n), rng.random(n)
estimate = 4 * np.mean(x ** 2 + y ** 2 <= 1)
print(f"{n:>9,} points: pi is about {estimate:.4f} (error {abs(estimate - np.pi):.4f})")Each 100-fold increase in points makes the error roughly 10 times smaller. That's the σ/√n rule from lesson 12: a Monte Carlo estimate is an average, so its error shrinks like 1/√n. Twice the accuracy costs four times the samples.
Reproducible train/test splits
Machine learning uses random sampling constantly: shuffling data, splitting it, initialising weights and picking mini-batches. To compare models fairly, the split should be the same every time:
import numpy as np
n_rows = 10 # imagine a table of 10 labelled examples
for run in (1, 2):
rng = np.random.default_rng(seed=7) # fixing the seed makes the split repeatable
order = rng.permutation(n_rows) # the row numbers 0 to 9, shuffled
train, test = order[:8], order[8:] # 80% for training, 20% for testing
print(f"run {run}: train rows {sorted(train.tolist())}, test rows {sorted(test.tolist())}")Same seed, same split. Shuffling first matters: if the data were sorted, for example by date or by label, taking the first 80% without shuffling would give the model a biased view.
Common mistakes
Make a reproducible 80/20 train/test split of 1,000 rows, then check it: no row should be in both sets, and every row should be used.
import numpy as np rng = np.random.default_rng(seed=42) n_rows = 1000 order = rng.permutation(n_rows) # the row numbers 0 to 999, in a random order # Split the shuffled row numbers: the first 80% for training, the rest for testing. # Then print on one line: the size of the training set, the size of the test set, # how many row numbers appear in both sets, and how many different row numbers are used in total.
You deal 5 cards from a shuffled deck. Which function matches this kind of sampling?
Summary
- Computers use pseudo-random generators; a seed makes their results reproducible.
- The
randommodule hasrandom,randint,uniform,gauss,choice,choices,sampleandshuffle. - NumPy's
default_rngdraws large samples quickly from many distributions. - With replacement allows repeats; without replacement doesn't.
- Monte Carlo estimates have errors that shrink like 1/√n.
- Shuffle with a fixed seed for reproducible train/test splits.
Course complete! You can now reason about chance, update beliefs with Bayes' theorem, and describe, calculate and simulate random variables and distributions. The Statistics course builds on this to learn from data: estimates, confidence intervals and hypothesis tests.
Finished reading? Tick it off to track your progress.