Relationships — Covariance & Correlation
Lesson opener
In one line: Covariance shows whether two metrics rise and fall together; Pearson correlation scales that relationship so you can compare pairs fairly.
Why it matters: Before you pick features for a model, you need to know which metric pairs move together — and which “relationships” are just different units looking big.
Before this lesson: Foundations
Before you start
| Resource | Link |
|---|---|
| Glossary | Statistics glossary |
| Previous | Foundations |
| Next | Inferential stats |
| Prerequisites | Foundations |
| Time | ~40 minutes |
What you will learn
What covariance tells you about how two metrics move together — and why its size depends on units. What Pearson correlation measures and why it is easier to compare across pairs. How to use both when exploring data before machine learning.

Covariance
Layer 1 — Plain English Definition
Covariance answers a simple question: when one number goes up, does the other tend to go up too, go down, or wander on its own? A positive covariance means they generally move in the same direction. A negative covariance means when one rises, the other tends to fall. Zero means no consistent linear co-movement. The catch: the actual number you get depends on the scale of your variables — rupees times rupees can look huge while percentages look tiny, even when the relationship is equally strong.
Layer 2 — Real Life Analogy
Imagine you run a chai stall outside a Gurgaon IT park. On days you sell more cups, you also buy more milk from your supplier. Both numbers rise together — positive covariance. On rainy days, footfall drops and your milk order drops too. Covariance captures that “we rise and fall together” feeling, but it does not tell you how tight the link is in a way you can compare to, say, sugar purchases vs cup sales.
Layer 3 — Visual (SVG diagram)
Layer 4 — Terminology Table
| Term | Symbol | Plain English Meaning |
|---|---|---|
| Covariance | Cov(X, Y) | Average of “how far X is from its centre” times “how far Y is from its centre” |
| Variable X | X | First numeric column you are comparing (e.g. ad spend in ₹ lakh) |
| Variable Y | Y | Second numeric column (e.g. revenue in ₹ lakh) |
| Mean of X | x̄ | Balancing point of all X values |
| Mean of Y | ȳ | Balancing point of all Y values |
| Deviation | xᵢ − x̄ | How far one X observation sits from its average |
| Sample size | n | Number of paired observations |
Layer 5 — Hand Calculation
Data: x = [2, 4, 6, 8], y = [4, 8, 12, 16] (units in ₹ lakh — e.g. marketing spend vs revenue)
Step 1 — Means
- x̄ = (2 + 4 + 6 + 8) ÷ 4 = 20 ÷ 4 = 5
- ȳ = (4 + 8 + 12 + 16) ÷ 4 = 40 ÷ 4 = 10
Step 2 — Deviations and products
| i | xᵢ | yᵢ | (xᵢ − x̄) | (yᵢ − ȳ) | Product |
|---|---|---|---|---|---|
| 1 | 2 | 4 | 2 − 5 = −3 | 4 − 10 = −6 | (−3)(−6) = 18 |
| 2 | 4 | 8 | 4 − 5 = −1 | 8 − 10 = −2 | (−1)(−2) = 2 |
| 3 | 6 | 12 | 6 − 5 = +1 | 12 − 10 = +2 | (+1)(+2) = 2 |
| 4 | 8 | 16 | 8 − 5 = +3 | 16 − 10 = +6 | (+3)(+6) = 18 |
Step 3 — Sum and divide by n
- Sum of products = 18 + 2 + 2 + 18 = 40
- Cov(X, Y) = 40 ÷ 4 = 10
Positive covariance — when spend rises, revenue rises in this dataset.
Now verify this in Python:
Layer 6 — Formula with Symbol Breakdown
Population covariance:
\[
\text{Cov}(X,Y) = \frac{1}{n}\sum_{i=1}^{n}(x_i - \bar{x})(y_i - \bar{y})
\]
| Symbol | What it is | What it does | Why it is there |
|---|---|---|---|
| n | Count of pairs | Divides the sum into an average | Turns total co-movement into one summary number |
| xᵢ, yᵢ | One paired observation | The actual spend and revenue for week i | Grounds the formula in real rows |
| x̄, ȳ | Means of X and Y | Reference “typical” level for each column | Deviations measure movement relative to normal |
| (xᵢ − x̄)(yᵢ − ȳ) | Product of deviations | Positive when both above or both below mean; negative when one above, one below | Captures direction of joint movement |
| Σ | Sum | Adds co-movement across all weeks | One pair is noise; the pattern is in the total |
Layer 7 — Python Verification
import numpy as np
x = np.array([2, 4, 6, 8])
y = np.array([4, 8, 12, 16])
# Population covariance (matches hand calc)
cov_matrix = np.cov(x, y, bias=True)
print(f"Cov(X, Y) = {cov_matrix[0, 1]:.1f}")Expected output:
Cov(X, Y) = 10.0Layer 8 — Real Dataset Application
A Bengaluru D2C brand tracks weekly Instagram ad spend (₹ lakh) and website revenue (₹ lakh) for six weeks:
| Week | Ad spend | Revenue |
|---|---|---|
| 1 | 3 | 12 |
| 2 | 5 | 18 |
| 3 | 4 | 15 |
| 4 | 7 | 24 |
| 5 | 6 | 21 |
| 6 | 8 | 28 |
import pandas as pd
import numpy as np
df = pd.DataFrame({
"ad_spend_lakh": [3, 5, 4, 7, 6, 8],
"revenue_lakh": [12, 18, 15, 24, 21, 28],
})
cov = np.cov(df["ad_spend_lakh"], df["revenue_lakh"], bias=True)[0, 1]
print(f"Covariance: {cov:.2f} lakh²")
print(f"Spend mean: ₹{df['ad_spend_lakh'].mean():.1f} lakh")
print(f"Revenue mean: ₹{df['revenue_lakh'].mean():.1f} lakh")Interpretation: Covariance is positive (~9.17 lakh²) — higher spend weeks align with higher revenue weeks. But “9.17 lakh²” is hard to explain in a board meeting. That is exactly why we standardise to correlation next.
Layer 9 — Common Mistakes
❌ Wrong: Compare covariance of “salary vs bonus” (₹ scale) directly to “hours vs rating” (different units) and say the larger number means the stronger relationship.
✅ Right: Use correlation for cross-metric strength comparisons; use covariance when you need the raw co-movement in original units or inside algorithms like PCA.
💡 Why: Covariance scales with how big your numbers are — doubling every salary doubles covariance even if the relationship shape is unchanged.
❌ Wrong: Treat negative covariance as “no relationship.”
✅ Right: Negative covariance means an inverse linear tendency — e.g. discount depth up, margin per unit down.
💡 Why: People equate “negative” with “unrelated,” but covariance only describes direction, not absence of pattern.
Layer 10 — ML Connection
When you run Principal Component Analysis (PCA) in scikit-learn, the algorithm builds new axes from the covariance matrix of your features. Columns with large covariance with the target or with each other influence which directions capture most variance. Before PCA on a CRM dataset, checking covariances (or correlations) between monthly_spend, support_tickets, and tenure_months tells you whether you are feeding redundant signals that will split importance across duplicate components.
Correlation (Pearson)
Layer 1 — Plain English Definition
Pearson correlation measures how closely two variables follow a straight-line trend together, on a fixed scale from negative one to positive one. Plus one means a perfect upward line — when one goes up, the other goes up in exact proportion. Minus one means a perfect downward line. Zero means no linear trend. Unlike covariance, correlation has no units, so you can compare “ad spend vs revenue” with “NPS vs repeat purchase rate” fairly.
Layer 2 — Real Life Analogy
Two Mumbai sales reps track daily call count and daily orders closed. Rep A’s points form a tight upward line — correlation near +1. Rep B’s calls and orders look like scattered rain — correlation near 0. Your sales head can compare both reps on the same −1 to +1 ruler without worrying that one rep counts calls in hundreds and orders in tens.
Layer 3 — Visual (SVG diagram)
Layer 4 — Terminology Table
| Term | Symbol | Plain English Meaning |
|---|---|---|
| Pearson correlation | r | Standardised measure of linear co-movement (−1 to +1) |
| Covariance | Cov(X, Y) | Raw co-movement (used inside the r formula) |
| Std dev of X | σₓ | Typical spread of X around its mean |
| Std dev of Y | σᵧ | Typical spread of Y around its mean |
| Linear relationship | — | Pattern that follows a straight line, not curves or steps |
| Perfect correlation | r = ±1 | All points fall on one straight line |
Layer 5 — Hand Calculation
Same data: x = [2, 4, 6, 8], y = [4, 8, 12, 16] — already know x̄ = 5, ȳ = 10, Cov = 10.
Step 1 — Spread of X
| xᵢ | (xᵢ − x̄) | Squared |
|---|---|---|
| 2 | −3 | 9 |
| 4 | −1 | 1 |
| 6 | +1 | 1 |
| 8 | +3 | 9 |
- Variance of X = (9 + 1 + 1 + 9) ÷ 4 = 20 ÷ 4 = 5
- σₓ = √5 ≈ 2.236
Step 2 — Spread of Y
| yᵢ | (yᵢ − ȳ) | Squared |
|---|---|---|
| 4 | −6 | 36 |
| 8 | −2 | 4 |
| 12 | +2 | 4 |
| 16 | +6 | 36 |
- Variance of Y = (36 + 4 + 4 + 36) ÷ 4 = 80 ÷ 4 = 20
- σᵧ = √20 ≈ 4.472
Step 3 — Correlation
- r = Cov(X, Y) ÷ (σₓ × σᵧ) = 10 ÷ (2.236 × 4.472) = 10 ÷ 10 = 1.0
Perfect positive linear relationship — revenue is exactly double spend at every point.
Now verify this in Python:
Layer 6 — Formula with Symbol Breakdown
Pearson correlation (population form):
\[
r = \frac{\text{Cov}(X,Y)}{\sigma_X \sigma_Y}
= \frac{\sum_{i=1}^{n}(x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum_{i=1}^{n}(x_i - \bar{x})^2}\;\sqrt{\sum_{i=1}^{n}(y_i - \bar{y})^2}}
\]
| Symbol | What it is | What it does | Why it is there |
|---|---|---|---|
| r | Correlation coefficient | Final score from −1 to +1 | Removes unit effects so pairs are comparable |
| Cov(X, Y) | Numerator core | Direction and strength of co-movement | Same idea as covariance layer |
| σₓ, σᵧ | Denominators | Each variable’s typical spread | Dividing out spread prevents “big numbers” from inflating r |
| Square roots in denominator | Combined scale factor | Normalises using both spreads at once | Equivalent to dividing Cov by product of std devs |
Layer 7 — Python Verification
import numpy as np
x = np.array([2, 4, 6, 8])
y = np.array([4, 8, 12, 16])
r = np.corrcoef(x, y)[0, 1]
print(f"Pearson r = {r:.1f}")Expected output:
Pearson r = 1.0Layer 8 — Real Dataset Application
A Pune SaaS company exports twelve months of metrics: marketing spend (₹ lakh) and new MRR (₹ lakh).
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.DataFrame({
"spend_lakh": [2, 3, 3, 4, 5, 5, 6, 7, 7, 8, 9, 10],
"new_mrr_lakh": [5, 7, 8, 10, 11, 12, 14, 15, 17, 18, 20, 22],
})
r = df["spend_lakh"].corr(df["new_mrr_lakh"])
print(f"Pearson r = {r:.3f}")
plt.figure(figsize=(6, 5))
sns.heatmap(df.corr(), annot=True, cmap="Blues", vmin=-1, vmax=1, fmt=".2f")
plt.title("Campaign metrics — correlation matrix")
plt.tight_layout()
plt.savefig("outputs/stat2_corr_heatmap.png")
plt.show()Interpretation: r ≈ 0.99 — spend and new MRR move together almost linearly. Before building a regression model, check whether impressions and clicks also correlate at 0.98; if so, keep one feature to avoid redundant inputs. Correlation does not prove spend causes MRR — seasonality or sales effort could drive both.
Layer 9 — Common Mistakes
❌ Wrong: Say “correlation proves ad spend causes revenue” because r = 0.95.
✅ Right: Say “spend and revenue move together linearly; run an experiment or causal analysis before budget decisions.”
💡 Why: Hidden factors (festive season, sales headcount) can lift both variables — classic correlation-is-not-causation trap.
❌ Wrong: Assume r = 0 means “no relationship of any kind.”
✅ Right: Check scatter plots — U-shaped or step patterns can have r ≈ 0 but still be predictable with the right model.
💡 Why: Pearson r only measures linear alignment; non-linear patterns hide from this one number.
❌ Wrong: Drop every feature pair with |r| > 0.5 automatically.
✅ Right: Drop or combine features when they measure the same thing (e.g. clicks and impressions); keep pairs that are correlated but meaningfully different for the business question.
💡 Why: Blind threshold rules remove useful signal; domain knowledge beats a magic cutoff.
Layer 10 — ML Connection
Before training a linear regression on a Flipkart-seller dataset, run df.corr() on numeric columns. If total_orders and unique_buyers show r = 0.97, keeping both inflates coefficient instability and makes feature importance hard to interpret. Drop one column or use regularisation (Ridge) so the model is not fighting two nearly identical inputs — correlation review is a five-minute step that prevents a brittle production model.
Essential commands
| Command / action | What it does |
|---|---|
np.cov(x, y, bias=True)[0, 1] | Population covariance from arrays |
np.corrcoef(x, y)[0, 1] | Pearson r from arrays |
df["a"].corr(df["b"]) | Pearson r between two columns |
df.corr() | Full correlation matrix |
sns.heatmap(df.corr()) | Visual matrix for EDA |
Practice
Do this now: Build a DataFrame with four numeric columns — e.g. spend_lakh, clicks, signups, revenue_lakh — for eight weeks of a fictional Indian e-commerce campaign. Compute population covariance between spend and revenue by hand for the first four rows, then verify with NumPy. Print the full correlation matrix and identify one pair with |r| > 0.9. Write which column you would drop before a linear model and why.
import pandas as pd
import numpy as np
# your weekly data here
# hand calc: means, deviations, products
# then df.corr() and heatmap optionalChecklist
- [ ] Can you compute covariance from deviations without skipping steps?
- [ ] Can you explain why Cov = 10 for x=[2,4,6,8], y=[4,8,12,16]?
- [ ] Can you derive r = 1.0 from Cov and standard deviations for that same data?
- [ ] Can you explain correlation on the −1 to +1 scale without claiming causation?
- [ ] Can you name when covariance is more useful than correlation (e.g. PCA)?
- [ ] Can you run
df.corr()and use the matrix to prune redundant ML features?