Level 3 In-Depth AI · Math Foundations
Statistics: Mean, Variance and Sampling
Statistics summarises data with a few honest numbers — the typical value, the spread, how two things move together — and tells you how much to trust a number measured on a sample. It is why a model's score on a small test set can lie.
- Level
- ●●●●● Beginner
- Reading
- 13 min
- To learn it well
- 50 minutes to read, an hour to practise
- Builds on
- 1 concept →
- Quiz
- 5 questions ↓
Read first
Probability BasicsThis leads to
—The full path from zero — 1 concept before this one
- Probability Basics
- Statistics: Mean, Variance and Sampling
Read them roughly in this order. See it on the concept map →
Why it matters
Machine learning runs on data, and the first thing you do with any data is summarise it. What's a typical value? How spread out are the values? Do two columns move together? Are there strange values that will confuse a model? Answering these questions is called descriptive statistics, and it is the start of every Data Cleaning and Preparation job.
Statistics also answers a second, subtler question that matters every time you evaluate an AI system: how much can I trust a number measured on a sample? Your model scored 87% on 200 test examples. Your colleague's scored 85%. Is yours really better, or did you just get luckier test questions? As this chapter shows, with 200 examples that 2-point gap is well within the noise. Many published "improvements" in machine learning, and many decisions made from dashboards, are just this kind of luck.
The ideas here are also built into AI methods themselves:
- Standardising features (subtract the mean, divide by the standard deviation) is used before almost every model.
- Batch and layer normalisation compute means and variances inside neural networks.
- Evaluation Metrics, Cross-Validation and Evaluating LLMs and Benchmarks are about estimating performance honestly from limited data.
The intuition
Imagine a class of 30 students' exam scores. You can't remember 30 numbers, so you summarise:
- Where's the middle? The average score, or the score of the student exactly in the middle.
- How spread out? Did everyone score about the same, or do scores range from 20 to 100?
- What goes with what? Did students who studied more score higher?
Then a deeper question. Your class is just one class. If the school wants to know how all 3,000 students would do, your 30 are a sample from that bigger population. A different class would have given a slightly different average. Statistics tells you how different, and so how much your sample's numbers can be trusted. The rule of thumb: averages from bigger samples wobble less, but only in proportion to the square root of the sample size. Four times the data halves the wobble.
Key idea Summarise data with a centre (mean or median) and a spread (standard deviation). Any number measured on a sample, including a model's test accuracy, comes with uncertainty that shrinks like . Report it.
How it works
Mean, median and outliers
The mean is the ordinary average: add everything up and divide by how many there are.
The bar over the is read "x bar". For the data : the sum is 40 and there are 8 values, so . The mean of a sample estimates the expected value of the underlying distribution, usually written .
The median is the middle value once the data is sorted. With an even count, take the average of the two middle values. Here they are 4 and 5, so the median is 4.5.
The two differ in how they react to outliers: values far from the rest. Take seven salaries, in thousands of pounds: . The mean is 73.7. The median is 38. Six of the seven people earn less than the mean! One huge value drags the mean towards it, while the median barely notices. That is why house prices and incomes are usually reported as medians. In machine learning, outliers similarly pull hard on models trained with squared error, which is one reason robust losses exist (see Loss Functions).
Variance and standard deviation
To measure spread, look at how far each value is from the mean. Some are above (positive) and some below (negative), and they would cancel if you simply added them. So square each distance first, then average. That is the variance:
The standard deviation is the square root of the variance, which brings it back to the original units (centimetres rather than square centimetres).
By hand, for with mean 5:
| Value | Distance from mean | Squared |
|---|---|---|
| 2 | −3 | 9 |
| 4 | −1 | 1 |
| 4 | −1 | 1 |
| 4 | −1 | 1 |
| 5 | 0 | 0 |
| 5 | 0 | 0 |
| 7 | 2 | 4 |
| 9 | 4 | 16 |
| sum | 32 |
Variance . Standard deviation . Roughly: a typical value sits about 2 away from the mean.
One small wrinkle. When you estimate a population's variance from a sample, dividing by instead of gives a slightly better (unbiased) estimate, because the sample mean sits a little closer to the sample than the true mean does. Here that gives . With thousands of data points the difference is negligible. NumPy divides by by default and pandas by , which surprises people.
Standardising a feature means computing for every value. The result has mean 0 and standard deviation 1, and the number (a z-score) says how many standard deviations a value is from the mean. A of 3 is unusual, and is a simple way to flag anomalies (see Anomaly Detection).
Correlation
Do two quantities move together? The (Pearson) correlation measures how well a straight line describes the relationship. It runs from (perfect downward line) through 0 (no straight-line relationship) to (perfect upward line).
The top line multiplies the two deviations for each point. When both are above their means, or both below, the product is positive. That's the dot product of the two centred columns. The bottom line divides by their lengths. So correlation is exactly the cosine similarity of the centred data.
By hand: hours studied and exam scores . The means are 3 and 60. The deviations are : and : . Products: . Squared sums: and . So , a very strong positive relationship.
Three warnings that every data scientist learns the hard way:
- Correlation is not causation. Ice-cream sales and drowning deaths are correlated, because both rise in summer.
- doesn't mean "unrelated". It means "no straight-line relationship". Points on a perfect U-shape have .
- One outlier can create or destroy a correlation. Always plot the data.
Populations, samples and sampling error
The population is everything you care about: all emails your filter will ever see, all patients, all the questions users will ask a chatbot. You almost never have it. You have a sample, a subset. Every number computed on the sample is an estimate of the population's number, and a different random sample would give a different estimate. This wobble is called sampling error. It's not a mistake. It's built into working with samples.
The key result is how big the wobble is. For the mean of independent values with standard deviation , the typical size of the error is the standard error:
Notice the square root. To halve the error you need four times as much data. To cut it by 10, a hundred times as much.
Confidence intervals
A confidence interval turns the standard error into a range. Thanks to the central limit theorem (see Probability Distributions), sample means are roughly Gaussian, so about 95% of the time the true value lies within about 2 standard errors of your estimate:
(The exact multiplier is 1.96.) Strictly, "95% confidence" means that if you repeated the whole sampling process many times, about 95% of the intervals you built would contain the true value.
Why small test sets lie
Here is the application that matters most in practice. A model's accuracy on a test set is the mean of a column of 1s (right) and 0s (wrong), so the same maths applies. For a proportion measured on examples, the standard error is
Suppose a model's true accuracy is 0.85:
| Test examples | SE | 95% interval (about ±2 SE) |
|---|---|---|
| 100 | 0.036 | 0.78 to 0.92 |
| 1,000 | 0.011 | 0.83 to 0.87 |
| 10,000 | 0.0036 | 0.843 to 0.857 |
With 100 test examples, a model that is really 85% accurate will often score anywhere from 78% to 92% just through luck of the draw. Two models 3 points apart on such a test set are statistically indistinguishable.
This is why serious benchmarks have thousands of examples, why Cross-Validation averages over several splits, and why you should be suspicious of any claim like "our prompt improved accuracy from 82% to 86%" that doesn't mention the test-set size.
The bootstrap
What if there's no neat formula for the standard error, for example for an F1 score or a median? The bootstrap estimates it by simulation. Treat your sample as a stand-in for the population. Draw a new sample of the same size from it with replacement (so some items appear twice and others not at all), recompute your statistic, and repeat a few thousand times. The spread of the results approximates the sampling error. It's one of the most useful tricks in applied statistics, and Random Forests and Bagging use the same resampling idea to build their trees.
In code
import numpy as np
x = np.array([2, 4, 4, 4, 5, 5, 7, 9], dtype=float)
print(x.mean(), np.median(x)) # 5.0 4.5
print(x.var(), x.std()) # 4.0 2.0 divide by n
print(x.var(ddof=1), x.std(ddof=1)) # 4.571428571428571 2.138089935299395 divide by n - 1
salaries = np.array([30, 32, 35, 38, 40, 41, 300]) # thousands
print(salaries.mean().round(1), np.median(salaries)) # 73.7 38.0
hours = np.array([1, 2, 3, 4, 5])
score = np.array([52, 55, 61, 64, 68])
print(np.corrcoef(hours, score)[0, 1].round(3)) # 0.994
# How much does test-set accuracy wobble? True accuracy 0.85.
rng = np.random.default_rng(0)
for n in [100, 1000, 10_000]:
accs = rng.binomial(n, 0.85, size=10_000) / n # 10,000 imaginary test sets
se = np.sqrt(0.85 * 0.15 / n)
print(n, accs.std().round(4), se.round(4), np.percentile(accs, [2.5, 97.5]))
# 100 0.0358 0.0357 [0.78 0.92]
# 1000 0.0113 0.0113 [0.828 0.872]
# 10000 0.0035 0.0036 [0.8429 0.8569]
# Bootstrap: a confidence interval from ONE test set of 200 right/wrong results
correct = rng.random(200) < 0.85
boots = [rng.choice(correct, size=correct.size, replace=True).mean() for _ in range(5000)]
print(correct.mean(), np.percentile(boots, [2.5, 97.5])) # 0.86 [0.81 0.905]
The simulated spread matches the formula almost exactly. And the bootstrap, using only one test set of 200, says the honest report is "86%, with a 95% interval of roughly 81% to 90.5%". In Pandas and Working with Data, df.describe() prints count, mean, standard deviation, minimum, quartiles and maximum for every column at once. It should be your first command on any new dataset.
Common pitfalls
- Reporting a single number. "Accuracy 87%" means little without the test-set size or an interval. Report and an interval, or the standard deviation across several runs or seeds.
- Comparing on tiny test sets. Differences smaller than about two standard errors are not evidence. Use more data, or compare both models on the same examples, which cancels much of the noise.
- Mean of skewed data. The mean salary, response time or house price can describe almost nobody. Look at the median and a histogram.
- Non-random samples. The formula assumes a random sample. If your test set was collected differently from real usage (different users, time period or source), it can be precisely wrong, and no amount of data fixes that. See Training, Validation and Test Sets.
- Reusing the test set. Every time you look at test results and adjust your model, you fit a little to the noise in that test set. Its scores then become optimistic. Keep a final test set you touch once.
- Correlation as causation. A feature that correlates with the target may be a consequence, not a cause, or both may be driven by something else. This matters a lot for fairness and for leakage.
Watch out Statistics computed on a sample only describe the population that sample came from. A model evaluated on last year's data, one hospital's patients, or English-language questions tells you little about next year, another hospital, or Hindi. Ask "sample of what?" before trusting any number.
Where it leads
- Probability Distributions: the Gaussian behind the 68–95–99.7 rule and the central limit theorem.
- Maximum Likelihood Estimation: the mean and variance turn out to be the best-fitting parameters of a Gaussian.
- Training, Validation and Test Sets, Cross-Validation and Evaluation Metrics: estimating model performance without fooling yourself.
- Overfitting and the Bias–Variance Tradeoff: what happens when a model fits the sampling noise in its training data.
- Normalization Layers: BatchNorm and LayerNorm: neural network layers that standardise activations using batch means and variances.
- Evaluating LLMs and Benchmarks and Evaluating LLM Applications: why small eval sets for language models need error bars too.
A bit of history
Averages are ancient, but modern statistics took shape in the 19th century. Adolphe Quetelet applied the mean and the bell curve to human measurements in the 1830s and 1840s. Francis Galton discovered correlation and "regression towards the mean" while studying heredity in the 1880s, and Karl Pearson gave the correlation coefficient its modern formula in 1896. In 1908 William Sealy Gosset, a chemist at the Guinness brewery writing as "Student", worked out how to handle the uncertainty of very small samples. Ronald Fisher in the 1920s and Jerzy Neyman, who introduced confidence intervals in 1937, built the framework of statistical inference still taught today. Bradley Efron invented the bootstrap in 1979, one of the first methods to swap formulas for computer power.
Try it
- By hand, find the mean, median and standard deviation of . Then add the value 50 and recompute. Which summary changed most?
- Your classifier gets 172 right out of 200 test examples. Compute the accuracy, its standard error and an approximate 95% confidence interval.
- Make 1,000 points with
x = rng.uniform(-1, 1, 1000)andy = x ** 2. Compute their correlation. Plot them. What does this teach you about ?Hint for 2: , , so roughly 0.81 to 0.91.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Statistics and Probability
A full school-to-university course on data summaries, probability, distributions, sampling and inference, with practice problems.
Seeing Theory
A visual introduction to probability and statistics with interactive animations.
OpenIntro Statistics
A widely used free introductory statistics textbook covering sampling, confidence intervals and hypothesis tests, with exercises.
Think Stats (3rd edition)
Exploratory data analysis and statistics for programmers, using Python and real data sets. Free online.
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/math/statistics-basics.md