Contents/ Part XIV · Correlation & Association/ Chapter 92

Covariance

Inference asked questions about one variable at a time. Now we ask how two variables relate. Covariance is the first answer: a single signed number for the direction two variables move together. Its catch, that its size depends on units, is exactly what motivates correlation in the next chapter.

⏱️ ~15 min read
🐍 Notebook included
📊 Chapter 92

Do advertising spend and sales rise together? Does resting heart rate fall as exercise rises? These are questions about association, how two variables co-vary. The simplest measure is covariance, and it is the foundation everything in this Part builds on.

cov
The covariance of x and y is the average of the products of their deviations from their means: cov(x, y) = mean of (x − x̄)(y − ȳ). It is positive when they move together, negative when they move oppositely, and near zero when there is no linear tendency.
🔗
The chapter in one line

Covariance reads the direction two variables move together from its sign. But its magnitude depends on the units, which is why we standardize it into correlation.

1

What Covariance Measures

Picture a scatterplot. If high x tends to come with high y (and low with low), the cloud slopes up and covariance is positive. If high x comes with low y, it slopes down and covariance is negative. A shapeless cloud gives covariance near zero.

The sign of covariance is the direction of the slope cov > 0 cov < 0 cov ≈ 0 np.cov(x, y) returns the 2×2 matrix; the off-diagonal entry is the covariance

In the notebook these three pictures come straight from np.cov: covariance about +0.8, −0.8, and 0.0. One signed number captures "which way do they move together?", the starting point for every relationship measure that follows.

2

The Formula & the Quadrant Intuition

Split the scatterplot into four quadrants with vertical and horizontal lines at the two means. A point where both x and y are above their means (upper-right) or both below (lower-left) has a positive deviation product. The other two quadrants give negative products. Covariance is the average of all of them.

cov = mean of (x − x̄)(y − ȳ) + (both above) + (both below) more (and stronger) points on the purple diagonal → positive covariance

It is a vote: each point casts a signed product, and the average is the covariance. In the notebook, coloring points by the sign of their product makes a positive relationship visibly purple-dominated. (Use ddof to pick the population or sample version; the sign and story are the same.)

3

Covariance vs Correlation

Covariance has a fatal flaw for comparison: its units are x times y, so its magnitude is arbitrary. Measure y in cents instead of dollars and the covariance jumps 100-fold, though nothing about the relationship changed. Divide by the two standard deviations and the units cancel, giving correlation, a unitless number locked into [−1, 1].

Change the units: covariance moves, correlation does not cov(x, y) = 0.45 → cov(x, 1000y) = 450 magnitude depends on units (uninterpretable) corr = cov / (sₓ sₐ) = 0.75 either way unitless, in [−1, 1] (comparable) correlation = covariance, standardized by the spread of each variable covariance answers "which direction?" · correlation answers "how strong?"

So the two are partners. Covariance gives the raw signed strength in the data's own units; correlation rescales it to a universal −1-to-1 ruler you can compare across any pair of variables. Correlation Coefficients is devoted to that ruler.

4

Real-World Example: Ad Spend & Sales

A marketing team has 160 campaigns with spend, reach, visits, and sales. We compute the covariance matrix (a grid of unit-dependent numbers) and the correlation matrix (a readable heatmap), and see why analysts almost always reach for the latter.

📂 Dataset · covariance--ad_sales.xlsx

One row per campaign with ad_spend, impressions, web_visits, and sales (plus region).

PairCovarianceCorrelationReading
ad_spend & sales≈ 29,000,0000.95very strong, positive
ad_spend & web_visitslarge positive0.97very strong, positive
web_visits & saleslarge positive0.91strong, positive

The covariance between spend and sales is roughly 29 million (dollars times dollars), a magnitude you cannot interpret or compare to anything. Standardized, that same relationship is a correlation of 0.95, instantly legible as "very strong and positive." Every metric here moves together, which is precisely why analysts read the correlation heatmap, not the covariance grid. The notebook draws both with pandas and seaborn.

Correlation heatmap: every metric moves together ad spend impressions web visits sales ad spend 1.00 0.99 0.97 0.95 impressions 0.99 1.00 0.95 0.93 web visits 0.97 0.95 1.00 0.91 sales 0.95 0.93 0.91 1.00 0 (none) 1 (perfect +)

How to read it: each cell is the correlation between its row and column variable, so the grid is symmetric and the diagonal is always 1.00 (a variable correlates perfectly with itself). Darker purple means a stronger positive correlation. Here every off-diagonal cell is dark (0.91 to 0.99): all four marketing metrics rise together almost in lockstep, more spend buys more impressions and visits, which turn into more sales. Why it matters: a heatmap turns a wall of numbers into an instant picture, you spot the strongest and weakest links at a glance, which is exactly why the correlation heatmap is the standard first look at any set of numeric variables.

5

Covariance in Machine Learning & AI

The covariance matrix is one of the most important objects in all of machine learning.

Idea (this chapter)In ML / AI it becomesExample
Covariance matrixThe shape of multivariate datathe Σ in a multivariate Gaussian
Directions of variancePrincipal Component Analysis (PCA)eigenvectors of the covariance matrix
StandardizingWhitening & Mahalanobis distancedistance that accounts for correlation
Sign of covarianceFeature relationship screeningwhich inputs move with the target
🤖
Why this matters for AI research

The covariance matrix encodes how every pair of features varies together, and its eigen-decomposition is exactly PCA: the eigenvectors point along the directions of greatest variance, letting you compress or denoise high-dimensional data. The same matrix defines the multivariate Gaussian at the heart of many models, and Mahalanobis distance uses its inverse to measure distance in a way that respects correlation (crucial for anomaly detection). Covariance is where one-variable statistics ends and the multivariate world of modern ML begins.

🐍

See covariance in pictures with Python

The companion notebook plots positive, negative, and zero covariance, colors the deviation quadrants, shows how units change covariance but not correlation, and loads covariance--ad_sales.xlsx to compare the covariance matrix with a seaborn correlation heatmap.

📓 View Notebook (code & outputs) ▶ Open in Colab ⬇ View / Download on GitHub

View opens the rendered notebook instantly (no setup). Open in Colab runs & edits it live in your browser. To run locally, install numpy, pandas, scipy, matplotlib, seaborn, statsmodels, and openpyxl and launch jupyter notebook.

🎓 Key Takeaways

  • Covariance = mean of (x − x̄)(y − ȳ); positive = move together, negative = move oppositely, ~0 = no linear tendency.
  • Quadrant intuition: points on the same side of both means push covariance up; opposite-side points push it down.
  • Units matter: covariance scales with the units of x and y, so its magnitude is not comparable across pairs.
  • Standardize by the two SDs to get correlation, unitless and in [−1, 1] (next chapter).
  • In ML/AI: the covariance matrix drives PCA, the multivariate Gaussian, and Mahalanobis distance.
6

Practice Challenges

Five short challenges, beginner to intermediate. Try them with NumPy and pandas before checking the solutions.

1

Covariance from the formula

For x = [1,2,3,4,5], y = [2,4,5,4,5], compute covariance as the mean of deviation products and check with NumPy.

Hint: ((x-x.mean())*(y-y.mean())).mean() matches np.cov(ddof=0).
2

Sign of covariance

Generate a negatively related pair and confirm the covariance is negative.

Hint: y = −0.7·x + noise.
3

Units change covariance, not correlation

Show cov(x, 100y) = 100·cov(x, y) while the correlation is unchanged.

Hint: compare np.cov and np.corrcoef.
4

Standardize to correlation

Compute correlation as cov/(sₓ·sₐ) and confirm it matches np.corrcoef.

Hint: use ddof=1 standard deviations.
5

Real data: covariance vs correlation matrix

Load covariance--ad_sales.xlsx and print the covariance and correlation matrices of the four numeric columns.

Hint: df.cov() and df.corr().
Check your work

A fully-worked solutions notebook walks through all five challenges, each verified in code. Try them yourself first, then compare.

📓 View Solutions ▶ Open Solutions in Colab ⬇ View / Download on GitHub
7

Quiz: Test Yourself

Eight quick questions on covariance. Answer them, hit Check Answers, and keep refining until you score 100%. Your progress is saved, so you can hop back to the chapter and return anytime.

➡️
Up next

Covariance told us the direction; its magnitude was unreadable. Correlation Coefficients standardizes it into Pearson's r and Spearman's rank correlation, the −1-to-1 ruler for the strength of a relationship.