Lesson 6 of 117 min
Correlation
One number from −1 to 1 says how tightly two things rise or fall together, and it never says which one moves the other.
After this lesson you can measure how two variables move together, and say what that does not prove.
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.
Give correlation numeric columns
Run the cells in order. Asking for a correlation matrix over the whole penguin table tries to turn names like Adelie into numbers. numeric_only=True keeps the numeric columns. Choose the columns you actually want to compare when the table has numbers such as years or IDs.
import numpy as np
import pandas as pd
url = "https://raw.githubusercontent.com/allisonhorst/palmerpenguins/main/inst/extdata/penguins.csv"
df = pd.read_csv(url)
try:
df.corr()
except ValueError as error:
print(error)
print(df.corr(numeric_only=True).loc["bill_depth_mm", "body_mass_g"].round(2))could not convert string to float: 'Adelie' -0.47
Read the slope in kilos per millimetre
Pearson's r has no units. The slope tells you how many kilos the fitted line gains per millimetre of bill depth. When a link flips after you split the rows into groups, it's an example of Simpson's paradox.
def depth_stats(rows):
pair = rows[["bill_depth_mm", "body_mass_g"]].dropna()
x, y = pair.bill_depth_mm, pair.body_mass_g / 1000
slope = np.polyfit(x, y, 1)[0]
return f"r = {x.corr(y):+.2f}, slope = {slope:+.2f} kg/mm"
print("All:", depth_stats(df))
for species, rows in df.groupby("species"):
print(species + ":", depth_stats(rows))All: r = -0.47, slope = -0.19 kg/mm Adelie: r = +0.58, slope = +0.22 kg/mm Chinstrap: r = +0.60, slope = +0.20 kg/mm Gentoo: r = +0.72, slope = +0.37 kg/mm
Spot a curve that scores zero
Square the numbers from −2 to 2 and you get a U. Each point on the left balances a point on the right. Pearson's r is zero even though the first column tells you exactly what's in the second.
x = np.arange(-2, 3)
print(np.column_stack((x, x**2)).tolist())
print(f"r = {np.corrcoef(x, x**2)[0, 1]:.2f}")[[-2, 4], [-1, 1], [0, 0], [1, 1], [2, 4]] r = 0.00
Look at the wolf photos
Ribeiro and colleagues trained on 20 photos with snow behind every wolf and none behind the huskies. Their classifier got 8 of 10 test photos right, miscalling a husky in snow and a wolf without it. Of 27 people, 10 trusted the classifier before seeing its explanations and 3 afterward. Read the experiment.
print(f"Test accuracy: {8 / 10:.0%}")
print(f"People who trusted it: {10 / 27:.0%} before, {3 / 27:.0%} after")Test accuracy: 80% People who trusted it: 37% before, 11% after
Centre both columns for cosine similarity
Subtract each column's average and take the cosine similarity of the two centred columns. That gives r. The matching signs count how often the two move together around their averages. The cosine also weighs how far each point is from those averages.
for column in ("flipper_length_mm", "bill_depth_mm"):
pair = df[[column, "body_mass_g"]].dropna().to_numpy()
x, y = (pair - pair.mean(axis=0)).T
agree = ((x * y) > 0).sum()
r = x @ y / (np.linalg.norm(x) * np.linalg.norm(y))
print(f"{column}: {agree}/{len(x)} agree, r = {r:+.2f}")flipper_length_mm: 297/342 agree, r = +0.87 bill_depth_mm: 79/342 agree, r = -0.47
Run on Python 3.13.3, NumPy 2.5.5 and pandas 3.1.1. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Expectation and variance
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?
2 of 3
Over many chats, longer answers come with more thumbs-up: r is 0.6. Someone says, "So make every answer longer, and the thumbs-up will rise." What does the r show?
3 of 3
pandas gives bill length and mass an r of 0.6. What share of the mass's spread can a straight line from bill length explain?
The ideas in this lesson
- Correlation
- One number, from −1 to 1, for how tightly two things rise or fall together along a line.
- r squared
- r times r: the share of one thing's spread that a line from the other explains.
- Correlation is not cause
- Two things can move together because a third thing moves both, so a correlation never proves a cause.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Deeper bills
Here's a puzzle about penguins. Some have deeper bills than others. Across all the penguins, deeper bills go with lighter penguins. Now take one kind of penguin alone. Do deeper bills still go with lighter penguins?
Your guess
Here's one dot for each penguin. Bill depth goes across, and mass goes up. A bill's depth is how tall it is, from top to bottom. Across all three hundred and forty-two penguins, the dots slope down: a deeper bill, a lighter penguin.
Now take one species, one kind of penguin, alone.
Will deeper bills still go with lighter penguins? Will there be no link?
Or will deeper bills go with heavier penguins?
Moving together
First, here's a pair that's easier to read: flipper length and mass.
Longer flippers come with heavier penguins, the way taller people tend to weigh more. The dots rise together, close to a line. But how tightly, as one number?
Who agrees
Split the penguins at the average flipper and the average mass. A penguin above both averages, or below both, agrees. A penguin above one and below the other disagrees.
Most of them agree.
One number: r
Now give each penguin two numbers: how many standard deviations it is from the average flipper, and from the average mass.
Below the average, the number gets a minus sign.
Then multiply the two.
This Gentoo has a flipper of two hundred and fifteen millimeters. That's one standard deviation above the average. Its mass, five kilos, is one above too.
One times one is one.
This Adelie is about one below on both.
What's minus one times minus one?
Plus one. So a penguin that agrees gives a plus, and a penguin that disagrees gives a minus.
Average this over all the penguins, and you get zero point eight seven.
That number... is called the correlation, r.
From minus one to one
r runs from minus one to one. At one, every dot sits on a line going up. At minus one, on a line going down. And at zero? No line at all, up or down. The sign says which way, and the size says how tight. So minus zero point nine is as tight as plus zero point nine. Zero point eight seven is close to a line, going up.
How much it explains
So what does zero point eight seven give a model that guesses mass?
A model that guesses the average mass for every penguin has a loss of zero point six four one. That's the variance. In Calculus for AI, the best line from flipper length has a loss of only zero point one five five. That's about a quarter of zero point six four one. So the line leaves a quarter of the spread, and explains the other three quarters: zero point seven six.
Now multiply r by itself. Zero point eight seven times zero point eight seven: zero point seven six. The same number.
r squared... is the share of the spread a line explains.
Below zero
Here's another pair: bill depth and mass. Bill depth is how tall a penguin's bill is. Its r with mass is minus zero point four seven. That's below zero: deeper bills come with lighter penguins, and most penguins disagree. And it's looser than the flippers: the dots spread wider around their line.
Inside each species
Now split the penguins by species, each in its own shape. Look at the three lines. All three go up, each with an r above plus zero point five. Inside every species, deeper bills go with heavier penguins.
So why do the dots slope down overall?
Look at where each species sits.
If you said "still lighter", here's why that felt right: overall, the dots do slope down. But the Gentoos are heavy, about five kilos, with shallow bills, about fifteen millimeters.
The Adelies and Chinstraps are light, under four kilos, with deep bills, about eighteen. Put them together, and the slope goes the other way.
Not a cause
So r only says that two things move together in this data.
Something else can move both of them: here, the species.
A third thing like that can even turn a plus into a minus.
Models fall for this too. A model learns every link in its data, true or not.
Researchers once trained a model on purpose, with photos where every wolf stood in snow.
Snow and "wolf" moved together, so the model learned the snow.
It called a husky in snow a wolf.
In code
Now in real code. pandas gives r in one line: flipper length and mass, zero point eight seven. The table keeps mass in grams, and r has no unit, so grams or kilos give the same number.
One more line gives every column against mass. Flipper length, zero point eight seven. Bill depth, minus zero point four seven.
Then groupby splits the table into groups by species. Inside each species, r is above zero, every time.
Before you train a model, this table shows which columns move with the one you want to guess. When two columns move together, ask what moves them both.
What moves together
So the correlation, r, says how tightly two things rise or fall together, from minus one to one.
r squared says how much of the spread a line explains.
And a third thing can make the link, or turn it the other way.
The lab
That's the end of this unit. In its lab, you use these three lessons to scan the penguins' columns, the way code does before training.
Not why
A correlation shows what moves together, but not why. Now try it on this lesson's page, and take the quiz. Find another pair whose link flips inside each species.
You use this lesson in Lab 2: Scan the penguins before a model, which comes next.
Facts last checked on .
