Statistics · medium

What is the bootstrap, and when would you use it instead of a formula?

Asked in Data Scientist interviews, in the Statistics round.

Short answer

Resample the data with replacement many times, recompute the statistic each time, and read the spread off those results. Use it when there is no clean formula for the standard error: medians, ratios, percentiles, or a metric per user with heavy tails.

How to answer it

Definition

Resample your data with replacement many times, recompute the statistic on each resample, and use the spread of those values as its sampling distribution. It replaces a formula for the standard error with simulation.

Approach

Example

import numpy as np
rng = np.random.default_rng(0)

def boot_ci(x, stat=np.median, n=10_000, alpha=0.05):
    x = np.asarray(x)
    stats = [stat(rng.choice(x, size=len(x), replace=True)) for _ in range(n)]
    lo, hi = np.percentile(stats, [100 * alpha / 2, 100 * (1 - alpha / 2)])
    return lo, hi

print(boot_ci(revenue))

Output

(41.20, 47.85)     a 95% interval for the MEDIAN,
                   which has no simple closed-form standard error

When it earns its place

When not to

Key points

FAQ

The 30-second answer

The bootstrap estimates the sampling distribution of a statistic by resampling the data with replacement, computing the statistic each time, and using the spread of those values. A ninety-five percent interval is just the two-point-five and ninety-seven-point-five percentiles of the results.
I reach for it when there is no clean formula for the standard error, which covers medians, percentiles and ratios of two metrics, or when the parametric assumptions look shaky and the sample is not big enough for the central limit theorem to cover me.
What I would be careful about is that it does not manufacture information. With a small or biased sample it reproduces that bias confidently, and for time series I would resample blocks rather than individual points, because plain resampling destroys the dependence.

In the interview

Practice this for real