Foundations of Data Science 📂 Descriptive Statistics · 9 of 11 93 min read

Covariance Explained — What It Measures, Formula & Examples

Learn what covariance measures, how to calculate it step by step, and how it differs from correlation — with real-world stories, worked examples, and Python code using NumPy and Pandas.

🌐
SectionSection第 01 节

The Ice Cream & Drowning StoryIce Cream और डूबने की कहानी冰淇淋与溺水的故事

Imagine a researcher combs through 20 years of summer data and discovers something alarming: on days when ice cream sales spike, the number of drowning incidents also rises. Does ice cream cause drowning? Should we ban ice cream at beaches?

कल्पना करें कि एक researcher 20 साल के गर्मियों के data की छानबीन करता है और एक चौंकाने वाली बात पाता है: जिन दिनों ice cream की बिक्री उछलती है, उन दिनों डूबने की घटनाएँ भी बढ़ती हैं। क्या ice cream से लोग डूबते हैं? क्या beaches पर ice cream पर रोक लगानी चाहिए?

设想一位研究者翻阅了 20 年的夏季数据,发现了一件令人担忧的事:冰淇淋销量猛增的日子,溺水事件也随之增加。是冰淇淋导致溺水吗?海滩上应该禁售冰淇淋吗?

Of course not. Both are driven by a third factor — hot weather. When it's hot, people buy more ice cream and swim more, which raises drowning risk. The two variables move together, but one does not cause the other.

बिल्कुल नहीं। दोनों एक तीसरे कारण से चलते हैं — गर्म मौसम। गर्मी में लोग ज़्यादा ice cream ख़रीदते हैं और ज़्यादा तैरते हैं, जिससे डूबने का ख़तरा बढ़ता है। दोनों variables साथ चलते हैं, पर एक दूसरे का कारण नहीं।

当然不是。两者都由第三个因素驱动 —— 炎热天气。天热时,人们买更多冰淇淋,也更多去游泳,溺水风险随之上升。两个变量一起变化,但一个并不导致另一个。

💡
This Is What Covariance CapturesCovariance यही पकड़ता है这正是协方差所捕捉的

Covariance tells you whether two variables tend to increase together, decrease together, or move in opposite directions. It measures the direction of a linear relationship — but not its strength on its own. And like correlation, it says nothing about cause.

Covariance बताता है कि दो variables साथ बढ़ते हैं, साथ घटते हैं, या उल्टी दिशा में चलते हैं। यह linear रिश्ते की दिशा मापता है — पर अकेले उसकी ताक़त नहीं। और correlation की तरह, यह कारण के बारे में कुछ नहीं कहता।

协方差告诉你两个变量是倾向于一起增加、一起减少,还是反向变化。它衡量线性关系的方向 —— 但单凭它看不出强度。和相关系数一样,它也不说明因果。

Understanding covariance is the first step toward understanding correlation, PCA, and multivariate statistics. Every time a data scientist asks "do these two features move together?", they are thinking about covariance.

Covariance समझना correlation, PCA और multivariate statistics समझने की पहली सीढ़ी है। जब भी कोई data scientist पूछता है "क्या ये दो features साथ चलते हैं?", वह covariance के बारे में सोच रहा होता है।

理解协方差是理解相关系数、PCA 和多元统计的第一步。每当数据科学家问“这两个特征会一起变化吗?”,他想的就是协方差。


SectionSection第 02 节

Covariance in Pictures — Understand Before the Mathsतस्वीरों में Covariance — गणित से पहले समझें图解协方差 — 先理解,再算数

Draw a dashed line through the mean of X and the mean of Y. This splits the plot into four corners. A point in the top-right or bottom-left (both values above, or both below, their means) is a green point. A point in the other two corners is red.

X के mean और Y के mean से dashed lines खींचें। इससे plot चार कोनों में बँट जाता है। ऊपर-दाएँ या नीचे-बाएँ का point (दोनों values अपने mean से ऊपर, या दोनों नीचे) हरा है। बाक़ी दो कोनों का point लाल है।

过 X 的均值和 Y 的均值各画一条虚线,把图分成四个角。右上或左下的点(两个值都高于或都低于各自均值)是绿色点;另外两个角的点是红色点。

📊 THE FOUR-CORNER PICTUREचार कोनों वाली तस्वीर四角图
Positive, zero and negative covariance Cov > 0Cov > 0协方差 > 0 most points in the green cornersज़्यादातर points हरे कोनों में大多数点在绿色角落 Cov ≈ 0Cov ≈ 0协方差 ≈ 0 green and red cancel outहरे और लाल एक-दूसरे को काटते हैं绿与红相互抵消 Cov < 0Cov < 0协方差 < 0 most points in the red cornersज़्यादातर points लाल कोनों में大多数点在红色角落 Dashed lines = the means of X and Y. Green corners: both above or both below the mean.Dashed lines = X और Y के means. हरे कोने: दोनों mean से ऊपर या दोनों नीचे।虚线 = X 和 Y 的均值。绿色角落:两者同时高于或同时低于均值。

Covariance is the average "box" each point makes with the centre: green boxes count as positive, red boxes as negative.

Covariance हर point के केंद्र के साथ बने "box" का औसत है: हरे boxes positive गिने जाते हैं, लाल negative.

协方差就是每个点与中心围成的“方块”的平均:绿色方块记为正,红色方块记为负。

LIVELIVE互动Watch the Boxes Add Up to CovarianceBoxes को जुड़कर Covariance बनते देखें看方块如何累加成协方差

Each point draws a box to the centre. Its area is (x − x̄)(y − ȳ). Add all the boxes, divide by n − 1, and you have the covariance. Drag points into red corners and watch it fall.

हर point केंद्र तक एक box बनाता है। इसका area (x − x̄)(y − ȳ) है। सारे boxes जोड़ें, n − 1 से भाग दें, और covariance मिल जाता है। Points को लाल कोनों में खींचें और इसे गिरते देखें।

每个点与中心围成一个方块,面积为 (x − x̄)(y − ȳ)。把所有方块加起来再除以 n − 1,就是协方差。把点拖进红色角落,看它如何下降。


SectionSection第 03 节

What Covariance MeasuresCovariance क्या मापता है协方差衡量什么

Covariance measures how much two variables change together relative to their own means. For each observation, we look at how far X is from its mean and how far Y is from its mean. We multiply those two deviations and average the results.

Covariance मापता है कि दो variables अपने-अपने mean के हिसाब से साथ-साथ कितना बदलते हैं। हर observation के लिए हम देखते हैं कि X अपने mean से कितना दूर है और Y अपने mean से कितना। इन दोनों deviations को गुणा करते हैं और नतीजों का औसत लेते हैं।

协方差衡量两个变量相对于各自均值一起变化的程度。对每个观测值,看 X 离它的均值多远、Y 离它的均值多远,把这两个离差相乘,再取平均。

Positive CovPositive Cov正协方差
Cov > 0
  • X↑ when Y↑Y↑ तो X↑Y↑ 时 X↑
  • X↓ when Y↓Y↓ तो X↓Y↓ 时 X↓
  • e.g. height & weightजैसे height और weight例如身高和体重
Negative CovNegative Cov负协方差
Cov < 0
  • X↑ when Y↓Y↓ तो X↑Y↓ 时 X↑
  • X↓ when Y↑Y↑ तो X↓Y↑ 时 X↓
  • e.g. price & demandजैसे कीमत और माँग例如价格和需求
Zero CovZero Cov零协方差
Cov ≈ 0
  • No linear relationshipकोई linear रिश्ता नहीं没有线性关系
  • May still have a curveफिर भी curve हो सकता है仍可能存在曲线关系
  • e.g. shoe size & IQजैसे shoe size और IQ例如鞋码和智商
⚠️
Covariance ≠ CorrelationCovariance ≠ Correlation协方差 ≠ 相关系数

Covariance has no upper or lower bound. Its value depends on the units of X and Y, which makes it hard to compare across datasets. Correlation rescales covariance to the range [−1, +1] and is therefore easier to interpret. Always know which one you are looking at.

Covariance की कोई ऊपरी या निचली सीमा नहीं। इसकी value X और Y की units पर निर्भर करती है, इसलिए अलग datasets के बीच तुलना मुश्किल है। Correlation, covariance को [−1, +1] की range में scale करता है, इसलिए उसे समझना आसान है। हमेशा पता रखें कि आप किसे देख रहे हैं।

协方差没有上下界。它的数值取决于 X 和 Y 的单位,很难在不同数据集之间比较。相关系数把协方差缩放到 [−1, +1],因此更容易解读。一定要清楚自己看的是哪一个。


SectionSection第 04 节

The FormulaFormula公式

There are two versions of the covariance formula — one for a population and one for a sample. In data science you will almost always use the sample formula, because you are working with a subset of the data.

Covariance के formula के दो रूप हैं — एक population के लिए और एक sample के लिए। Data science में आप लगभग हमेशा sample formula इस्तेमाल करेंगे, क्योंकि आप data के एक हिस्से पर काम कर रहे होते हैं।

协方差公式有两个版本 —— 一个用于总体,一个用于样本。在数据科学中,你几乎总是用样本公式,因为你处理的只是数据的一部分。

Population CovariancePopulation Covariance总体协方差
Cov(X,Y) = Σ (xᵢ − μₓ)(yᵢ − μᵧ) / N
Divide by N (all members). Use only when you have data for the entire population, e.g. all employees in a company.
N (सारे सदस्यों) से भाग दें। सिर्फ़ तब इस्तेमाल करें जब पूरी population का data हो, जैसे किसी company के सारे employees.
除以 N(全部成员)。只有掌握整个总体的数据时才用,例如公司的全部员工。
Sample CovarianceSample Covariance样本协方差
Cov(X,Y) = Σ (xᵢ − x̄)(yᵢ − ȳ) / (n − 1)
Divide by n − 1 (Bessel's correction). Use this in practice — it gives an unbiased estimate of the population covariance.
n − 1 से भाग दें (Bessel's correction)। व्यवहार में यही इस्तेमाल करें — यह population covariance का unbiased अनुमान देता है।
除以 n − 1(贝塞尔校正)。实际中用这个 —— 它是总体协方差的无偏估计。
🎯
Why n − 1?n − 1 क्यों?为什么是 n − 1?

The sample means x̄ and ȳ are calculated from the same data, so the points sit a little closer to them than to the true population means. The deviations come out slightly too small. Dividing by n − 1 instead of n corrects this on average. This is Bessel's correction; you "use up" one degree of freedom by estimating the mean.

Sample means x̄ और ȳ उसी data से निकाले जाते हैं, इसलिए points उनके असली population means की तुलना में थोड़ा ज़्यादा पास होते हैं। Deviations थोड़े छोटे आते हैं। n की जगह n − 1 से भाग देने पर औसतन यह कमी ठीक हो जाती है। इसे Bessel's correction कहते हैं; mean का अनुमान लगाने में आप एक degree of freedom "ख़र्च" कर देते हैं।

样本均值 x̄ 和 ȳ 是用同一批数据算出来的,所以数据点离它们比离真实总体均值更近一些,离差会略微偏小。用 n − 1 代替 n 作除数,平均而言就能纠正这一点。这就是贝塞尔校正;估计均值时你“用掉”了一个自由度。

LIVELIVE互动Why n − 1? Test It on 2,000 Samplesn − 1 क्यों? 2,000 Samples पर परखें为什么是 n − 1?用 2,000 个样本检验

The population has a true covariance of 0.60. We draw 2,000 small samples, compute both versions for each, and average them. Try n = 2 and n = 50.

Population का असली covariance 0.60 है। हम 2,000 छोटे samples निकालते हैं, हर एक पर दोनों रूप निकालते हैं, और उनका औसत लेते हैं। n = 2 और n = 50 आज़माएँ।

总体的真实协方差是 0.60。我们抽取 2,000 个小样本,对每个样本计算两种版本,再取平均。试试 n = 2 和 n = 50。


SectionSection第 05 节

Step-by-Step CalculationStep-by-Step गणना分步计算

A real-world scenario: five students' hours studied (X) and exam score (Y). Is studying more associated with scoring higher?

एक असली स्थिति: पाँच छात्रों के पढ़ाई के घंटे (X) और exam score (Y)। क्या ज़्यादा पढ़ाई, ज़्यादा अंकों से जुड़ी है?

一个真实场景:五名学生的学习时长(X)和考试分数(Y)。学得多是否与考得高相关?

Studentछात्र学生Hours Studied (X)पढ़ाई के घंटे (X)学习时长(X)Exam Score (Y)Exam Score (Y)考试分数(Y)
A250
B460
C670
D885
E1095
🧮 Calculating Sample CovarianceSample Covariance निकालना计算样本协方差
Step 1
Mean of X (hours studied):
x̄ = (2 + 4 + 6 + 8 + 10) / 5 = 6.0
X (पढ़ाई के घंटे) का mean:
x̄ = (2 + 4 + 6 + 8 + 10) / 5 = 6.0
X(学习时长)的均值:
x̄ = (2 + 4 + 6 + 8 + 10) / 5 = 6.0
Step 2
Mean of Y (exam score):
ȳ = (50 + 60 + 70 + 85 + 95) / 5 = 72.0
Y (exam score) का mean:
ȳ = (50 + 60 + 70 + 85 + 95) / 5 = 72.0
Y(考试分数)的均值:
ȳ = (50 + 60 + 70 + 85 + 95) / 5 = 72.0
Step 3
Each deviation product (xᵢ − x̄)(yᵢ − ȳ):
A: (2−6)(50−72) = (−4)(−22) = 88
B: (4−6)(60−72) = (−2)(−12) = 24
C: (6−6)(70−72) = (0)(−2) = 0
D: (8−6)(85−72) = (2)(13) = 26
E: (10−6)(95−72) = (4)(23) = 92
हर deviation product (xᵢ − x̄)(yᵢ − ȳ):
A: (2−6)(50−72) = (−4)(−22) = 88
B: (4−6)(60−72) = (−2)(−12) = 24
C: (6−6)(70−72) = (0)(−2) = 0
D: (8−6)(85−72) = (2)(13) = 26
E: (10−6)(95−72) = (4)(23) = 92
每个离差乘积 (xᵢ − x̄)(yᵢ − ȳ):
A:(2−6)(50−72) = (−4)(−22) = 88
B:(4−6)(60−72) = (−2)(−12) = 24
C:(6−6)(70−72) = (0)(−2) = 0
D:(8−6)(85−72) = (2)(13) = 26
E:(10−6)(95−72) = (4)(23) = 92
Step 4
Sum the products: 88 + 24 + 0 + 26 + 92 = 230 — every box is green (or zero)
Products का जोड़: 88 + 24 + 0 + 26 + 92 = 230 — हर box हरा (या zero) है
乘积之和:88 + 24 + 0 + 26 + 92 = 230 —— 每个方块都是绿色(或为零)
Step 5
Divide by n − 1 = 4: Cov(X, Y) = 230 / 4 = 57.5
(Population version: 230 / 5 = 46.0)
n − 1 = 4 से भाग: Cov(X, Y) = 230 / 4 = 57.5
(Population रूप: 230 / 5 = 46.0)
除以 n − 1 = 4:Cov(X, Y) = 230 / 4 = 57.5
(总体版本:230 / 5 = 46.0)
✅
Result: Cov(X, Y) = 57.5नतीजा: Cov(X, Y) = 57.5结果:Cov(X, Y) = 57.5

The positive covariance confirms that students who study more hours tend to score higher — the two variables move in the same direction. The value 57.5 is in units of (hours × marks), which is hard to interpret on its own. Dividing by the two standard deviations (√10 = 3.16 hours and √332.5 = 18.2 marks) gives Pearson's r = 57.5 / (3.16 × 18.2) = 0.997.

Positive covariance पक्का करता है कि ज़्यादा पढ़ने वाले छात्र ज़्यादा अंक लाते हैं — दोनों variables एक ही दिशा में चलते हैं। 57.5 की value (घंटे × marks) की units में है, जिसे अकेले समझना मुश्किल है। दोनों standard deviations (√10 = 3.16 घंटे और √332.5 = 18.2 marks) से भाग देने पर Pearson का r = 57.5 / (3.16 × 18.2) = 0.997 मिलता है।

正协方差证实了学得越多的学生往往考得越高 —— 两个变量同向变化。57.5 的单位是(小时 × 分),单看很难解读。除以两个标准差(√10 = 3.16 小时,√332.5 = 18.2 分),得到 Pearson r = 57.5 / (3.16 × 18.2) = 0.997。


SectionSection第 06 节

Python ImplementationPython ImplementationPython 实现

Manual calculationहाथ से गणना手动计算

import numpy as np

X = [2, 4, 6, 8, 10]      # hours studied
Y = [50, 60, 70, 85, 95]  # exam scores

x_mean = np.mean(X)
y_mean = np.mean(Y)
n = len(X)

products = [(x - x_mean) * (y - y_mean) for x, y in zip(X, Y)]
print("Deviation products:", [float(p) + 0.0 for p in products])

cov_sample = sum(products) / (n - 1)
cov_population = sum(products) / n
print(f"Sample covariance (÷ n−1):   {cov_sample}")
print(f"Population covariance (÷ n): {cov_population}")
OUTPUT
Deviation products: [88.0, 24.0, 0.0, 26.0, 92.0] Sample covariance (÷ n−1): 57.5 Population covariance (÷ n): 46.0

Using NumPyNumPy से使用 NumPy

import numpy as np

X = [2, 4, 6, 8, 10]
Y = [50, 60, 70, 85, 95]

cov_matrix = np.cov(X, Y)      # ddof=1 (sample) by default
print(cov_matrix)
print(f"Var(X)    = {cov_matrix[0, 0]}")    # top-left
print(f"Var(Y)    = {cov_matrix[1, 1]}")    # bottom-right
print(f"Cov(X, Y) = {cov_matrix[0, 1]}")    # off-diagonal (same as [1, 0])

print("\nPopulation version (ddof=0):")
print(np.cov(X, Y, ddof=0))
OUTPUT
[[ 10. 57.5] [ 57.5 332.5]] Var(X) = 10.0 Var(Y) = 332.5 Cov(X, Y) = 57.5 Population version (ddof=0): [[ 8. 46.] [ 46. 266.]]
🧭
Reading the Covariance MatrixCovariance Matrix पढ़ना如何读协方差矩阵

np.cov(X, Y) returns a 2 × 2 matrix. The diagonal holds the variances: Var(X) = 10 (top-left) and Var(Y) = 332.5 (bottom-right). The off-diagonal cells hold the covariance, 57.5 — twice, because Cov(X, Y) = Cov(Y, X).

np.cov(X, Y) एक 2 × 2 matrix देता है। Diagonal में variances हैं: Var(X) = 10 (ऊपर-बाएँ) और Var(Y) = 332.5 (नीचे-दाएँ)। Off-diagonal cells में covariance 57.5 है — दो बार, क्योंकि Cov(X, Y) = Cov(Y, X)।

np.cov(X, Y) 返回一个 2 × 2 矩阵。对角线是方差:Var(X) = 10(左上)和 Var(Y) = 332.5(右下)。非对角线是协方差 57.5 —— 出现两次,因为 Cov(X, Y) = Cov(Y, X)。

Using pandaspandas से使用 pandas

import pandas as pd

df = pd.DataFrame({
    'hours': [2, 4, 6, 8, 10],
    'score': [50, 60, 70, 85, 95],
})

print(df.cov())                          # full covariance matrix (ddof=1)
print(df['hours'].cov(df['score']))      # single pair
print(round(df['hours'].corr(df['score']), 4))   # correlation for comparison
OUTPUT
hours score hours 10.0 57.5 score 57.5 332.5 57.5 0.9972
⚠️
Know Each Library's Defaultहर Library का Default जानें了解各个库的默认设置

np.cov() and pandas .cov() both divide by n − 1 by default (sample covariance). np.var() and np.std(), however, divide by n by default (ddof=0). For the population covariance, pass ddof=0: np.cov(X, Y, ddof=0) gives 46.0.

np.cov() और pandas .cov() दोनों default में n − 1 से भाग देते हैं (sample covariance)। लेकिन np.var() और np.std() default में n से भाग देते हैं (ddof=0)। Population covariance के लिए ddof=0 दें: np.cov(X, Y, ddof=0) 46.0 देता है।

np.cov() 和 pandas 的 .cov() 默认都除以 n − 1(样本协方差)。而 np.var() 和 np.std() 默认除以 n(ddof=0)。要计算总体协方差,传入 ddof=0:np.cov(X, Y, ddof=0) 得到 46.0。


SectionSection第 07 节

Why Covariance Depends on UnitsCovariance Units पर क्यों निर्भर है为什么协方差依赖单位

Covariance multiplies an X-deviation by a Y-deviation, so its unit is "X-unit × Y-unit". Measure hours in minutes and every X-deviation becomes 60 times bigger — so does the covariance. The relationship itself has not changed at all.

Covariance एक X-deviation को Y-deviation से गुणा करता है, इसलिए उसकी unit "X-unit × Y-unit" होती है। घंटों को मिनट में मापें तो हर X-deviation 60 गुना बड़ा हो जाता है — और covariance भी। रिश्ता ज़रा भी नहीं बदला।

协方差是 X 离差乘以 Y 离差,所以它的单位是“X 单位 × Y 单位”。把小时换成分钟,每个 X 离差变成 60 倍 —— 协方差也一样。而关系本身完全没变。

import numpy as np

hours = np.array([2, 4, 6, 8, 10])
score = np.array([50, 60, 70, 85, 95])

def cov(a, b):
    return np.cov(a, b)[0, 1]

def corr(a, b):
    return np.corrcoef(a, b)[0, 1]

print(f"hours  vs marks:     cov = {cov(hours, score):8.1f}   r = {corr(hours, score):.4f}")
print(f"minutes vs marks:    cov = {cov(hours * 60, score):8.1f}   r = {corr(hours * 60, score):.4f}")
print(f"hours  vs fraction:  cov = {cov(hours, score / 100):8.3f}   r = {corr(hours, score / 100):.4f}")
print(f"hours+1 vs marks+5:  cov = {cov(hours + 1, score + 5):8.1f}   r = {corr(hours + 1, score + 5):.4f}")
OUTPUT
hours vs marks: cov = 57.5 r = 0.9972 minutes vs marks: cov = 3450.0 r = 0.9972 hours vs fraction: cov = 0.575 r = 0.9972 hours+1 vs marks+5: cov = 57.5 r = 0.9972
LIVELIVE互动Same Data, Different Unitsएक Data, अलग Units同样的数据,不同的单位

Switch the units of X and Y, or add a constant to both. The scatter plot looks identical every time — watch which number changes.

X और Y की units बदलें, या दोनों में एक constant जोड़ें। Scatter plot हर बार एक जैसा दिखता है — देखें कौन सी संख्या बदलती है।

切换 X 和 Y 的单位,或给两者都加一个常数。散点图每次看起来都一样 —— 看看哪个数字变了。

X
Y


SectionSection第 08 节

The Covariance MatrixCovariance Matrix协方差矩阵

With many variables, we put every pairwise covariance into a covariance matrix. The diagonal holds each variable's variance; every other cell is the covariance of a pair. The matrix is symmetric. It is the starting point for correlation matrices, PCA, multivariate normal distributions and many ML methods.

बहुत से variables हों तो हर जोड़े का covariance एक covariance matrix में रखते हैं। Diagonal में हर variable का variance होता है; बाक़ी हर cell किसी जोड़े का covariance है। Matrix symmetric होती है। यही correlation matrices, PCA, multivariate normal distributions और कई ML methods की शुरुआत है।

变量很多时,把每一对的协方差放进协方差矩阵。对角线是各变量的方差,其余每个单元格是一对变量的协方差。矩阵是对称的。它是相关矩阵、PCA、多元正态分布和许多机器学习方法的起点。

import numpy as np
import pandas as pd

rng = np.random.default_rng(7)
n = 200
height = rng.normal(170, 8, n)                           # cm
weight = 0.9 * (height - 170) + rng.normal(70, 6, n)     # kg
shoe   = 0.25 * (height - 170) + rng.normal(42, 1.2, n)  # EU size
df = pd.DataFrame({'height_cm': height, 'weight_kg': weight, 'shoe_eu': shoe})

C = df.cov()
print("Covariance matrix:")
print(C.round(2))

# Correlation = covariance divided by the two standard deviations
sd = np.sqrt(np.diag(C))
R = C / np.outer(sd, sd)
print("\nCorrelation matrix (from covariance):")
print(R.round(3))
print("\nSame as df.corr()?", np.allclose(R, df.corr()))
OUTPUT
Covariance matrix: height_cm weight_kg shoe_eu height_cm 48.94 44.76 12.38 weight_kg 44.76 74.98 10.49 shoe_eu 12.38 10.49 4.34 Correlation matrix (from covariance): height_cm weight_kg shoe_eu height_cm 1.000 0.739 0.849 weight_kg 0.739 1.000 0.582 shoe_eu 0.849 0.582 1.000 Same as df.corr()? True

Dividing each covariance by the two standard deviations turns the covariance matrix into the correlation matrix — exactly what df.corr() returns. Height and shoe size have the strongest correlation (0.85) even though their covariance (12.38) is much smaller than height and weight (44.76), because shoe sizes vary over a much smaller range.

हर covariance को दोनों standard deviations से भाग देने पर covariance matrix, correlation matrix बन जाती है — ठीक वही जो df.corr() देता है। Height और shoe size का correlation सबसे मज़बूत (0.85) है, जबकि उनका covariance (12.38), height और weight के (44.76) से बहुत छोटा है — क्योंकि shoe sizes बहुत छोटी range में बदलते हैं।

把每个协方差除以两个标准差,协方差矩阵就变成了相关矩阵 —— 正是 df.corr() 返回的结果。身高与鞋码的相关最强(0.85),尽管它们的协方差(12.38)远小于身高与体重(44.76),因为鞋码的变化范围小得多。

LIVELIVE互动The Covariance Matrix as a Shape — with PCA Axesआकार के रूप में Covariance Matrix — PCA Axes के साथ把协方差矩阵看成形状 — 附 PCA 轴

Set the spread of X, the spread of Y and their correlation. The ellipse is drawn from the covariance matrix; the arrows are its eigenvectors — the principal components used in PCA.

X का फैलाव, Y का फैलाव और उनका correlation चुनें। Ellipse covariance matrix से बनता है; arrows उसके eigenvectors हैं — PCA में इस्तेमाल होने वाले principal components.

设置 X 的离散程度、Y 的离散程度以及它们的相关。椭圆由协方差矩阵画出;箭头是它的特征向量 —— 也就是 PCA 中的主成分。


SectionSection第 09 节

Covariance vs Correlation — ComparisonCovariance vs Correlation — तुलना协方差 vs 相关系数 — 对比

Covariance and correlation are closely related. Correlation is simply the standardised version of covariance — you divide by the standard deviations of both variables to remove the effect of units.

Covariance और correlation आपस में बहुत जुड़े हैं। Correlation बस covariance का standardised रूप है — units का असर हटाने के लिए दोनों variables के standard deviations से भाग देते हैं।

协方差和相关系数密切相关。相关系数就是协方差的标准化版本 —— 除以两个变量的标准差,消除单位的影响。

Propertyगुण特性CovarianceCovariance协方差CorrelationCorrelation相关系数
RangeRange取值范围(−∞, +∞)[−1, +1]
Unit-dependent?Units पर निर्भर?依赖单位?Yesहाँ是Noनहीं否
Interpretable magnitude?आकार समझ आता है?大小好解读?Hardमुश्किल难Easyआसान易
Detects directionदिशा बताता है能判断方向Yesहाँ是Yesहाँ是
Changes if you add a constant?Constant जोड़ने पर बदलता है?加常数会变吗?Noनहीं否Noनहीं否
Used in PCA?PCA में इस्तेमाल?用于 PCA?Yes (same units)हाँ (एक जैसी units)是(单位相同时)Yes, when features have different unitsहाँ, जब features की units अलग हों是(特征单位不同时)
FormulaFormula公式Σ(xᵢ−x̄)(yᵢ−ȳ) / (n−1)Cov(X,Y) / (sₓ · sᵧ)
Symmetric?Symmetric?对称?Yesहाँ是Yesहाँ是
📐
The Relationship Formulaरिश्ते का Formula两者关系的公式

r(X, Y) = Cov(X, Y) / (sₓ × sᵧ)
Pearson's r is covariance divided by the product of both standard deviations (use the same n − 1 or n in all three). This scales the value to [−1, +1] regardless of the original units. In our example: 57.5 / (3.162 × 18.235) = 0.997.

r(X, Y) = Cov(X, Y) / (sₓ × sᵧ)
Pearson का r, covariance को दोनों standard deviations के गुणनफल से भाग देने पर मिलता है (तीनों में एक ही n − 1 या n लें)। इससे value मूल units कुछ भी हों, [−1, +1] में आ जाती है। हमारे उदाहरण में: 57.5 / (3.162 × 18.235) = 0.997.

r(X, Y) = Cov(X, Y) / (sₓ × sᵧ)
Pearson r 等于协方差除以两个标准差的乘积(三者要统一用 n − 1 或 n)。这样无论原始单位如何,数值都被缩放到 [−1, +1]。在我们的例子中:57.5 / (3.162 × 18.235) = 0.997。


SectionSection第 10 节

Zero Covariance Does Not Mean "No Relationship"Zero Covariance का मतलब "कोई रिश्ता नहीं" नहीं零协方差不等于“没有关系”

Covariance only measures the straight-line part of a relationship. A perfect curve can give zero covariance — but only when the positive and negative boxes happen to cancel out.

Covariance रिश्ते का सिर्फ़ सीधी-line वाला हिस्सा मापता है। एक perfect curve भी zero covariance दे सकता है — पर सिर्फ़ तब जब positive और negative boxes संयोग से एक-दूसरे को काट दें।

协方差只衡量关系中的直线部分。完美的曲线也可能让协方差为零 —— 但前提是正负方块恰好相互抵消。

import numpy as np

x = np.arange(-5, 6)          # -5 ... 5, symmetric around 0
y = x ** 2                    # perfect curve
print("x from -5 to 5:  cov =", round(np.cov(x, y)[0, 1], 2))

x2 = np.arange(0, 11)         # 0 ... 10, NOT symmetric around 0
y2 = x2 ** 2
print("x from 0 to 10:  cov =", round(np.cov(x2, y2)[0, 1], 2))
OUTPUT
x from -5 to 5: cov = 0.0 x from 0 to 10: cov = 110.0
LIVELIVE互动A Perfect Curve with Zero CovarianceZero Covariance वाला एक Perfect Curve协方差为零的完美曲线

y = x² exactly. Slide the window of x values. Centred on zero, the green and red boxes cancel and covariance is 0. Move it, and covariance appears.

y ठीक x² है। x values की खिड़की खिसकाएँ। Zero पर केंद्रित होने पर हरे और लाल boxes कट जाते हैं और covariance 0 है। खिसकाएँ, और covariance आ जाता है।

y 恰好等于 x²。滑动 x 的取值窗口。以零为中心时,绿色和红色方块相互抵消,协方差为 0。移动窗口,协方差就出现了。


SectionSection第 11 节

Golden RulesGolden Rules黄金法则

🎯 Covariance — Key RulesCovariance — मुख्य नियम协方差 — 关键规则
1
The sign tells direction, not strength. Positive = the variables move together; negative = they move oppositely. The raw number says nothing about how strongly they are related.
Sign दिशा बताता है, ताक़त नहीं। Positive = variables साथ चलते हैं; negative = उल्टे चलते हैं। कच्ची संख्या यह नहीं बताती कि रिश्ता कितना मज़बूत है।
符号表示方向,不表示强度。正 = 两个变量同向变化;负 = 反向变化。原始数值并不能说明关系有多强。
2
Use ddof=1 for sample data. np.cov() and pandas .cov() do this by default; be explicit when you compute by hand or use other functions (for example np.var and np.std default to ddof=0).
Sample data के लिए ddof=1 इस्तेमाल करें। np.cov() और pandas .cov() default में यही करते हैं; हाथ से या दूसरे functions से निकालते समय साफ़ लिखें (जैसे np.var और np.std का default ddof=0 है)।
样本数据用 ddof=1。np.cov() 和 pandas 的 .cov() 默认如此;手算或用其他函数时要写明(例如 np.var 和 np.std 默认 ddof=0)。
3
Covariance depends on units. Change hours to minutes and covariance grows 60×. Adding a constant changes nothing. Never compare covariances across datasets or units — use correlation.
Covariance units पर निर्भर है। घंटों को मिनट करें तो covariance 60 गुना हो जाता है। Constant जोड़ने से कुछ नहीं बदलता। अलग datasets या units के covariances की तुलना कभी न करें — correlation लें।
协方差依赖单位。小时换成分钟,协方差变成 60 倍;加一个常数则毫无变化。不要跨数据集或跨单位比较协方差 —— 用相关系数。
4
Zero covariance ≠ no relationship. y = x² has zero covariance when x is symmetric around 0, yet y depends perfectly on x. Covariance only captures linear association — always plot the data.
Zero covariance ≠ कोई रिश्ता नहीं। जब x, 0 के आसपास symmetric हो तो y = x² का covariance zero होता है, फिर भी y पूरी तरह x पर निर्भर है। Covariance सिर्फ़ linear रिश्ता पकड़ता है — हमेशा data plot करें।
零协方差 ≠ 没有关系。当 x 关于 0 对称时,y = x² 的协方差为零,但 y 完全由 x 决定。协方差只捕捉线性关联 —— 一定要画图。
5
Covariance is symmetric. Cov(X, Y) = Cov(Y, X), and Cov(X, X) is simply the variance of X — which is why variances sit on the diagonal of the covariance matrix.
Covariance symmetric है। Cov(X, Y) = Cov(Y, X), और Cov(X, X) बस X का variance है — इसीलिए variances covariance matrix के diagonal पर होते हैं।
协方差是对称的。Cov(X, Y) = Cov(Y, X),而 Cov(X, X) 就是 X 的方差 —— 所以方差位于协方差矩阵的对角线上。
6
Covariance ≠ causation. A strong covariance (or correlation) never proves that one variable causes the other. Look for confounders, like the hot weather behind ice cream sales and drownings.
Covariance ≠ causation. मज़बूत covariance (या correlation) कभी साबित नहीं करता कि एक variable दूसरे का कारण है। Confounders खोजें, जैसे ice cream की बिक्री और डूबने के पीछे गर्म मौसम।
协方差 ≠ 因果。再强的协方差(或相关)也不能证明一个变量导致另一个。要寻找混杂变量,比如冰淇淋销量和溺水背后的炎热天气。