Statistics and probability for machine learning in Python
Compute distributions, sample variance, conditional probabilities and correlations on small examples and explain the uncertainty in each.
By Invicly Tech, , in AI and Machine Learning with Python. About 11 minutes to read.
In short
Statistics tells you how much to trust a number computed from a sample. You will simulate distributions, compute the mean, variance and standard error, work through conditional probability, and use the bootstrap to put a confidence interval around a result. You will also see why a strong correlation does not prove that one thing causes another.
Think of it like this: A sample is a spoonful of soup: it tells you about the pot, but a bigger or better-stirred spoonful tells you more.
Explained simply
Every dataset is a sample: a limited set of observations from a bigger world. If you measured a different week of customers, you would get slightly different numbers. Statistics is the toolkit for saying how much those numbers would wobble, and so how far to trust them.
The mean is the average. The variance and standard deviation describe how spread out the values are. The standard error describes something different: how much the mean itself would change if you took another sample. It shrinks as the sample grows.
Conditional probability asks: given that one thing happened, how likely is another? A medical test can be very accurate and still be wrong most of the time it says positive, if the illness is rare. Working through the numbers once makes this clear.
Correlation shows two things moving together, but it cannot tell you why. Finally, the bootstrap is a simple computer trick for uncertainty: resample your own data many times, recompute the result, and see how much it varies.
Press Play on a diagram to walk through it one step at a time.
- 1Start with your sample
n observed values.
- 2Resample with replacement
Draw n values; some repeat, some are left out.
- 3Compute the statistic
Mean, accuracy, or any other number.
- 4Store it and repeat
Thousands of times.
- 5Read the spread
2.5th and 97.5th percentiles give a 95 percent interval.
- Back to step 1
- Spread of individual values
- Same units as the data
- Does not shrink with more data
- Spread of the sample mean
- SD divided by square root of n
- Shrinks as n grows
- A range for the true value
- Often mean plus or minus 1.96 SE
- Bootstrap works for any statistic
In depth
Distributions and samples by simulation
A distribution is the pattern of values a process produces. The normal distribution is the familiar bell curve, set by a mean and a standard deviation. The binomial counts successes in a fixed number of yes/no trials, such as clicks out of 100 views. The Poisson counts events in a time window, such as support tickets per hour.
Simulation builds intuition fast. Create a generator with rng = np.random.default_rng(0), then draw rng.normal(50, 10, size=30). Draw it again and the mean changes a little. Repeat 1,000 times and plot the means: they form their own narrower bell curve. That spread of sample means is exactly what the standard error measures.
- rng.normal(mean, sd, size)
- rng.binomial(n, p, size)
- rng.poisson(lam, size)
- scipy.stats has the same distributions with pdf, cdf and ppf
Variance, standard deviation and standard error
Variance is the average squared distance from the mean. For a sample you divide by n minus 1 instead of n, because the sample mean sits closer to its own data than the true mean does. In NumPy that is np.var(x, ddof=1); pandas Series.var() already uses ddof=1, and NumPy defaults to ddof=0, so the two disagree unless you set it.
The standard deviation is the square root of the variance, in the original units. The standard error of the mean is the standard deviation divided by the square root of n. With a standard deviation of 10 and n = 25, the standard error is 2; with n = 100 it is 1. Four times the data halves the uncertainty, which is why extra data has diminishing returns.
Conditional probability with a worked test
P(A | B) means the probability of A given that B is true. Take a disease that affects 1 percent of people and a test that catches 99 percent of cases but also flags 5 percent of healthy people. In 10,000 people, 100 are ill and 99 test positive. Of the 9,900 healthy people, 495 test positive. So 594 positives in total, and only 99 of them are ill: P(ill | positive) is about 17 percent.
This is Bayes' rule in action, and it matters for ML. A fraud model that is right on most transactions can still produce mostly false alarms when fraud is rare. That is why later modules care about precision, not only accuracy.
- 100 ill (1 percent)
- 99 test positive
- 1 tests negative
- 9,900 healthy
- 495 test positive (5 percent)
- 9,405 test negative
Correlation, association and causation
Pearson correlation, np.corrcoef(x, y), measures how close two variables are to a straight-line relationship, from -1 to 1. It misses curved relationships: y = x squared on values from -3 to 3 has a correlation near 0 even though y depends completely on x. Spearman correlation uses ranks and catches any steadily rising or falling pattern.
Association is not causation. A confounder can drive both variables, such as hot weather raising ice cream sales and swimming accidents. Selection can create patterns too: if you only study customers who complained, odd links appear. A model can use correlated features to predict well, but you need an experiment, such as an A/B test, to claim that changing a feature changes the outcome.
Bootstrapping a confidence interval
The bootstrap estimates uncertainty for any statistic without a formula. Resample your n values with replacement, compute the statistic, and repeat a few thousand times. The 2.5th and 97.5th percentiles of those results form a 95 percent percentile interval.
It works for medians, ratios and model accuracy, where formulas are awkward. SciPy offers scipy.stats.bootstrap, which takes the data as a sequence of samples, for example bootstrap((x,), np.median), and uses the BCa method by default. Limits: the bootstrap cannot invent information missing from a small or biased sample, and for time series or grouped data you must resample whole blocks or groups, not single rows.
- Resample with replacement, same size as the data
- Use 2,000 to 10,000 resamples
- Percentiles 2.5 and 97.5 give a 95 percent interval
- Resample whole groups when rows are not independent
Learn it in 5 short steps
About 40m each. Track them with a timer in your plan.
- 1Simulate distributions and samples~40m
- 2Compute mean, variance and standard error~40m
- 3Work through conditional probability~40m
- 4Separate correlation from causation~40m
- 5Bootstrap a confidence interval~40m
Key points
- A distribution describes how often each value occurs; a sample is a finite draw from it.
- Variance measures spread; the standard error measures how much a sample mean would vary between samples.
- Conditional probability, P(A given B), can be very different from P(B given A).
- Correlation measures how two variables move together; it does not prove cause and effect.
- The bootstrap estimates uncertainty for almost any statistic by resampling your data.
Key terms
Tap a card to flip it. 0/6 known
Examples
import numpy as np
rng = np.random.default_rng(0)
sample = rng.normal(loc=50, scale=10, size=40)
mean = sample.mean()
sd = sample.std(ddof=1) # sample standard deviation
se = sd / np.sqrt(len(sample)) # standard error of the mean
boot = [rng.choice(sample, size=len(sample), replace=True).mean() for _ in range(5000)]
lo, hi = np.percentile(boot, [2.5, 97.5])
print(f"mean {mean:.1f}, SE {se:.2f}, 95% bootstrap CI [{lo:.1f}, {hi:.1f}]")The bootstrap interval should be close to mean plus or minus about two standard errors.
Is the new checkout's conversion rate really higher?
Old checkout: 120 purchases from 2,000 visits (6.0 percent). New checkout: 150 from 2,000 (7.5 percent). Step 1: build 0/1 arrays for each version. Step 2: bootstrap the difference in rates 10,000 times. Step 3: read the 95 percent interval. Expected evidence: an interval of roughly 0 to 3 percentage points. If it barely includes or excludes zero, the evidence is weak, and you should collect more data before declaring a winner. The data here is synthetic.
import numpy as np
rng = np.random.default_rng(7)
old = np.r_[np.ones(120), np.zeros(1880)]
new = np.r_[np.ones(150), np.zeros(1850)]
diffs = [rng.choice(new, new.size).mean() - rng.choice(old, old.size).mean()
for _ in range(10_000)]
lo, hi = np.percentile(diffs, [2.5, 97.5])
print(f"difference {new.mean() - old.mean():.3f}, 95% CI [{lo:.3f}, {hi:.3f}]")Correlation that misses a strong relationship
Step 1: create x from -3 to 3 and y = x squared. Step 2: compute Pearson correlation: close to 0. Step 3: plot it and see a perfect U shape. Step 4: compute Pearson on |x| and y: close to 1. Lesson: a correlation near zero does not mean no relationship, so always plot before concluding.
import numpy as np
x = np.linspace(-3, 3, 61)
y = x ** 2
print(round(np.corrcoef(x, y)[0, 1], 3)) # about 0.0
print(round(np.corrcoef(np.abs(x), y)[0, 1], 3)) # about 0.97Quick reference
- rng = np.random.default_rng(seed) for repeatable random draws
- Sample variance: np.var(x, ddof=1); pandas .var() uses ddof=1 already
- Standard error of the mean = SD / sqrt(n); 4x the data halves it
- P(A | B) = P(A and B) / P(B); rare events make positives mostly false
- np.corrcoef(x, y)[0, 1] is Pearson; it only measures straight-line links
- Bootstrap: resample with replacement, recompute, take 2.5 and 97.5 percentiles
Common mistakes
- Using np.var or np.std with the default ddof=0 for a sample; pandas uses ddof=1, so results differ.
- Confusing P(positive test | disease) with P(disease | positive test).
- Reading a correlation as proof that changing one variable will change the other.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Draw 50 values from a normal distribution with mean 100 and SD 15 using seed 3. Print the mean, sample SD and standard error.
- Exercise 2medium
Simulate the medical test from the deep dive for 100,000 people and estimate P(ill | positive). Compare with the exact 17 percent.
- Exercise 3hard
A model got 172 of 200 test rows right. Bootstrap a 95 percent interval for its accuracy, and confirm it with scipy.stats.bootstrap.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Why divide by n minus 1 for sample variance?
- The sample mean is fitted to the same data, so deviations from it are slightly too small. Dividing by n minus 1 corrects that underestimate.
- What is the difference between standard deviation and standard error?
- Standard deviation describes how spread out individual values are. Standard error describes how much an estimate, such as the mean, would change between samples.
- Can machine learning models find causes?
- Standard predictive models find associations, not causes. To claim that changing something causes an effect you need a controlled experiment or dedicated causal inference methods.
- How many bootstrap resamples should I use?
- A few thousand is usually enough for a stable 95 percent interval; 10,000 is a common safe choice for small datasets.