Lesson 4 of 116 min
Expectation and variance
A distribution's centre is the best single guess, each value times its chance, and its spread says how wrong that guess still is.
After this lesson you can summarise a distribution by its centre and its spread.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Choose what you divide by
NumPy divides by the number of masses. Pandas divides by one fewer by default. Use ddof=0 in pandas to match the way the chapter describes the spread of these 342 masses. Save the Palmer Penguins CSV beside your notebook.
import numpy as np
import pandas as pd
df = pd.read_csv("penguins.csv")
kilos = df.body_mass_g.dropna() / 1000
mass = kilos.to_numpy()
print(mass.var().round(3), mass.std().round(3))
print(kilos.var().round(3), kilos.std().round(3))
print(kilos.var(ddof=0).round(3), kilos.std(ddof=0).round(3))0.641 0.801 0.643 0.802 0.641 0.801
See what the scaler learned
fit saves the average in mean_ and the scale in scale_. Fit on your training rows and reuse those numbers for new rows. For a constant column the scaler uses a scale of 1, so centering makes its training values zero.
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler().fit(mass.reshape(-1, 1))
print(scaler.mean_.round(4), scaler.scale_.round(4))
print(scaler.transform([[5.0], [3.4]]).ravel().round(2))[4.2018] [0.8008] [ 1. -1.]
Add up the misses on each side
More penguins sit below the average, but the ones above it are farther away. Both sides add up to the same distance. When you square the misses, guessing away from the average adds the square of that shift to the smallest loss.
miss = mass - mass.mean()
below, above = miss[miss < 0], miss[miss > 0]
print(below.size, above.size)
print((-below.sum()).round(2), above.sum().round(2))
guess = 3.4
print(((mass - guess) ** 2).mean().round(3))
print((mass.var() + (guess - mass.mean()) ** 2).round(3))193 149 115.66 115.66 1.284 1.284
Try scoring by distance
Change the loss to the average distance. Now the median is the best single guess. Each extra kilo missed adds the same amount to the loss, so a heavy penguin has less pull.
for guess in (mass.mean(), np.median(mass)):
loss = np.abs(mass - guess).mean()
print(round(guess, 2), round(loss, 4))4.2 0.6764 4.05 0.6664
Find the fullest bar
The tallest bar tells you where masses pile up. The average tells you where they balance. Count both bars at a quarter kilo wide and see how far apart they are.
edges = np.arange(2.5, 6.75, 0.25)
counts, _ = np.histogram(mass, bins=edges)
fullest = counts.argmax()
centre = np.searchsorted(edges, mass.mean()) - 1
for i in (fullest, centre):
print(edges[i], edges[i + 1], counts[i])3.5 3.75 49 4.0 4.25 28
Use the chances as weights
Multiply each value by its chance and add to get the expected value. For the variance, square each value's distance from the expected value, then use the same chances to average those squares.
scores = np.array([0, 1])
chances = np.array([0.2, 0.8])
expected = (scores * chances).sum()
variance = (((scores - expected) ** 2) * chances).sum()
print(round(expected, 2), round(variance, 2))0.8 0.16
Run on Python 3.13.3, NumPy 2.5.5, pandas 3.1.1 and scikit-learn 1.9.1. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Random variables and distributions
The penguins' masses are drawn as bars of share per kilo. The bar from 3.5 to 4 kilos is half a kilo wide, and 0.55 high. What share of the penguins weigh 3.5 to 4 kilos?
2 of 3
Five penguins weigh 3, 3, 3, 4 and 7 kilos. You give one guess for all five. Each guess is scored like a model: square every miss, then average. Which guess gets the smallest loss?
3 of 3
The penguins' average mass is 4.2 kilos, and their standard deviation is 0.8 kilos. A scaler takes away the average, then divides by the standard deviation. What does a 6 kilo penguin become?
The ideas in this lesson
- Expected value
- Each value times its chance, added up: a distribution's centre, and the best single guess.
- Variance
- The average squared distance from the centre: how wrong the best single guess still is.
- Standard deviation
- The square root of the variance: the spread back in the values' own units.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
One guess for every penguin
Here's a game. There's a penguin, and you can't see it. You have to guess how heavy it is. You know nothing about this penguin. And you give the same guess for every penguin. Which guess is least wrong?
Three guesses
Here are the masses of three hundred and forty-two penguins. Each guess gets a loss, the way a model is scored. Square every miss, then take the average. The smaller the loss, the better the guess.
Here are three guesses. About the most common mass: three point six kilos. Halfway between the lightest and the heaviest: four and a half.
Or the average: four point two.
Which guess gets the smallest loss?
The best single guess
Here are the losses. The most common mass gets a loss of one. Halfway gets zero point seven three. And the average gets zero point six four one. That's the lowest. If you picked the most common mass, here's why that guess loses. It's close to all the light penguins. But it's far from the heavy ones, and a big miss, squared, counts a lot.
So the best single guess... is the average.
Where the bars balance
If the bars were weights on a board, the board would balance at the average. The lighter penguins sit on one side, and the heavier ones sit on the other.
Each value times its chance
So far we've had a list of penguins. Often you only have chances: a distribution. Here's one. A model answers a question right eight times in ten. A right answer scores one, and a wrong answer scores zero. Where do these two bars balance? Halfway, at zero point five?
Multiply each score by its chance, and add them up.
One times zero point eight, plus zero times zero point two. That's zero point eight.
Each value times its chance, added up... is called the expected value.
Expected, never scored
So why is it called expected?
One question scores zero or one. It never scores zero point eight.
Draw ten questions at random, and their average is zero point seven. Draw a thousand, and their average is zero point eight. The expected value is what the average of many draws comes close to.
And a penguin picked at random has the same chance as any other penguin: one in three hundred and forty-two.
So the penguins' expected mass is just their average, four point two kilos.
How wrong it still is
Guess the average, four point two kilos, for every penguin. How wrong is that guess still?
Take each penguin's miss, and square it. The heaviest penguin weighs six point three kilos. It misses by two point one, and its square is four point four. Average all three hundred and forty-two squares, and you get zero point six four one. The average squared distance from the average... is called the variance.
The loss of knowing nothing
In Calculus for AI, a flat line through the penguins is a model that knows nothing about a penguin. It guesses the average for all of them. Its loss is this same number, zero point six four one. So a model that looks at the penguin, at its flipper or its bill, has to beat it.
Square kilos
Zero point six four one... of what?
Square kilos.
Weigh the same penguins in grams, and the variance is six hundred and forty-one thousand. Read that as a distance in grams. Then a typical penguin would be six hundred and forty-one kilos from the average.
No. Only the unit changed. So the variance isn't a distance you can read off.
The square root
Take its square root, and you get about zero point eight kilos. In grams, it's about eight hundred: the same spread in either unit. The square root of the variance... is called the standard deviation. It's the spread, back in kilos. About two penguins in three are within zero point eight kilos of the average. That's from three point four to five kilos.
In code
Now in real code. NumPy gives the average, the variance and the standard deviation, one short call each. They're the same three numbers. The question's expected value is one call too. Give it the two scores and their chances: zero point eight. Then a scaler from scikit-learn. With fit, it learns the average and the standard deviation. With transform, it takes away the average and divides by the standard deviation. What will a five-kilo penguin become?
One. It's one standard deviation above the average. And three point four becomes minus one.
After the scaler, every column a model learns from has an average of zero, and a spread of one.
Centre and spread
So the expected value is each value times its chance, and it's the best single guess. The variance says how wrong that guess still is, in squares.
And the standard deviation says it in kilos.
Guess the average
Guess the average, and the spread tells you how wrong you are. Now try it on this lesson's page, and take the quiz. Find a guess that doubles the smallest loss.
You use this lesson in Lab 2: Scan the penguins before a model, after Correlation.
Facts last checked on .
