Rana Maninder Singh
Lesson 3 of 5Statistics for AI & ML

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

ResourceLink
GlossaryStatistics glossary
PreviousFoundations
NextInferential stats
PrerequisitesFoundations
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.

Statistics for data science cheat sheet
Statistics for data science cheat sheet

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)

Positive covariance — both rise together Low X High X Low Y High Y

Layer 4 — Terminology Table

TermSymbolPlain English Meaning
CovarianceCov(X, Y)Average of “how far X is from its centre” times “how far Y is from its centre”
Variable XXFirst numeric column you are comparing (e.g. ad spend in ₹ lakh)
Variable YYSecond numeric column (e.g. revenue in ₹ lakh)
Mean of Xx̄Balancing point of all X values
Mean of YȳBalancing point of all Y values
Deviationxᵢ − x̄How far one X observation sits from its average
Sample sizenNumber 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

Step 2 — Deviations and products

ixᵢyᵢ(xᵢ − x̄)(yᵢ − ȳ)Product
1242 − 5 = −34 − 10 = −6(−3)(−6) = 18
2484 − 5 = −18 − 10 = −2(−1)(−2) = 2
36126 − 5 = +112 − 10 = +2(+1)(+2) = 2
48168 − 5 = +316 − 10 = +6(+3)(+6) = 18

Step 3 — Sum and divide by n

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})

\]

SymbolWhat it isWhat it doesWhy it is there
nCount of pairsDivides the sum into an averageTurns total co-movement into one summary number
xᵢ, yᵢOne paired observationThe actual spend and revenue for week iGrounds the formula in real rows
x̄, ȳMeans of X and YReference “typical” level for each columnDeviations measure movement relative to normal
(xᵢ − x̄)(yᵢ − ȳ)Product of deviationsPositive when both above or both below mean; negative when one above, one belowCaptures direction of joint movement
ΣSumAdds co-movement across all weeksOne 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.0

Layer 8 — Real Dataset Application

A Bengaluru D2C brand tracks weekly Instagram ad spend (₹ lakh) and website revenue (₹ lakh) for six weeks:

WeekAd spendRevenue
1312
2518
3415
4724
5621
6828
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)

Pearson r scale −1 0 +1 Perfect negative No linear trend Perfect positive Our hand-calc data: r = 1.0

Layer 4 — Terminology Table

TermSymbolPlain English Meaning
Pearson correlationrStandardised measure of linear co-movement (−1 to +1)
CovarianceCov(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 correlationr = ±1All 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−39
4−11
6+11
8+39

Step 2 — Spread of Y

yᵢ(yᵢ − ȳ)Squared
4−636
8−24
12+24
16+636

Step 3 — Correlation

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}}

\]

SymbolWhat it isWhat it doesWhy it is there
rCorrelation coefficientFinal score from −1 to +1Removes unit effects so pairs are comparable
Cov(X, Y)Numerator coreDirection and strength of co-movementSame idea as covariance layer
σₓ, σᵧDenominatorsEach variable’s typical spreadDividing out spread prevents “big numbers” from inflating r
Square roots in denominatorCombined scale factorNormalises using both spreads at onceEquivalent 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.0

Layer 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 / actionWhat 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 optional

Checklist

  • [ ] 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?