◆ AI All-in-One

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 →
↗ Plan a path here

Read first

Probability Basics

This leads to

—
The full path from zero — 1 concept before this one
  1. Probability Basics
  2. 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:

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 1/n1/\sqrt{n}. 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.

xˉ=1n∑i=1nxi\bar{x} = \frac{1}{n} \sum_{i=1}^{n} x_i

The bar over the xx is read "x bar". For the data 2,4,4,4,5,5,7,92, 4, 4, 4, 5, 5, 7, 9: the sum is 40 and there are 8 values, so xˉ=5\bar{x} = 5. The mean of a sample estimates the expected value of the underlying distribution, usually written μ\mu.

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: 30,32,35,38,40,41,30030, 32, 35, 38, 40, 41, 300. 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:

σ2=1n∑i=1n(xi−xˉ)2\sigma^2 = \frac{1}{n} \sum_{i=1}^{n} (x_i - \bar{x})^2

The standard deviation σ\sigma is the square root of the variance, which brings it back to the original units (centimetres rather than square centimetres).

By hand, for 2,4,4,4,5,5,7,92, 4, 4, 4, 5, 5, 7, 9 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 =32/8=4= 32 / 8 = 4. Standard deviation =4=2= \sqrt{4} = 2. Roughly: a typical value sits about 2 away from the mean.

0 1 2 3 4 5 6 7 8 9 10 Mean and standard deviation data: 2, 4, 4, 4, 5, 5, 7, 9 mean 5 ±1 sd (sd = 2) 0 1 2 3 4 5 6 7 8 9 10 Same mean, more spread data: 0, 1, 3, 5, 5, 7, 9, 10 sd = 3.4 mean 5 0 100 200 300 Mean vs median salaries in £1,000s; one is 300 median 38 mean 73.7 outlier One huge value drags the mean far from where most people are. The median (the middle value) barely moves.
Fig. 1 Left top: the data 2, 4, 4, 4, 5, 5, 7, 9 as dots, with mean 5 and a bar showing one standard deviation (2) either side. Left bottom: different data with the same mean but standard deviation 3.4. Right: seven salaries where one is 300; the median stays at 38 while the mean is dragged to 73.7.

One small wrinkle. When you estimate a population's variance from a sample, dividing by n−1n - 1 instead of nn 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 32/7=4.5732 / 7 = 4.57. With thousands of data points the difference is negligible. NumPy divides by nn by default and pandas by n−1n - 1, which surprises people.

Standardising a feature means computing z=(x−xˉ)/σz = (x - \bar{x}) / \sigma for every value. The result has mean 0 and standard deviation 1, and the number zz (a z-score) says how many standard deviations a value is from the mean. A zz of 3 is unusual, and is a simple way to flag anomalies (see Anomaly Detection).

Correlation

Do two quantities move together? The (Pearson) correlation rr measures how well a straight line describes the relationship. It runs from −1-1 (perfect downward line) through 0 (no straight-line relationship) to +1+1 (perfect upward line).

r=∑i(xi−xˉ)(yi−yˉ)∑i(xi−xˉ)2  ∑i(yi−yˉ)2r = \frac{\sum_i (x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum_i (x_i - \bar{x})^2} \; \sqrt{\sum_i (y_i - \bar{y})^2}}

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 x=1,2,3,4,5x = 1, 2, 3, 4, 5 and exam scores y=52,55,61,64,68y = 52, 55, 61, 64, 68. The means are 3 and 60. The deviations are xx: −2,−1,0,1,2-2, -1, 0, 1, 2 and yy: −8,−5,1,4,8-8, -5, 1, 4, 8. Products: 16+5+0+4+16=4116 + 5 + 0 + 4 + 16 = 41. Squared sums: 1010 and 170170. So r=41/10×170=41/41.2≈0.99r = 41 / \sqrt{10 \times 170} = 41 / 41.2 \approx 0.99, a very strong positive relationship.

r = +0.87 strong positive r = +0.00 none r = −0.69 negative Correlation r runs from −1 to +1 and measures how well a straight line describes the cloud.
Fig. 2 Three clouds of points with correlations +0.87, 0.00 and −0.69. The closer the cloud is to a straight line, the closer r is to +1 or −1.

Three warnings that every data scientist learns the hard way:

  1. Correlation is not causation. Ice-cream sales and drowning deaths are correlated, because both rise in summer.
  2. r=0r = 0 doesn't mean "unrelated". It means "no straight-line relationship". Points on a perfect U-shape have r=0r = 0.
  3. 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 nn independent values with standard deviation σ\sigma, the typical size of the error is the standard error:

SE=σn\text{SE} = \frac{\sigma}{\sqrt{n}}

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:

95% confidence interval≈estimate±2×SE\text{95\% confidence interval} \approx \text{estimate} \pm 2 \times \text{SE}

(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 pp measured on nn examples, the standard error is

SE=p(1−p)n\text{SE} = \sqrt{\frac{p(1 - p)}{n}}

Suppose a model's true accuracy is 0.85:

Test examples nn 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.

0.70 0.75 0.80 0.85 0.90 0.95 1.00 measured accuracy on the test set One model, true accuracy 0.85, scored on many random test sets true 0.85 100 examples 95% of scores: 0.78–0.92 1,000 examples 95% of scores: 0.83–0.87 A 3-point gain on 100 examples can be pure luck.
Fig. 3 A model with true accuracy 0.85 scored on 20,000 different random test sets. With 100 examples per test set (red), scores spread from about 0.78 to 0.92. With 1,000 examples (blue), they cluster between about 0.83 and 0.87.

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 nn 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 σ/n\sigma / \sqrt{n} 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

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

  1. By hand, find the mean, median and standard deviation of 1,3,3,6,71, 3, 3, 6, 7. Then add the value 50 and recompute. Which summary changed most?
  2. Your classifier gets 172 right out of 200 test examples. Compute the accuracy, its standard error and an approximate 95% confidence interval.
  3. Make 1,000 points with x = rng.uniform(-1, 1, 1000) and y = x ** 2. Compute their correlation. Plot them. What does this teach you about r=0r = 0?

Hint for 2: p=0.86p = 0.86, SE=0.86×0.14/200≈0.025\text{SE} = \sqrt{0.86 \times 0.14 / 200} \approx 0.025, so roughly 0.81 to 0.91.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Seven salaries (in thousands) are 30, 32, 35, 38, 40, 41 and 300. Which summary best describes a typical person's pay?

  2. Your model scores 87% and a colleague's scores 85% on the same 200-example test set. What is the honest conclusion?

  3. You want to halve the standard error of a measured accuracy. How much more test data do you need?

  4. Points lie on a perfect U-shape, y = x², with x spread evenly from −1 to 1. The correlation r comes out near 0. What does that mean?

  5. You need a confidence interval for an F1 score, which has no neat standard-error formula. What can you do?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Statistics and Probability

Khan Academy · Beginner · Free

A full school-to-university course on data summaries, probability, distributions, sampling and inference, with practice problems.

Interactive

Seeing Theory

Brown University · Beginner · Free

A visual introduction to probability and statistics with interactive animations.

Book

OpenIntro Statistics

Diez, Çetinkaya-Rundel & Barr · Beginner · Free

A widely used free introductory statistics textbook covering sampling, confidence intervals and hypothesis tests, with exercises.

Book

Think Stats (3rd edition)

Allen B. Downey · Beginner · Free

Exploratory data analysis and statistics for programmers, using Python and real data sets. Free online.

Video

StatQuest

Josh Starmer · Beginner · Free

Short, cheerful, very clear videos on statistics and nearly every ML algorithm.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/math/statistics-basics.md