Covariance
Descriptive Statistics
Do Two Variables Move Together? Covariance Tells You
Covariance measures how two variables change together. Positive covariance means they tend to move in the same direction; negative means opposite directions.
- Direction of relationship — Positive, negative, or zero covariance reveals the sign of association
- Magnitude is scale-dependent — The raw number is hard to interpret without normalization
- Covariance matrix — The foundation of multivariate statistics and portfolio theory
- Gateway to correlation — Standardizing covariance produces the Pearson correlation coefficient
What You'll Learn
- 1Compute sample covariance by hand from paired observations and verify it against NumPy
- 2Interpret the sign of covariance while refusing to read strength from its raw magnitude
- 3Explain why rescaling one variable multiplies covariance by the same factor
- 4Build a covariance matrix and use its diagonal, off-diagonal, and quadratic forms
Covariance answers one question with two numbers in hand: when observations sit above their own mean, does the paired observation tend to sit above its mean as well? Stock returns and market returns, study hours and exam scores, advertising spend and weekly sales — each pair produces a stream of deviation products, and covariance is their average. The sign of that average tells you the direction of the linear association. The number itself carries the units of both variables multiplied together, which is exactly why it is useful inside matrix algebra and exactly why you should never quote it alone in a report.
From Paired Observations to a Joint Measure
Take paired observations . Center each variable by subtracting its own mean, multiply the two deviations pair by pair, and average the products. That chain of steps is the entire idea:
Each term is positive when both observations are above their means or both below, and negative when one is above while the other is below. A dataset dominated by same-direction pairs yields positive covariance; opposite-direction pairs drag it negative; a roughly even mix cancels toward zero. The divisor makes the sample covariance an unbiased estimator of the population quantity under random sampling. Zero covariance means no linear co-movement — curved relationships can still hide there, which is why a scatter plot always earns its space next to the number.
A Ten-Point Worked Example
Suppose ten students report study hours and exam scores. Work the formula by hand once and every library call afterwards becomes trustworthy.
The same data give hours and points, which you will reuse in the correlation section below.
import numpy as np
import pandas as pd
data = pd.DataFrame({
'study_hours': [2, 3, 5, 4, 6, 1, 7, 3, 5, 8],
'exam_score': [60, 65, 75, 70, 80, 55, 85, 65, 72, 90]
})
mean_x = data['study_hours'].mean()
mean_y = data['exam_score'].mean()
deviations_xy = (data['study_hours'] - mean_x) * (data['exam_score'] - mean_y)
cov_manual = deviations_xy.sum() / (len(data) - 1)
cov_numpy = np.cov(data['study_hours'], data['exam_score'])[0, 1]
print(f"Sum of deviation products: {deviations_xy.sum():.2f}")
print(f"Manual covariance: {cov_manual:.4f}")
print(f"NumPy covariance: {cov_numpy:.4f}")
Reading the Sign, Misreading the Magnitude
Three rules keep interpretations honest. First, the sign: positive covariance means above-average pairs with above-average on average; negative means the pairing flips; near-zero means the linear signal is weak or the relationship bends. Second, symmetry: always, because the product of deviations commutes. Third, the trap: covariance is not bounded, and it scales with units. Recode the hours in the worked example as minutes and every deviation multiplies by 60, pushing covariance from 24.47 to 1,468 without any change in the underlying relationship.
| Situation | Typical covariance | What you may conclude |
|---|---|---|
| X and Y rise together | Positive | Same-direction linear association |
| X rises while Y falls | Negative | Opposite-direction linear association |
| No linear pattern | Near zero | No linear signal; check for curves |
| X recoded in new units | Scales by the unit factor | Sign survives, magnitude does not compare |
Because of that unit sensitivity, covariance is a component of a larger machine, not a reportable effect size. The bounded, unit-free quantity built from it is Pearson's correlation, covered in the next lesson.
Sample versus Population Covariance
Software disagrees with textbooks on one detail: the divisor. The unbiased sample estimate divides by , matching the and you compute with ddof=1. The maximum-likelihood (biased) estimator divides by and is what some physics and engineering pipelines emit. NumPy's np.cov defaults to ; set bias=True if you deliberately want the version. Mixing the two conventions inside one project shifts every covariance by a factor of — at that is a 3.4 percent drift, small enough to hide in a spreadsheet and large enough to fail a strict numerical regression test.
x = data['study_hours'].to_numpy()
y = data['exam_score'].to_numpy()
cov_ddof1 = np.cov(x, y, ddof=1)[0, 1] # unbiased, divisor n-1
cov_ddof0 = np.cov(x, y, ddof=0)[0, 1] # MLE, divisor n
n = len(x)
print(f"ddof=1 covariance: {cov_ddof1:.4f}")
print(f"ddof=0 covariance: {cov_ddof0:.4f}")
print(f"Ratio equals n/(n-1) = {n/(n-1):.4f}: {np.isclose(cov_ddof1/cov_ddof0, n/(n-1))}")
The Covariance Matrix
Stack several variables and covariance becomes a matrix. For variables, entry holds , so the diagonal repeats each variable's own variance and the off-diagonal entries carry every pairwise covariance. The matrix is always symmetric, and for any vector the quadratic form is the variance of the weighted combination — the single fact that powers portfolio theory and principal component analysis. Markowitz portfolio variance is exactly : diversification works when off-diagonal covariances are smaller than the product of individual risks.
import seaborn as sns
import matplotlib.pyplot as plt
iris = sns.load_dataset('iris')
numeric = iris.select_dtypes(include='number')
cov_matrix = numeric.cov()
print("Covariance Matrix (Iris):")
print(cov_matrix.round(4))
w = np.array([0.5, 0.3, 0.1, 0.1])
portfolio_var = w @ cov_matrix.to_numpy() @ w
print(f"\nVariance of the weighted combo w = {w}: {portfolio_var:.4f}")
fig, ax = plt.subplots(figsize=(6, 5))
sns.heatmap(cov_matrix, annot=True, fmt='.2f', cmap='RdBu_r', center=0, ax=ax)
ax.set_title('Covariance Matrix (Iris Dataset)')
plt.tight_layout()
plt.show()
Covariance and Correlation Side by Side
Divide covariance by both standard deviations and the units cancel, leaving Pearson's on a fixed scale from to :
On the worked study-hours data, — an almost perfect positive linear relationship that the raw covariance of 24.47 could never advertise on its own.
| Property | Covariance | Pearson correlation |
|---|---|---|
| Range | ||
| Units | Units of X times units of Y | Dimensionless |
| Changes if X is rescaled | Yes, by the same factor | No |
| Readable strength | No | Yes: near 1 is strong |
| Role in algebra | Entries of , portfolio variance | Effect size and reporting |
cov = np.cov(data['study_hours'], data['exam_score'])[0, 1]
sx = data['study_hours'].std(ddof=1)
sy = data['exam_score'].std(ddof=1)
r_from_cov = cov / (sx * sy)
r_numpy = np.corrcoef(data['study_hours'], data['exam_score'])[0, 1]
print(f"r from covariance formula: {r_from_cov:.6f}")
print(f"r from np.corrcoef: {r_numpy:.6f}")
Where Covariance Drives Machine Learning
Nearly every multivariate method consumes covariance indirectly. Principal component analysis eigendecomposes the covariance (or correlation) matrix to find directions of maximal variance, so features measured in different units corrupt the result unless you switch to the correlation matrix. Multicollinearity detection flags pairs whose covariance approaches the product of their standard deviations, because duplicated features make regression coefficients unstable. Gaussian discriminant analysis and many anomaly detectors model directly, and a singular covariance matrix — often from redundant columns — breaks the inverse those models need.
| ML application | How covariance enters | Failure mode if ignored |
|---|---|---|
| PCA | Eigenvectors of | Unit-dominated components |
| Multicollinearity | High feature covariance | Unstable OLS coefficients |
| Portfolio optimization | risk | Understated diversification benefit |
| Gaussian Bayes | Full covariance per class | Singular matrix, crashed fit |
| Anomaly detection | Distance scaled by | False alarms on correlated features |
from sklearn.decomposition import PCA
from sklearn.datasets import load_iris
X = load_iris().data
print("Covariance matrix:")
print(np.cov(X.T).round(2))
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)
print(f"\nExplained variance ratio: {pca.explained_variance_ratio_}")
print(f"Total variance explained: {pca.explained_variance_ratio_.sum():.3f}")
💡A quick covariance sanity check
Common Mistakes
Reporting covariance as a measure of relationship strength
Fix: Report Pearson correlation for strength; keep covariance for matrix algebra and variance calculations.
Comparing covariances across variables measured in different units
Fix: Standardize first: correlation equals covariance divided by both standard deviations, so units cancel.
Mixing ddof=0 and ddof=1 across a pipeline
Fix: Pick the n-1 convention once, document it, and pass the same ddof to every variance and covariance call.
Best Practices
- Always print the covariance matrix alongside the correlation matrix when exploring features
- Check symmetry and positive semi-definiteness before inverting a covariance matrix
- Switch to the correlation matrix whenever features carry different physical units
- Pair every covariance number with a scatter plot to catch curved or clustered structure
Key Takeaways
- Covariance averages the products of paired deviations, so its sign gives the direction of linear association
- The raw magnitude carries units of X times Y and rescales with any unit change, so it never measures strength alone
- Sample covariance divides by n-1; the covariance matrix diagonal holds variances and wᵀ Σ w is the variance of a weighted sum
- Dividing covariance by sX times sY yields Pearson correlation, the bounded statistic you actually report
Frequently Asked Questions
Can covariance be zero when two variables are related?
Yes. Covariance only detects linear co-movement. A perfect parabolic relationship such as over a symmetric range of has zero covariance even though is completely determined by . Always pair the number with a scatter plot.
Why does NumPy's np.cov return a matrix for two vectors?
np.cov always returns the full covariance matrix of its inputs. For two one-dimensional arrays the result is a 2 by 2 matrix whose diagonal entries are the variances and whose off-diagonal entries are both the covariance — take element [0, 1] or [1, 0].
Does a large positive covariance mean the data are close to a line?
Not by itself. A cloud with huge spread in both variables can produce a large covariance while sitting far from any line. Only the correlation coefficient, which divides out both spreads, tells you how tightly the points hug a linear trend.
Interview Questions
Q1: What are the units of covariance and why does that matter?
Covariance is measured in units of X times units of Y — hour-points in the study-hours example. That is why it feeds matrix algebra like portfolio variance wᵀ Σ w, but why correlation, which divides out both standard deviations, is what you report as an effect size.
Q2: How do you prove covariance is symmetric?
The numerator is a sum of products (xi − x̄)(yi − ȳ), and multiplication commutes, so swapping X and Y leaves every term unchanged; therefore Cov(X, Y) equals Cov(Y, X).
Q3: What happens to covariance if you multiply X by 10?
Every deviation of X scales by 10, so the covariance scales by 10 as well. The correlation coefficient is unchanged because the same factor appears in the numerator and in sX.
Q4: Why is the sample covariance divided by n − 1?
Dividing by n − 1 removes the bias introduced by estimating the means from the same sample, making the estimator unbiased for the population covariance under random sampling.