Correlation: Pearson, Spearman & Multicollinearity
Here is where this two-lesson story ends up. Three real-looking results that mislead, each of which you will be able to catch by the end of Part 2:
- A classifier is trained on photos where most camels stand on sand and most cows on grass. It quietly learns "sand means camel", scores well on a test set from the same collection, and fails the day a camel stands on grass.
- A hospital model learns that patients given an intensive-care bed are higher risk. That is true in the data and useless as advice, because nobody should withhold the bed.
- Model A beats model B on overall accuracy while B is better inside every segment of users, which is Simpson's paradox in an evaluation table.
- Each is a correlation that is real in the data and still a poor guide to action. This lesson builds the measuring tools, and Part 2 gives you the questions that expose them.
After this lesson, you will be able to:
- Compute Pearson's r by hand from deviations, interpret r and r squared, and explain why r only detects straight-line association
- Use Anscombe's quartet to show that four very different datasets can share the same mean, variance, regression line and r of about 0.816
- Compute Spearman's rank correlation, and say when it beats Pearson (monotone but curved relationships, outliers)
- Read a correlation matrix, spot redundant features, explain why highly correlated inputs make linear regression coefficients unstable, and compute the matrix and per-group means in pandas
Before you start
#Why Correlation Is the Most Misused Number
Correlation answers one narrow question: if I know X, how well can I guess Y with a straight line? It says nothing about why, and nothing about what happens if you change X.
Cov(X, Y) = E[(X − μ_X)(Y − μ_Y)], where μ (mu) is the mean of a variable. This lesson takes the standardised version, Pearson's r, and puts it under stress. Causal estimation itself lives in the Causal Inference Basics lesson in the classical ML track, which covers propensity scores (the modelled chance that a unit receives the treatment, used to compare like with like) and Double ML (using machine-learning models to strip the confounders out of both variables before comparing them). Here we stay with the foundations: what the number is, how it breaks, and how to avoid being fooled by it. This is Part 1 of two lessons, and it follows Checkpoint: Foundations Review. Part 2, Causation, Confounding & Simpson's Paradox, takes the number into the question of cause.Every section below uses numbers you can verify by hand or by running the code. All counts and simulations are synthetic and labelled as such. The one real dataset is Anscombe's quartet, a famous public teaching example from 1973.
#Covariance Recap and Pearson r
Covariance measures whether X and Y sit above or below their means together:
The trouble with covariance is its units. Heights in centimetres and weights in kilograms give a covariance in cm·kg, and changing centimetres to metres changes the number by a factor of 100 without changing the relationship. Dividing by both standard deviations removes the units:
How to read the value:
- r = +1 means every point lies exactly on a rising line. r = −1 means exactly on a falling line.
- r = 0 means no linear association. It does not mean no association (see Anscombe below).
- r squared is the fraction of the variance of Y that the best straight line through X accounts for. With r = 0.5, only 25 percent.
- r is symmetric (
r(X, Y) = r(Y, X)) and unchanged if you shift either variable or rescale it by a positive factor, for example grams to kilograms (a negative factor only flips the sign of r).
Two results are hiding in the bullets above: why r can never leave the range from minus 1 to plus 1, and why shifting or rescaling a variable cannot change it. Open either derivation to see each step.
#Pearson r by Hand on Eight Points
Eight students record hours studied (x) and exam score (y). Compute r step by step.
| student | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| hours x | 1 | 2 | 3 | 5 | 6 | 7 | 8 | 8 |
| score y | 48 | 52 | 55 | 58 | 62 | 66 | 69 | 70 |
| student | x − 5 | y − 60 | product | (x − 5)² | (y − 60)² |
|---|---|---|---|---|---|
| 1 | −4 | −12 | 48 | 16 | 144 |
| 2 | −3 | −8 | 24 | 9 | 64 |
| 3 | −2 | −5 | 10 | 4 | 25 |
| 4 | 0 | −2 | 0 | 0 | 4 |
| 5 | 1 | 2 | 2 | 1 | 4 |
| 6 | 2 | 6 | 12 | 4 | 36 |
| 7 | 3 | 9 | 27 | 9 | 81 |
| 8 | 3 | 10 | 30 | 9 | 100 |
| sum | 153 | 52 | 458 |
So Sxy = 153, Sxx = 52, Syy = 458.
Notice what each part did. Student 4 studied 5 hours, exactly the average, so the x deviation is 0 and the product contributes nothing. Students 1 and 8 sit far from the centre on both axes and contribute the most. Correlation is dominated by the points that are far from both means.
Two more results sit behind the number: the slope of the best straight line, and what r squared means. Open them if you want to see where they come from.
Now let the code confirm every number, and move straight on to the case that breaks the rule.
#What r Measures and What It Does Not: Anscombe's Quartet
Four datasets each have 11 points. All four have the same mean of x, the same mean of y, the same variance of x and y, the same r, and the same best-fit line. How alike do their scatter plots look?
Here are the four datasets, which are public and widely reproduced. Datasets I, II and III share the same x values. In set IV, ten points have x = 8 and one has x = 19.
| x (I, II, III) | 10 | 8 | 13 | 9 | 11 | 14 | 6 | 4 | 12 | 7 | 5 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| y I | 8.04 | 6.95 | 7.58 | 8.81 | 8.33 | 9.96 | 7.24 | 4.26 | 10.84 | 4.82 | 5.68 |
| y II | 9.14 | 8.14 | 8.74 | 8.77 | 9.26 | 8.10 | 6.13 | 3.10 | 9.13 | 7.26 | 4.74 |
| y III | 7.46 | 6.77 | 12.74 | 7.11 | 7.81 | 8.84 | 6.08 | 5.39 | 8.15 | 6.42 | 5.73 |
| x (IV) | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 19 | 8 | 8 | 8 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| y IV | 6.58 | 5.76 | 7.71 | 8.84 | 8.47 | 7.04 | 5.25 | 12.50 | 5.56 | 7.91 | 6.89 |
Running the code below confirms that for all four sets the mean of x is 9.00, the mean of y is 7.50, the variance of x is 11.00, the variance of y is about 4.13, the best-fit line is y ≈ 3.00 + 0.50x, and r is 0.816 for I, II and III and 0.817 for IV (about 0.816 in every case).
What the plots show:
- I: a noisy straight line. r is a fair summary here.
- II: a perfect smooth curve (an inverted U). The relationship is exact, yet r is still 0.816, because r only measures the straight-line part.
- III: an exact straight line with one outlier. Without the outlier r would be 1.000 and the line would be different. One point drags r down and tilts the slope.
- IV: every x is 8 except one point at 19. The entire correlation comes from that single point. Remove it and there is no relationship at all.
Picture what r is built to detect. A scatter of points that forms a tilted oval cloud has r well away from zero, and the thinner the oval, the closer |r| is to 1. A round cloud has r near 0. A tilted oval is exactly the shape r can detect, and the only shape it can detect: a U or a ring is far from random, yet its r is near zero, which is Anscombe's set II again.
You can check the claim about the U-shape with one line of algebra. The derivation shows why a perfect curve can still have zero correlation.
#Spearman Rank Correlation
Spearman's ρ (rho) answers a looser question: when X goes up, does Y tend to go up, whatever the shape? The recipe is simple. Replace each value by its rank (1 for the smallest, n for the largest, ties share the average rank), then compute Pearson's r on the ranks.
The shortcut formula above is a result, and the next derivation builds it from the idea that Spearman is Pearson on ranks.
| situation | Pearson r | Spearman ρ |
|---|---|---|
| straight line, light noise | good | about the same |
| monotone but curved (growth, saturation) | understates | captures it |
| a few extreme outliers | distorted | robust |
| non-monotone (U-shape) | near 0 | also near 0 |
| you need the actual linear slope | meaningful | not the right tool |
Spearman is not magic. A U-shape is not monotone, so it fails there too. And it discards the sizes of the gaps, so if magnitude matters, it throws information away.
#The Correlation Matrix and Multicollinearity
In ML you read the matrix for three things:
- Feature to label. A large |r| with the target suggests a feature carries a linear signal. Remember the limits above: it can also be a confounder's footprint.
- Feature to feature. Pairs near ±1 are redundant. Two columns that are the same quantity in different units (square metres and square feet) add no information, only trouble.
- Clusters of features. Blocks of high correlation hint at a smaller number of underlying factors, which is the idea behind PCA.
y = 3·x1 + noise (so the true coefficients are 3 and 0). Refitting 300 times on fresh samples of 50, with x2 only loosely tied to x1 (r about 0.7), the coefficient on x1 has a standard deviation of 0.20. With x2 a near-copy (r about 0.998), the standard deviations balloon to about 2.85 each, a 14-fold jump, while the standard deviation of the sum of the two coefficients stays at 0.15 because the combined signal is still pinned down.Take three rows and two features, X with rows (1, 0), (0, 1), (1, 1), and targets y = (1, 2, 3). Each entry of X^T X is the dot product of two columns. Column 1 is (1, 0, 1) and column 2 is (0, 1, 1), so the table is 2, 1 on top and 1, 2 below. The entries of X^T y are the dot products of each column with y: 1 + 3 = 4 and 2 + 3 = 5.
The fit is y = 1 times column 1 plus 2 times column 2, which gives 1, 2, 3 and so matches y exactly, with no leftover error. The derivation below uses this same recipe, with centred columns so that X^T X holds the sums S_11, S_12 and S_22.
Why correlated inputs inflate the variance of the coefficients, and why their sum is spared, can be derived exactly for two features. The derivation reproduces the 14-fold jump in the simulation.
0.05 to 0.5 and watch the coefficient spread fall as the two columns become less alike. The usual fixes for collinearity are to drop or combine redundant columns, or to add regularisation (RegularizationRegularizationRegularization adds a penalty term to the loss function (L1, L2) to discourage overly complex models and reduce overfitting.Learn more), which adds a penalty on large coefficients and so shrinks the arbitrary coefficient splits towards a stable answer (covered in a later lesson).Two features have r = 0.998. You fit a linear regression with both. Which statement is most accurate?
#The Same Tools in pandas: corr(), groupby and a Heat-Map
df.corr() returns the Pearson correlation matrix of every numeric column at once (method="spearman" gives the rank version). df.groupby("col")[...].mean() splits the rows into groups and summarises each group, which is exactly the compare-inside-the-groups move that Simpson's paradox is about. And plt.imshow paints a grid of numbers as coloured squares, so a correlation matrix becomes a heat-map you can scan in a second: red for positive, blue for negative.users is the same data every time. We add one column, pro, which is 1 for a Pro user and 0 for a Free one, because a 0/1 column can be correlated like any other.churned against sessions_per_week is −0.561 and against session_min is −0.343: users who stay open the app more often and for longer. pro against churned is −0.290, so Pro users churn less. The grouped means say the same thing in the units you care about: stayers average 30.19 minutes and 4.35 sessions a week, churners 15.29 minutes and 1.20 sessions. And grouping by plan and device shows where the churn sits: Free Mobile churns 40.0 percent of its 70 users, Free Desktop 20.0 percent of 30, Pro Mobile 15.0 percent of 40 and Pro Desktop 6.7 percent of 60.Everything above is a correlation. It tells you that short sessions go with churn, not that lengthening a session would keep a user. Treat the heat-map as a list of places to look, and ask the three-explanations question of every red or blue square, which Part 2 spells out.
.corr() to .corr(method="spearman") and see which squares move. Then add df.groupby("plan")["session_min"].mean() and compare it with the grouped means above.#Try It Yourself
Three short exercises put this lesson's main numbers in your hands: Spearman on a curved, tied dataset, the same correlations in pandas, and an outlier that moves Pearson but not Spearman. The pearson helper is given. Fill in the TODOs, then compare with the solution.
Tests: Pearson on the hours/steps data is about 0.758 and Spearman is about 0.994 (ties in steps get average ranks). df.corr() gives about 0.758 and df.corr(method='spearman') about 0.994 for hours against steps, and the mean of steps is 3.25 for late = 0 and 37.00 for late = 1. With the last steps value replaced by 1000, Pearson falls to about 0.596 while Spearman stays at about 0.994.
df.corr() repeats the Pearson number (0.758 between hours and steps) and method="spearman" gives 0.994. The late column, which marks the second half of the rows, correlates 0.873 with hours, and the grouped mean of steps rises from 3.25 to 37.00. In the third part, replacing the last value 95 by 1000 drags Pearson down from 0.7584 to 0.5958, while Spearman stays at 0.9940 because the ranks did not change.#Key Takeaways
- r is covariance without units —
r = Sxy / √(Sxx · Syy); on the eight-student data Sxy = 153, Sxx = 52, Syy = 458, so r = 0.9914 and r squared = 0.983 - r only sees straight lines — Anscombe's four datasets share mean 7.50, variance 4.13, line y = 3 + 0.5x and r about 0.816, yet they are a line, a curve, a line with an outlier, and one lone point creating the correlation
- Spearman is Pearson on ranks — it gives 1.000 on a monotone curve where Pearson gives 0.7905, and 0.9286 with an outlier where Pearson gives 0.6955; it still fails on U-shapes
- Correlated inputs destabilise coefficients — with r about 0.998 between two features each coefficient's standard deviation rises from about 0.2 to about 2.85, while their sum stays stable at about 0.15
- pandas does the bookkeeping —
df.corr()gives the matrix,groupby().mean()the per-group view andimshowthe heat-map; on StreamBox, churn correlates −0.561 with sessions per week and −0.343 with session minutes
#Quick Check
A dataset has Sxy = 60, Sxx = 25 and Syy = 196. What is Pearson's r?