Chance and data: probability, mean, variance and the normal curve
Before this lesson: lesson 02 (-notation),
lesson 03 (seeded random numbers, axis) and
lesson 04 (). Time: about 60 minutes, plus the notebook.
The full story is in the Probability and statistics track.
Why this matters #
- Preprocessing.
StandardScalerin scikit-learn turns each feature into z-scores: subtract the mean, divide by the standard deviation. Many models train better after this step. - Initialization. Neural network weights start as random numbers, often from a normal distribution with chosen from the layer size (Glorot and He initialization).
- Losses. If you assume that the noise in the targets is normal, the best fit is the one with the smallest squared error. This is why the mean squared error is the default loss for regression.
- Evaluation. A test accuracy is a frequency. On 1000 test examples, an accuracy of 0.90 has an uncertainty of about . Two models that differ by 0.005 may not differ at all.
- Training noise. A mini-batch gradient is an average over examples. Its noise shrinks like , the same law that you see for coin flips below.
1. Predict first #
2. The picture #
2.1 Probability as long-run frequency #
Flip a fair coin many times and keep a running score: the relative frequency of heads, that is, (number of heads so far) / (number of flips so far). After 10 flips it can be 0.3 or 0.7. After 10 000 flips it is very close to 0.5. This is the frequency view of probability: means that the relative frequency gets close to 0.5 in a long series of independent flips. (The Probability and statistics track also treats probability as a degree of belief; the rules are the same.)
The important word is slowly. The typical gap between the frequency and is (section 3.4 proves this). It shrinks like : to make the gap 10 times smaller, you need 100 times more flips.
Flip, then compare runs. Each line is one run of 10 000 flips (run 1 is blue). The aqua dashed lines are the band ; for large about 95 % of runs are inside it. Press New flips a few times: early on the runs disagree a lot, later they all stay near . The x-axis is logarithmic, so each step to the right is 10 times more flips.
2.2 Centre and spread #
Put the data on a number line. The mean is the point where the line would balance if each data point were a small equal weight. The median is the middle value after sorting. To measure the spread, take each deviation , square it, and average the squares: this is the variance. Its square root is the standard deviation.
Drag the blue dots. The violet triangle is the mean (the balance point) and the yellow diamond is the median. Each orange square has side , so its area is the squared deviation; the variance is the average area. Press Add outlier at 20 and watch the mean move but the median hardly move. Press Shift all +1: the mean moves, the variance does not.
2.3 Histograms #
For many data points, a dot plot is too crowded. A histogram cuts the number line into bins of equal width and draws a bar for each bin. The bar height is either the count (number of points in the bin) or the density . With density heights, the area of each bar is the fraction of the data in that bin, so all bar areas add up to 1. Only density histograms can be compared with a density curve, or with a histogram of a different size .
Change the bin width . The blue bars are the histogram; the orange curve is the true density the samples came from. With the two peaks merge into one; with and the bars are mostly 0 or 1 sample and look like noise. Switch between count and density: the shape stays, the y-axis changes, and in density mode the bar areas add up to 1.
2.4 The normal curve #
As grows and shrinks, a density histogram gets close to a smooth curve: the density of the distribution. The most common one is the bell-shaped normal curve . Its centre is the mean , and its width is the standard deviation . A probability is an area under the curve: is the area between and .
Drag and , then change . The yellow area under the orange curve is . Use the presets , , to see 0.6827, 0.9545 and 0.9973. When you move or , the blue handles keep their z-scores and the area does not change. With the peak is near 4, above the dashed line at density 1.
For a fair coin (), the typical gap between the running frequency and is . About how many flips do you need until the band is only wide?
gives , so . The gap shrinks like , not like : 100 flips give only , and 10 times more precision costs 100 times more flips.
The data have mean 5 and median 4.5. You add one value, 50. What are the new mean and median?
The sum becomes over 9 values, so the mean is 10: one point moved it from 5 to 10. Sorted, the 9 values are , and the middle (5th) value is 5. The median only counts positions, so it does not care how far away the outlier is.
3. Definitions and main results #
3.1 Experiments, events and the rules of probability #
An experiment has outcomes that we cannot predict, for example one roll of a die. The set of all outcomes is the sample space . An event is a set of outcomes, for example ("even"). A probability gives each event a number with three properties:
- for every event ;
- (something happens);
- if and are disjoint (they have no outcome in common), then .
For a fair die, every outcome has probability and , so .
Two rules that follow.
- Complement: . Proof. and "not " are disjoint, and together they are . Property 3 and property 2 give .
- "Or" for any two events: . The outcomes in both events are counted twice in , so we subtract them once. Example with one die, and : , and indeed .
Independence. Two events are independent if . In words: knowing that happened does not change the chance of . Separate flips of a coin are independent, so . The product rule is only for independent events: for one die, , not .
Conditional probability
The probability of given that happened is (for ). Independence is the same as . Bayes' rule, , follows from writing in two ways. The Probability and statistics track builds on this.
3.2 Random variables and distributions #
A random variable is a number that depends on the outcome: the face of a die, the height of a random person, the error of a model on a random test example.
- A discrete random variable takes separate values. Its distribution is a table of probabilities that add up to 1. For a fair die, for .
- A continuous random variable can take any value in an interval. Its distribution is a density with total area 1 under the curve, and
(The integral sign means "area under the curve"; the Calculus track defines it.)
A density is not a probability. For a small width , . So is "probability per unit length", and it can be larger than 1 when the distribution is narrow. Example: the uniform distribution on has density on that interval; the area is . Also, for a continuous , for every single value : a line has no area.
A density curve has the value at . What can you conclude?
A density is probability per unit length. Only areas are probabilities, and the total area is always 1. A tall, narrow peak is fine: has peak height . For a continuous variable .
3.3 Mean, median, variance and standard deviation #
For data (a sample):
| Quantity | Formula | Unit |
|---|---|---|
| mean | same as the data | |
| median | middle value after sorting (the average of the two middle values if is even) | same as the data |
| variance | data unit squared | |
| standard deviation | same as the data |
The standard deviation (std) is the one to report: it has the unit of the data (cm, not cm²), and it is a typical distance from the mean.
For a random variable, the same ideas use probabilities as weights. The expectation (or expected value) is , and the variance is with . For a fair die, (not a possible face: an expectation is an average, not a typical outcome), and . The data formulas are the special case where each of the points has probability .
Three facts with short proofs.
- The deviations add up to 0: . This is why the mean is the balance point.
- Shortcut formula: (mean of the squares minus the square of the mean). Proof. Expand and average over : .
- Shift and scale: if , then and . Proof. Averaging gives . So : the shift cancels. Squaring gives , so and .
Outliers. One extreme value can move the mean and the std a lot, because the mean uses the values and the variance uses their squares. The median uses only the order, so it is robust to outliers.
3.4 Sums and averages of independent variables #
Two rules for random variables (proofs in the probability track):
- always, and ;
- if and are independent, and .
Why the variances add for independent variables
Write for the means. Then . Square and take expectations:
For independent variables, the expectation of a product is the product of the expectations, so the last term is .
The law. Let be independent, each with mean and variance , and let . Then
Back to the coin. Let for heads and for tails. Then and , so (shortcut formula). The running frequency is , so its typical gap to is . This is the band in the coin figure. The law of large numbers says the same in words: as grows, gets close to with probability close to 1.
3.5 Dividing by or by #
The sample variance divides by :
Why? We usually want the variance of the whole population, but we measure the deviations from the sample mean , not from the true mean . The sample mean sits in the middle of this sample, so the deviations from it are a bit too small on average. Dividing by instead of corrects this exactly: (we say is unbiased).
Why gives an unbiased estimate
Let be independent with mean and variance .
- Write and square: .
- Sum over . The middle term is (fact 1 of section 3.3). So .
- Take expectations. On the left, each term has expectation , so we get . On the right, (section 3.4). So .
- Hence , and dividing by gives .
The square root is still slightly too small on average, but for large the difference is tiny.
Library defaults differ. NumPy's np.var and np.std divide by (ddof=0, "delta degrees of
freedom"); pandas' .var() and .std() divide by (ddof=1). scikit-learn's StandardScaler
uses . For the lesson data, np.std gives 2.0 and pandas gives 2.138. For large the difference is
small; for small , say which one you use.
For the same 8 numbers, np.std(x) prints 2.0 and pd.Series(x).std() prints 2.138. Why?
. Then and . Pass ddof=1 to NumPy (or ddof=0 to pandas) to make them agree.
3.6 The normal distribution #
The normal (or Gaussian) distribution has the density
Read it from the inside out: is the distance from the centre in units of ; it is squared, so the curve is symmetric; makes the curve fall fast away from the centre (lesson 04); the factor makes the total area 1. The peak height is : for and for .
z-scores. The standard normal is . If , then the z-score is standard normal (shift and scale, section 3.3). So every normal probability is a standard normal probability:
where is the standard normal cumulative distribution function (CDF), in
scipy.stats.norm.cdf.
The 68–95–99.7 rule. For any normal distribution, , , . A value more than 3 standard deviations from the mean is rare (about 3 in 1000), if the data are normal.
3.7 The central limit theorem #
Theorem (central limit theorem, CLT). Let be independent and have the same distribution, with mean and finite variance . Then, for large , the mean is approximately . Precisely: for every ,
The same holds for the sum , which is approximately .
Increase the number of dice . The blue bars are the exact distribution of the mean of dice; the orange curve is the normal curve with the same mean and standard deviation . One die is flat, two dice give a triangle, and from about 5 dice the bars follow the curve closely. The loaded die is skewed: it needs more dice before the bars look normal.
What the CLT does not say.
- It does not say that data are normal. It is about averages and sums of many independent effects. Incomes, waiting times and word frequencies are strongly skewed.
- It does not say how large must be. For a symmetric distribution, can be enough; for a skewed one you need more.
- It needs a finite variance and independence. The mean of samples from the Cauchy distribution (which has no finite variance) never settles: it has the same distribution for every .
This is why the normal curve is everywhere: a measurement error is often the sum of many small independent errors.
Answers to section 1. (1) Not necessarily. A fair coin gives 7 or more heads in 10 flips with probability (section 4c), about 1 time in 6. Ten flips are too few to tell. (2) The standard deviation is 2 (section 4a). After adding 50, the mean jumps from 5 to 10, but the median only moves from 4.5 to 5. (3) Yes. Density is probability per unit length; only areas must be at most 1. The peak of is 3.99.
4. Worked example #
(a) Mean, variance and standard deviation by hand. Data: , so .
Mean: .
| 2 | 4 | 4 | 4 | 5 | 5 | 7 | 9 | sum | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 0 | 2 | 4 | 0 | |||||
| 9 | 1 | 1 | 1 | 0 | 0 | 4 | 16 | 32 |
The deviations add up to 0 (fact 1). Variance: , so . Sample variance: , so . Median: the sorted data are already in order; the two middle values are 4 and 5, so the median is 4.5.
Check with the shortcut formula: , so ✓.
z-scores : . The value 9 is 2 standard deviations above the mean.
Shift and scale: for , the mean is and the std is .
Outlier: add 50. Mean , median , and grows from 2 to about 14.27.
(b) A normal probability. Adult heights in some population are about (in cm). What fraction is between 160 and 180 cm, and what fraction is above 190 cm?
- z-scores: and .
- : the "68" of the rule.
- For 190 cm: . By symmetry, the two tails outside have together, so each tail has . About 2.3 % are taller than 190 cm.
(c) Is 7 heads in 10 flips surprising? Assume the coin is fair. Each of the sequences of heads and tails has probability . The number of sequences with exactly heads is , the number of ways to choose which flips are heads. So
A fair coin does this about once in 6 tries. It is not good evidence of a bias.
5. In code #
NumPy, pandas and SciPy check the numbers of section 4. The notebook for this lesson has these cells and the exercises.
import numpy as np
import pandas as pd
from scipy import stats
x = np.array([2, 4, 4, 4, 5, 5, 7, 9], dtype=float)
print(x.mean(), np.median(x)) # 5.0 4.5
print(np.var(x), np.std(x)) # 4.0 2.0 (divide by n, ddof=0)
print(np.var(x, ddof=1), np.std(x, ddof=1)) # 4.571... 2.138... (divide by n - 1)
print(pd.Series(x).std()) # 2.138... (pandas: ddof=1 by default)
print((x - x.mean()) / x.std()) # z-scores: [-1.5 -0.5 -0.5 -0.5 0. 0. 1. 2. ]
print(np.std(3 * x + 5)) # 6.0 = 3 * 2
# (b) normal probabilities with the CDF
print(stats.norm.cdf(180, 170, 10) - stats.norm.cdf(160, 170, 10)) # 0.6826894921370859
print(stats.norm.sf(190, 170, 10)) # 0.022750131948179198 (sf = 1 - cdf)
# (c) 7 or more heads in 10 fair flips
print(stats.binom.sf(6, 10, 0.5)) # 0.171875 = 176/1024 (P(X > 6))
# the running frequency of heads, with a seed
rng = np.random.default_rng(0)
flips = rng.random(10_000) < 0.5 # True = heads
freq = np.cumsum(flips) / np.arange(1, 10_001)
print(freq[[9, 99, 999, 9999]]) # [0.3 0.44 0.473 0.499] (n = 10, 100, 1000, 10 000)
With this seed, the first 10 flips give only 3 heads. The frequency gets close to 0.5, but slowly. Another seed gives other numbers, with the same slow approach.
6. Where it shows up #
- Feature standardization.
StandardScalerstores the mean and std of each column of the training data and maps . Use the training statistics also for the test data. - Batch normalization and layer normalization. Inside a network, these layers compute a mean and a variance over a batch or over the features, and standardize. To normalize, they divide by .
- Weight initialization. He initialization draws weights from , so that the variance of the activations stays about the same from layer to layer (variances of independent terms add, section 3.4).
- Gaussian noise and squared error. Linear regression assumes with . Maximizing the likelihood of this model is the same as minimizing the squared error (the ML Fundamentals track shows this).
- Uncertainty of a metric. An accuracy on test examples has a standard error of about : for , .
- Generative models. Diffusion models and variational autoencoders start from standard normal noise and transform it into images, molecules or weather fields.
- ML for science. Repeated measurements are averaged and reported as mean ± std (or ± std$/\sqrt n$ for the uncertainty of the mean). Ensembles of climate or weather simulations are summarized by their mean and spread.
7. Common mistakes #
- Reading a short run as the probability. 7 heads in 10 flips does not mean . The typical error after trials is about , which is 0.16 for and .
- Treating a density value as a probability. can be larger than 1. Probabilities are areas.
- Mixing and . NumPy and pandas use different defaults. Say which one you use, and do not compare a NumPy std with a pandas std.
- Reporting the variance in data units. The variance of heights is in cm². Report the std, which is in cm.
- Using the product rule for events that are not independent. only for independent events.
- Trusting the mean with outliers. A single extreme value can move the mean and the std a lot. Look at the median and at a histogram too.
- Believing the CLT makes data normal. It is about averages of many independent terms, not about the data themselves.
- Choosing a histogram's bin width without looking. Too wide hides structure (two peaks become one);
too narrow shows noise. Try a few widths, or
bins="auto"in NumPy and matplotlib.
8. Check yourself #
- You roll two fair dice. What is the probability that the sum is 7?
Answer
There are equally likely pairs. The pairs with sum 7 are : 6 pairs. So the probability is . - , , and and are independent. Compute and .
Answer
. . - Test scores are about . About what fraction of students score above 90?
Answer
. The two tails beyond hold , so one tail holds about : about 2.3 %. - One measurement has standard deviation 5. You average 25 independent measurements. What is the standard deviation of the average?
Answer
. To halve it again, you need measurements. - You make a histogram of 50 values with bin width 0.05. Why does it look noisy, and what should you do?
Answer
There are many more bins than the data can fill: most bins hold 0 or 1 value, so the heights jump. Use wider bins (fewer bins), or collect more data. - A model has accuracy 0.90 on 1000 test examples. A second model has 0.905. Is the second model better?
Answer
Not clearly. The standard error of each accuracy is about , so a difference of 0.005 is well inside the noise. (A paired comparison on the same test set is more precise, but 0.005 is still small.)
In the frequency view, what does mean?
In a long series of independent flips, the fraction of heads gets close to 0.3.
How does the typical gap between a relative frequency and depend on the number of trials ?
It is , so it shrinks like : 100 times more trials give 10 times more precision.
Write the variance of data (dividing by ).
, the average squared deviation from the mean.
Why do we usually report the standard deviation and not the variance?
The standard deviation has the same unit as the data, and it is a typical distance from the mean.
Compute the mean and standard deviation (divide by ) of .
Mean 5; squared deviations sum to 32; variance ; std 2.
What divisor do
np.stdand pandas.std()use by default?NumPy divides by (
ddof=0); pandas divides by (ddof=1).All data are multiplied by and then is added. What happens to the standard deviation?
It is multiplied by . The shift has no effect.
What fractions of a normal distribution lie within 1, 2 and 3 standard deviations of the mean?
About 68 %, 95 % and 99.7 % (0.6827, 0.9545, 0.9973).
Why can a probability density be larger than 1?
A density is probability per unit length; only areas are probabilities. Example: uniform on has density 2.
What does the central limit theorem say?
The mean of independent, identically distributed variables with finite variance is approximately for large , whatever their own distribution.
9. Interview angle #
- "Why divide by in the sample variance?" — The deviations are measured from , which is
fitted to the same sample, so they are too small on average. With , .
Know the defaults: NumPy
ddof=0, pandasddof=1. - "What is the variance of the mean of i.i.d. variables?" — ; the std is . Use it for error bars on a metric and for the noise of a mini-batch gradient.
- "State the central limit theorem. When does it fail?" — Averages of i.i.d. variables with finite variance become normal. It fails without a finite variance (Cauchy) and can be slow for very skewed data; it says nothing about the data themselves.
- "Mean or median?" — The median is robust to outliers (for example house prices, latencies); the mean is the right summary when you care about totals, and it is what squared-error losses estimate.
- "Is a density value a probability?" — No; probability is the area under the density, and can be larger than 1.
10. Practice #
The notebook for this lesson runs in Colab or in your browser. It has five exercises, each with a check cell and a folded solution:
- Simulate coin flips with a seeded generator and plot the running frequency of several runs with the band.
- Implement the mean, variance and standard deviation with a
ddofargument, and compare with NumPy and pandas. - Compute a density histogram with
np.histogramand check that the bar areas add up to 1. - Standardize a dataset to z-scores, then count the fraction of normal samples within 1 and 2 standard deviations.
- The CLT in action: average uniform numbers many times and compare the std of the averages with .
11. Watch and read #
- Daniel Kunin and others, Seeing Theory (Brown University), interactive chapters 1–3: chance events, expectation and variance, distributions, and the CLT.
- Illowsky and Dean, Introductory Statistics 2e (OpenStax, free): chapter 2 (descriptive statistics, histograms), chapter 3 (probability rules), chapter 6 (the normal distribution) and chapter 7 (the central limit theorem).
- Grinstead and Snell, Introduction to Probability (free PDF): chapter 1 (simulation and frequencies), chapter 6 (expected value and variance) and chapter 9 (CLT).
- Allen Downey, Think Stats (free online): the same ideas with Python and real data.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.