Foundations of Data Science 📂 Descriptive Statistics · 7 of 11 167 min read

What is Correlation

Learn what correlation means in statistics, how to calculate Pearson and Spearman coefficients, avoid the causation trap, and use correlation in Python with NumPy and Pandas.

🌐
SectionSection第 01 节

The Story That Explains Correlationवह कहानी जो Correlation समझाती है一个讲清相关性的故事

A city council notices that on days when more ice cream is sold, more people drown. A worried councillor proposes banning ice cream to save lives.

एक city council देखती है कि जिन दिनों ज़्यादा ice cream बिकती है, उन दिनों ज़्यादा लोग डूबते हैं। एक चिंतित councillor जान बचाने के लिए ice cream पर रोक लगाने का प्रस्ताव रखता है।

市议会发现:冰淇淋卖得多的日子,溺水的人也多。一位忧心忡忡的议员提议禁售冰淇淋来挽救生命。

⚠️
Wait — That Cannot Be Rightरुकिए — यह सही नहीं हो सकता等等 —— 这不对吧

Ice cream does not cause drowning. Both rise together because of a hidden third variable — hot weather. On hot days people buy more ice cream and swim more, and more swimming means more drowning risk. Ice cream and drowning are correlated, but neither causes the other. This is one of the most important lessons in statistics: correlation does not imply causation.

Ice cream डूबने का कारण नहीं है। दोनों एक छिपे हुए तीसरे variable — गर्म मौसम — की वजह से साथ बढ़ते हैं। गर्म दिनों में लोग ज़्यादा ice cream ख़रीदते हैं और ज़्यादा तैरते हैं, और ज़्यादा तैरने से डूबने का ख़तरा बढ़ता है। Ice cream और डूबना correlated हैं, पर कोई दूसरे का कारण नहीं। यह statistics के सबसे ज़रूरी सबकों में से एक है: correlation का मतलब causation नहीं।

冰淇淋不会导致溺水。两者一起上升,是因为一个隐藏的第三变量 —— 炎热天气。天热时,人们买更多冰淇淋,也更多去游泳,游泳多了溺水风险就大。冰淇淋和溺水是相关的,但谁也不是谁的原因。这是统计学最重要的教训之一:相关不等于因果。

Correlation is a number that measures how strongly two variables move together. Knowing what it shows — and what it cannot show — is a core data-science skill.

Correlation एक संख्या है जो मापती है कि दो variables कितनी मज़बूती से साथ चलते हैं। यह क्या दिखाता है — और क्या नहीं दिखा सकता — यह जानना data science का एक मुख्य कौशल है।

相关系数是一个数字,衡量两个变量一起变化的紧密程度。知道它能说明什么、不能说明什么,是数据科学的核心技能。


SectionSection第 02 节

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

📊 WHAT DIFFERENT VALUES OF r LOOK LIKEr की अलग-अलग values कैसी दिखती हैं不同 r 值长什么样
What different values of r look like r = -1 r = -0.8 r = -0.4 r = 0 r = 0.4 r = 0.8 r = +1 strong negative ← → none ← → strong positiveमज़बूत negative ← → कोई नहीं ← → मज़बूत positive强负相关 ← → 无相关 ← → 强正相关

Each panel has 40 points. The closer r is to ±1, the more tightly the points hug a straight line. At r = 0.4 the trend is already hard to see by eye.

हर panel में 40 points हैं। r जितना ±1 के पास, points उतना ही एक सीधी line से चिपके रहते हैं। r = 0.4 पर trend आँख से देखना पहले ही मुश्किल है।

每个小图有 40 个点。r 越接近 ±1,点越紧贴一条直线。r = 0.4 时,肉眼已经很难看出趋势。

Where does r come from? Draw a line through the mean of x and the mean of y. Every point then makes a box with the centre. Points in the top-right or bottom-left give a positive box (green); points in the other two corners give a negative box (red). r is the total of these boxes, scaled so it always lands between −1 and +1.

r आता कहाँ से है? x के mean और y के mean से lines खींचें। हर point केंद्र के साथ एक box बनाता है। ऊपर-दाएँ या नीचे-बाएँ के points positive box (हरा) देते हैं; बाक़ी दो कोनों के points negative box (लाल)। r इन boxes का कुल जोड़ है, scale किया हुआ ताकि हमेशा −1 और +1 के बीच रहे।

r 是从哪来的?过 x 的均值和 y 的均值各画一条线。每个点都和中心围成一个方块。右上或左下的点构成正方块(绿色);另外两个角的点构成负方块(红色)。r 就是这些方块的总和,经过缩放后始终落在 −1 到 +1 之间。

LIVELIVE互动The Quadrant Picture — Drag Points and Watch rQuadrant तस्वीर — Points खींचें और r देखें象限图 — 拖动点,观察 r

Start with the five students from the worked example below. Drag a point into a red corner and watch r fall. Add a far-away point and compare Pearson with Spearman.

नीचे के उदाहरण वाले पाँच छात्रों से शुरू करें। किसी point को लाल कोने में खींचें और r को गिरते देखें। एक दूर का point जोड़ें और Pearson की Spearman से तुलना करें।

从下面例题中的五名学生开始。把一个点拖进红色角落,看 r 如何下降。再添加一个远处的点,比较 Pearson 和 Spearman。


SectionSection第 03 节

What Is Correlation?Correlation क्या है?什么是相关性?

Correlation measures the strength and direction of the relationship between two numerical variables. Pearson's r measures the straight-line part of that relationship: when one variable goes up, does the other tend to go up or down — and how consistently?

Correlation दो numerical variables के रिश्ते की ताक़त और दिशा मापता है। Pearson का r उस रिश्ते का सीधी-line वाला हिस्सा मापता है: जब एक variable बढ़ता है, तो क्या दूसरा बढ़ता या घटता है — और कितनी लगातार?

相关性衡量两个数值变量之间关系的强度和方向。Pearson r 衡量其中的直线部分:一个变量上升时,另一个倾向于上升还是下降 —— 有多一致?

PositivePositive正相关
↑↑
  • Both tend to rise togetherदोनों साथ बढ़ते हैं两者倾向于一起上升
  • …and fall together…और साथ घटते हैं…也一起下降
  • e.g. arm span and heightजैसे arm span और height例如臂展和身高
No linear correlationकोई linear correlation नहीं无线性相关
→ ?
  • No straight-line trendकोई सीधी-line trend नहीं没有直线趋势
  • Not the same as "unrelated" — a U-shape gives r ≈ 0"बिना रिश्ते" जैसा नहीं — U-shape भी r ≈ 0 देता है不等于“没关系” —— U 形关系的 r 也约等于 0
  • e.g. shoe size and IQ in adultsजैसे वयस्कों में shoe size और IQ例如成年人的鞋码和智商
NegativeNegative负相关
↑↓
  • One rises, the other fallsएक बढ़ता है, दूसरा घटता है一个升,另一个降
  • An inverse relationshipउल्टा रिश्ता反向关系
  • e.g. car age and resale valueजैसे गाड़ी की उम्र और resale value例如车龄和二手车价

SectionSection第 04 节

The Correlation Coefficient (r)Correlation Coefficient (r)相关系数 r

The Pearson correlation coefficient, written r, is the most common measure. It is always between −1 and +1.

Pearson correlation coefficient, जिसे r लिखते हैं, सबसे आम माप है। यह हमेशा −1 और +1 के बीच होता है।

Pearson 相关系数记作 r,是最常用的度量,永远在 −1 到 +1 之间。

Pearson r
r = Σ[(x−x̄)(y−ȳ)] / √[Σ(x−x̄)² × Σ(y−ȳ)²]
Top: the sum of the quadrant boxes. Bottom: scales the answer so it lands between −1 and +1, whatever the units.
ऊपर: quadrant boxes का जोड़। नीचे: जवाब को scale करता है ताकि units कुछ भी हों, यह −1 और +1 के बीच आए।
分子:象限方块之和。分母:缩放结果,使其无论单位如何都落在 −1 到 +1 之间。
r valuer valuer 值Strength (rule of thumb)ताक़त (अंगूठा-नियम)强度(经验法则)Directionदिशा方向Exampleउदाहरण例子
+1.0PerfectPerfect完全PositivePositive正Celsius and FahrenheitCelsius और Fahrenheit摄氏度和华氏度
+0.7 to +0.9Strongमज़बूत强PositivePositive正Arm span and heightArm span और height臂展和身高
+0.4 to +0.6Moderateमध्यम中等PositivePositive正Height and weight of adultsवयस्कों की height और weight成年人的身高和体重
+0.1 to +0.3Weakकमज़ोर弱PositivePositive正Sleep and productivityनींद और productivity睡眠和效率
0.0None (linear)कोई नहीं (linear)无(线性)—Shoe size and IQ (adults)Shoe size और IQ (वयस्क)鞋码和智商(成年人)
−0.1 to −0.3Weakकमज़ोर弱NegativeNegative负Stress and sleep qualityतनाव और नींद की गुणवत्ता压力和睡眠质量
−0.4 to −0.6Moderateमध्यम中等NegativeNegative负Price and demandकीमत और माँग价格和需求
−0.7 to −0.9Strongमज़बूत强NegativeNegative负Car age and resale valueगाड़ी की उम्र और resale value车龄和二手价
−1.0PerfectPerfect完全NegativeNegative负Km driven and km left on a fixed tripतय यात्रा में चले km और बचे km固定行程中已行驶与剩余的公里数

The cut-offs are rules of thumb, and real values change from study to study. A "weak" r can still matter in medicine or finance; a "strong" r can still be useless if the relationship is not causal.

ये सीमाएँ अंगूठा-नियम हैं, और असली values हर study में बदलती हैं। "कमज़ोर" r भी medicine या finance में मायने रख सकता है; "मज़बूत" r भी बेकार हो सकता है अगर रिश्ता causal न हो।

这些分界只是经验法则,真实数值因研究而异。“弱”的 r 在医学或金融中仍可能很重要;“强”的 r 如果不是因果关系,也可能毫无用处。

📐
The Sign Gives Direction, the Size Gives StrengthSign दिशा बताता है, आकार ताक़त符号表示方向,大小表示强度

r = −0.85 is a stronger relationship than r = +0.40. The minus sign only means the variables move in opposite directions. Use the absolute value |r| to judge strength and the sign to judge direction.

r = −0.85, r = +0.40 से ज़्यादा मज़बूत रिश्ता है। Minus sign का मतलब बस इतना है कि variables उल्टी दिशा में चलते हैं। ताक़त के लिए absolute value |r| और दिशा के लिए sign देखें।

r = −0.85 比 r = +0.40 的关系更强。负号只表示两个变量反向变化。用绝对值 |r| 判断强度,用符号判断方向。

LIVELIVE互动Guess the CorrelationCorrelation का अंदाज़ा लगाएँ猜猜相关系数

Train your eye. Look at 60 points, set your guess, then check. Try at least five plots.

अपनी आँख को train करें। 60 points देखें, अपना अंदाज़ा लगाएँ, फिर जाँचें। कम से कम पाँच plots आज़माएँ।

训练你的眼力。看 60 个点,给出你的猜测,然后检查。至少试五张图。


SectionSection第 05 节

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

A teacher records study hours and exam scores for 5 students:

एक teacher 5 छात्रों के study hours और exam scores लिखता है:

老师记录了 5 名学生的学习时长和考试分数:

Studentछात्र学生Study hours (x)Study hours (x)学习时长(x)Exam score (y)Exam score (y)考试分数(y)
Alice250
Bob460
Carol672
Dan880
Eve1095
🧮 Calculating Pearson rPearson r निकालना计算 Pearson r
Step 1
Means: x̄ = 30 / 5 = 6, ȳ = 357 / 5 = 71.4
Means: x̄ = 30 / 5 = 6, ȳ = 357 / 5 = 71.4
均值:x̄ = 30 / 5 = 6,ȳ = 357 / 5 = 71.4
Step 2
Deviations and their products (the quadrant boxes):
Alice: −4 × −21.4 = 85.6
Bob: −2 × −11.4 = 22.8
Carol: 0 × 0.6 = 0
Dan: 2 × 8.6 = 17.2
Eve: 4 × 23.6 = 94.4
Deviations और उनके products (quadrant boxes):
Alice: −4 × −21.4 = 85.6
Bob: −2 × −11.4 = 22.8
Carol: 0 × 0.6 = 0
Dan: 2 × 8.6 = 17.2
Eve: 4 × 23.6 = 94.4
离差及其乘积(象限方块):
Alice:−4 × −21.4 = 85.6
Bob:−2 × −11.4 = 22.8
Carol:0 × 0.6 = 0
Dan:2 × 8.6 = 17.2
Eve:4 × 23.6 = 94.4
Step 3
Σ(x−x̄)(y−ȳ) = 85.6 + 22.8 + 0 + 17.2 + 94.4 = 220 — all boxes are green
Σ(x−x̄)(y−ȳ) = 85.6 + 22.8 + 0 + 17.2 + 94.4 = 220 — सारे boxes हरे
Σ(x−x̄)(y−ȳ) = 85.6 + 22.8 + 0 + 17.2 + 94.4 = 220 —— 全是绿色方块
Step 4
Σ(x−x̄)² = 16 + 4 + 0 + 4 + 16 = 40
Σ(y−ȳ)² = 457.96 + 129.96 + 0.36 + 73.96 + 556.96 = 1219.2
Σ(x−x̄)² = 16 + 4 + 0 + 4 + 16 = 40
Σ(y−ȳ)² = 457.96 + 129.96 + 0.36 + 73.96 + 556.96 = 1219.2
Σ(x−x̄)² = 16 + 4 + 0 + 4 + 16 = 40
Σ(y−ȳ)² = 457.96 + 129.96 + 0.36 + 73.96 + 556.96 = 1219.2
Step 5
r = 220 / √(40 × 1219.2) = 220 / √48768 = 220 / 220.83 = 0.996
r = 220 / √(40 × 1219.2) = 220 / √48768 = 220 / 220.83 = 0.996
r = 220 / √(40 × 1219.2) = 220 / √48768 = 220 / 220.83 = 0.996
✅
Interpretationमतलब解读

r = 0.996 — an almost perfect positive linear relationship in these five students. The best-fit line rises 5.5 marks per hour (about 11 marks per extra 2 hours). Two cautions: five students is a tiny sample, and this r says nothing about why — keen students may both study more and score higher for other reasons.

r = 0.996 — इन पाँच छात्रों में लगभग perfect positive linear रिश्ता। Best-fit line हर घंटे 5.5 marks बढ़ती है (हर 2 extra घंटे में लगभग 11 marks)। दो सावधानियाँ: पाँच छात्र बहुत छोटा sample है, और यह r क्यों के बारे में कुछ नहीं कहता — मेहनती छात्र दूसरे कारणों से भी ज़्यादा पढ़ सकते हैं और ज़्यादा अंक ला सकते हैं।

r = 0.996 —— 这五名学生几乎呈完美的正线性关系。最佳拟合线每小时上升 5.5 分(每多学 2 小时约多 11 分)。两点提醒:五个学生样本太小;而且 r 无法说明原因 —— 用功的学生可能出于其他原因既学得多又考得好。


SectionSection第 06 节

Python ImplementationPython ImplementationPython 实现

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

import math

x = [2, 4, 6, 8, 10]       # study hours
y = [50, 60, 72, 80, 95]   # exam scores

n = len(x)
x_mean = sum(x) / n
y_mean = sum(y) / n

numerator   = sum((xi - x_mean) * (yi - y_mean) for xi, yi in zip(x, y))
denom_x     = sum((xi - x_mean) ** 2 for xi in x)
denom_y     = sum((yi - y_mean) ** 2 for yi in y)
denominator = math.sqrt(denom_x * denom_y)

r = numerator / denominator
print(f"Sum of products: {numerator:.1f}")
print(f"Sum of squares:  x = {denom_x:.1f}, y = {denom_y:.1f}")
print(f"Pearson r: {r:.4f}")
OUTPUT
Sum of products: 220.0 Sum of squares: x = 40.0, y = 1219.2 Pearson r: 0.9962

Using NumPyNumPy से使用 NumPy

import numpy as np

x = [2, 4, 6, 8, 10]
y = [50, 60, 72, 80, 95]

# np.corrcoef returns a correlation matrix
corr_matrix = np.corrcoef(x, y)
r = corr_matrix[0, 1]   # [0,0] and [1,1] are always 1.0 (self-correlation)

print(f"Pearson r: {r:.4f}")
print("Full correlation matrix:")
print(np.round(corr_matrix, 4))
OUTPUT
Pearson r: 0.9962 Full correlation matrix: [[1. 0.9962] [0.9962 1. ]]

Using pandas on a DataFrameDataFrame पर pandas से在 DataFrame 上使用 pandas

import pandas as pd

df = pd.DataFrame({
    'study_hours':   [2, 4, 6, 8, 10, 3, 7, 5, 9, 1],
    'exam_score':    [50, 60, 72, 80, 95, 55, 78, 65, 88, 40],
    'sleep_hours':   [8, 7, 7, 6, 5, 8, 6, 7, 5, 9],
    'anxiety_level': [3, 4, 4, 6, 7, 3, 5, 4, 8, 2],
})

r = df['study_hours'].corr(df['exam_score'])
print(f"Study hours vs exam score: r = {r:.4f}")

print("Full correlation matrix:")
print(df.corr().round(3))
OUTPUT
Study hours vs exam score: r = 0.9963 Full correlation matrix: study_hours exam_score sleep_hours anxiety_level study_hours 1.000 0.996 -0.976 0.948 exam_score 0.996 1.000 -0.979 0.941 sleep_hours -0.976 -0.979 1.000 -0.970 anxiety_level 0.948 0.941 -0.970 1.000

With 10 students instead of 5, r is 0.9963. Notice how strongly sleep and anxiety are linked to study hours in this tiny made-up table — real data is rarely this tidy.

5 की जगह 10 छात्रों के साथ r = 0.9963 है। ध्यान दें कि इस छोटी बनाई हुई table में नींद और anxiety, study hours से कितनी मज़बूती से जुड़े हैं — असली data शायद ही कभी इतना साफ़ होता है।

换成 10 名学生后,r = 0.9963。注意在这张虚构的小表里,睡眠和焦虑与学习时长的关联有多强 —— 真实数据很少这么整齐。

Visualising with a scatter plotScatter plot से दिखाना用散点图可视化

import matplotlib.pyplot as plt
import numpy as np

x = [2, 4, 6, 8, 10]
y = [50, 60, 72, 80, 95]
r = np.corrcoef(x, y)[0, 1]

fig, ax = plt.subplots(figsize=(7, 4.5))
ax.scatter(x, y, color='#378add', s=100, zorder=3, edgecolors='white', linewidths=1)

m, b = np.polyfit(x, y, 1)                       # straight line of best fit
x_line = np.linspace(min(x) - 0.5, max(x) + 0.5, 100)
ax.plot(x_line, m * x_line + b, color='#f59e0b', linewidth=2, linestyle='--',
        label=f'Trend line: y = {m:.1f}x + {b:.1f}')

for xi, yi, lb in zip(x, y, ['Alice', 'Bob', 'Carol', 'Dan', 'Eve']):
    ax.annotate(lb, (xi, yi), textcoords='offset points', xytext=(8, -12),
                fontsize=9, color='#888780')

ax.set_title(f'Study Hours vs Exam Score  (r = {r:.3f})', fontsize=13)
ax.set_xlabel('Study hours'); ax.set_ylabel('Exam score')
ax.legend(); ax.grid(alpha=0.3)
plt.tight_layout(); plt.show()

print(f"Slope: {m:.2f} marks per extra hour, intercept: {b:.2f}")
OUTPUT
Slope: 5.50 marks per extra hour, intercept: 38.40
Output plot: the five students and the trend line.
Output plot: the five students and the trend line.
Output plot: पाँच छात्र और trend line.
输出图:五名学生和趋势线。

SectionSection第 07 节

Real-World Stories — Why Correlation Is Not Causationअसली कहानियाँ — Correlation, Causation क्यों नहीं真实故事 — 为什么相关不等于因果

When two variables are correlated, there are four common explanations. Only the first is "X causes Y":

जब दो variables correlated हों, तो चार आम कारण होते हैं। सिर्फ़ पहला "X, Y का कारण है" है:

两个变量相关时,常见的解释有四种,只有第一种是“X 导致 Y”:

Explanationकारण解释What it meansमतलब含义
CausationCausation因果X really changes YX सच में Y बदलता हैX 确实改变 Y
Reverse causationउल्टा causation反向因果Y actually changes Xअसल में Y, X को बदलता है其实是 Y 改变 X
ConfounderConfounder混杂变量A third variable Z drives bothएक तीसरा variable Z दोनों को चलाता है第三个变量 Z 同时驱动两者
Chanceसंयोग偶然A pattern in a small sample, or one of many comparisonsछोटे sample में, या बहुत सी तुलनाओं में से एक में बना pattern小样本里的偶然规律,或大量比较中碰巧出现的一个

Story 1 — The sunscreen paradoxकहानी 1 — Sunscreen का विरोधाभास故事 1 — 防晒霜悖论

A study finds that regions with higher sunscreen sales also have higher skin-cancer rates. A headline says: "Sunscreen causes cancer."

एक study पाती है कि जिन इलाक़ों में sunscreen ज़्यादा बिकती है, वहाँ skin cancer भी ज़्यादा है। Headline कहती है: "Sunscreen से cancer होता है।"

一项研究发现,防晒霜销量越高的地区,皮肤癌发病率也越高。标题写道:“防晒霜致癌。”

⚠️
Confounder: Sun ExposureConfounder: धूप混杂变量:日晒

Sunny regions have more UV exposure, so people buy more sunscreen and get more skin cancer (sunscreen lowers the risk but cannot remove it). UV exposure drives both. The raw correlation points the wrong way; you need to compare people with similar sun exposure.

धूप वाले इलाक़ों में UV ज़्यादा होता है, इसलिए लोग ज़्यादा sunscreen ख़रीदते हैं और उन्हें skin cancer भी ज़्यादा होता है (sunscreen ख़तरा घटाती है, मिटा नहीं सकती)। UV दोनों को चलाता है। Raw correlation ग़लत दिशा दिखाता है; एक जैसी धूप वाले लोगों की तुलना करनी होगी।

阳光充足的地区紫外线更强,所以人们买更多防晒霜,也更容易得皮肤癌(防晒霜能降低但无法消除风险)。紫外线同时驱动两者。原始相关指向了错误的方向;需要比较日晒程度相近的人群。

Story 2 — Netflix and shoe sizeकहानी 2 — Netflix और shoe size故事 2 — Netflix 和鞋码

Imagine a dataset of children and adults in which bigger shoe sizes go with more Netflix hours (r = +0.71). Should Netflix target large-footed customers?

कल्पना करें कि बच्चों और बड़ों के एक dataset में बड़े shoe size के साथ ज़्यादा Netflix घंटे आते हैं (r = +0.71)। क्या Netflix को बड़े पैरों वाले customers को target करना चाहिए?

设想一个包含儿童和成人的数据集,鞋码越大,看 Netflix 的时间越长(r = +0.71)。Netflix 应该瞄准大脚顾客吗?

💡
Confounder: AgeConfounder: उम्र混杂变量:年龄

Adults have bigger feet and also watch more Netflix than young children. Age is the hidden variable. Compare people of the same age and the link disappears. Such a correlation is often called spurious: it is real in the numbers, but it does not reflect a direct link.

बड़ों के पैर बड़े होते हैं और वे छोटे बच्चों से ज़्यादा Netflix भी देखते हैं। उम्र छिपा हुआ variable है। एक ही उम्र के लोगों की तुलना करें और link ग़ायब हो जाता है। ऐसे correlation को अक्सर spurious कहते हैं: संख्याओं में असली, पर कोई सीधा link नहीं।

成人脚更大,看 Netflix 也比小孩多。年龄就是隐藏变量。比较同龄人,这个联系就消失了。这样的相关常被称为伪相关:数字上是真的,但并不代表直接联系。

Story 3 — Support tickets and revenueकहानी 3 — Support tickets और revenue故事 3 — 客服工单与收入

An e-commerce company finds a strong correlation (r = +0.82) between support tickets and revenue. A manager suggests cutting support to reduce tickets and save money.

एक e-commerce company support tickets और revenue के बीच मज़बूत correlation (r = +0.82) पाती है। एक manager tickets घटाने और पैसा बचाने के लिए support काटने का सुझाव देता है।

一家电商公司发现客服工单数与收入强相关(r = +0.82)。一位经理建议削减客服,以减少工单、节省开支。

⚠️
Reverse Causationउल्टा Causation反向因果

More revenue means more customers, and more customers raise more tickets. Revenue drives tickets, not the other way round. Cutting support would hurt customers and future revenue. The correlation is real; the assumed direction was backwards.

ज़्यादा revenue = ज़्यादा customers, और ज़्यादा customers = ज़्यादा tickets. Revenue tickets को चलाता है, उल्टा नहीं। Support काटने से customers और भविष्य का revenue दोनों को नुक़सान होगा। Correlation असली है; मानी गई दिशा उल्टी थी।

收入越多意味着顾客越多,顾客越多工单就越多。是收入带动了工单,而不是反过来。削减客服会伤害顾客和未来收入。相关是真的,但假设的方向反了。

Removing a confounder in PythonPython में confounder हटाना在 Python 中去除混杂变量

import numpy as np

rng = np.random.default_rng(1)
temp = rng.uniform(15, 40, 365)                            # daily temperature, °C
ice_cream = 20 * temp + rng.normal(0, 60, 365)             # sales depend on heat
drownings = 0.15 * temp + rng.normal(0, 0.8, 365)          # swimming depends on heat

print(f"r(ice cream, drownings) = {np.corrcoef(ice_cream, drownings)[0, 1]:.2f}")

# Control for temperature: remove what temperature explains, correlate the rest
def residuals(v, z):
    slope, intercept = np.polyfit(z, v, 1)
    return v - (slope * z + intercept)

partial = np.corrcoef(residuals(ice_cream, temp), residuals(drownings, temp))[0, 1]
print(f"Partial r, controlling for temperature = {partial:.2f}")
OUTPUT
r(ice cream, drownings) = 0.74 Partial r, controlling for temperature = 0.03

This is a partial correlation: regress each variable on temperature, keep the leftovers (residuals) and correlate those. The raw r of 0.74 falls to 0.03.

यह partial correlation है: हर variable को temperature पर regress करें, बचा हुआ हिस्सा (residuals) रखें और उनका correlation निकालें। Raw r 0.74 से गिरकर 0.03 हो जाता है।

这就是偏相关:把每个变量对气温做回归,保留剩下的部分(残差),再计算残差之间的相关。原始 r 从 0.74 降到 0.03。

LIVELIVE互动Hidden Variable — Ice Cream, Drowning and Temperatureछिपा Variable — Ice Cream, Drowning और Temperature隐藏变量 — 冰淇淋、溺水与气温

200 simulated days. Turn up the effect of temperature and the raw r grows. Then control for temperature. Add a direct link to see what a real effect would look like.

200 simulated दिन। तापमान का असर बढ़ाएँ और raw r बढ़ता है। फिर तापमान को control करें। असली असर कैसा दिखता, यह देखने के लिए सीधा link जोड़ें।

200 个模拟日。调高气温的影响,原始 r 随之增大。然后控制气温。再加入直接联系,看看真实效应是什么样子。


SectionSection第 08 节

Pearson vs Spearman — Which to Use?Pearson vs Spearman — कौन सा इस्तेमाल करें?Pearson vs Spearman — 用哪个?

Pearson measures linear association. Spearman ranks both variables first and then applies Pearson to the ranks, so it measures monotonic association — "when x goes up, does y go up (or down), at any rate?"

Pearson linear रिश्ता मापता है। Spearman पहले दोनों variables को rank करता है और फिर ranks पर Pearson लगाता है, इसलिए यह monotonic रिश्ता मापता है — "x बढ़ने पर क्या y किसी भी रफ़्तार से बढ़ता (या घटता) है?"

Pearson 衡量线性关联。Spearman 先把两个变量转成名次,再对名次计算 Pearson,所以它衡量的是单调关联 ——“x 上升时,y 是否(以任意速度)上升或下降?”

Propertyगुण特性Pearson rSpearman ρ
Measuresमापता है衡量Straight-line relationshipसीधी-line रिश्ता直线关系Monotonic relationship (ranks)Monotonic रिश्ता (ranks)单调关系(名次)
Needs normal data?Normal data चाहिए?需要正态数据?Not for r itself; its p-value assumes roughly normal data or a large nr के लिए नहीं; इसका p-value लगभग normal data या बड़ा n मानता हैr 本身不需要;其 p 值假设数据近似正态或 n 较大Noनहीं不需要
Sensitive to outliers?Outliers से प्रभावित?对离群点敏感?Veryबहुत非常敏感Less (but not immune)कम (पर पूरी तरह बचा नहीं)较不敏感(但并非免疫)
Ordinal data?Ordinal data?定序数据?Not suitableउपयुक्त नहीं不适合Yesहाँ适合
Sees a U-shape?U-shape देखता है?能识别 U 形吗?Noनहीं不能Noनहीं不能
Use whenकब इस्तेमाल करें适用场景Continuous data, roughly linear, no extreme outliersContinuous data, लगभग linear, कोई extreme outlier नहीं连续数据,大致线性,无极端离群点Ranks, ratings, skewed data, curved but one-direction trendsRanks, ratings, skewed data, curved पर एक दिशा वाले trends名次、评分、偏斜数据、弯曲但单向的趋势
from scipy import stats

x = [2, 4, 6, 8, 10, 3, 7, 5, 9, 1]                   # study hours
y = [50, 60, 72, 80, 95, 55, 78, 65, 88, 40]          # exam scores

pearson_r, pearson_p = stats.pearsonr(x, y)
spearman_r, spearman_p = stats.spearmanr(x, y)
print(f"Pearson r  = {pearson_r:.4f}  (p = {pearson_p:.2e})")
print(f"Spearman ρ = {spearman_r:.4f}  (p = {spearman_p:.2e})")

# Add one student who studied 12 hours but was ill on exam day
x2, y2 = x + [12], y + [30]
print(f"\nWith one outlier → Pearson r = {stats.pearsonr(x2, y2)[0]:.4f}, "
      f"Spearman ρ = {stats.spearmanr(x2, y2)[0]:.4f}")
OUTPUT
Pearson r = 0.9963 (p = 8.61e-10) Spearman ρ = 1.0000 (p = 6.65e-64) With one outlier → Pearson r = 0.3523, Spearman ρ = 0.5000

In this data the exam score rises every time study hours rise, so the ranks match perfectly: Spearman ρ = 1.0000 exactly. One sick student (12 hours, 30 marks) drags Pearson from 0.996 to 0.35 — Spearman drops too, to 0.50, so "robust" does not mean "unaffected".

इस data में study hours बढ़ने पर हर बार exam score बढ़ता है, इसलिए ranks पूरी तरह मेल खाते हैं: Spearman ρ ठीक 1.0000 है। एक बीमार छात्र (12 घंटे, 30 marks) Pearson को 0.996 से 0.35 तक खींच देता है — Spearman भी गिरकर 0.50 हो जाता है, यानी "robust" का मतलब "अप्रभावित" नहीं।

在这组数据中,学习时长每增加一次,考试分数都随之上升,所以名次完全一致:Spearman ρ 正好等于 1.0000。一个生病的学生(学 12 小时,考 30 分)就把 Pearson 从 0.996 拉到 0.35 —— Spearman 也降到 0.50,可见“稳健”不等于“不受影响”。


SectionSection第 09 节

Is the Correlation Real? p-values and Sample Sizeक्या Correlation असली है? p-values और Sample Size相关是真的吗?p 值与样本量

💡
What the p-value Means Hereयहाँ p-value का मतलब这里的 p 值是什么意思

The p-value answers: if the true correlation were zero, how often would a sample this size show an r at least this far from zero? p < 0.05 is the usual line for "statistically significant". With 6 points, r = 0.6 gives p = 0.21 — not convincing. Two cautions: a tiny r can be "significant" in a huge dataset, and significance says nothing about cause.

p-value इस सवाल का जवाब देता है: अगर असली correlation zero होता, तो इतने बड़े sample में कितनी बार कम से कम इतना दूर r दिखता? "Statistically significant" के लिए आम सीमा p < 0.05 है। 6 points के साथ r = 0.6 पर p = 0.21 — भरोसेमंद नहीं। दो सावधानियाँ: बहुत बड़े dataset में छोटा r भी "significant" हो सकता है, और significance कारण के बारे में कुछ नहीं कहती।

p 值回答的是:如果真实相关为零,这么大的样本有多大概率得到离零至少这么远的 r?通常以 p < 0.05 作为“统计显著”的界线。6 个点时,r = 0.6 对应 p = 0.21 —— 不足为信。两点提醒:在超大数据集中,极小的 r 也可能“显著”;而显著性完全不说明因果。

from scipy import stats
import numpy as np

# Small sample: r = 0.6 from just 6 points
x_small = [1, 2, 3, 4, 5, 6]
y_small = [3, 5, 2, 6, 4, 7]
r_s, p_s = stats.pearsonr(x_small, y_small)

# Large sample: about the same r from 100 points
rng = np.random.default_rng(42)
x_large = rng.uniform(1, 10, 100)
y_large = 0.6 * x_large + rng.normal(0, 2, 100)
r_l, p_l = stats.pearsonr(x_large, y_large)

print(f"Small sample (n=6):   r = {r_s:.3f}  p = {p_s:.3f}")
print(f"Large sample (n=100): r = {r_l:.3f}  p = {p_l:.2e}")

# 95% confidence interval for r (scipy >= 1.9)
for name, res in [('n=6', stats.pearsonr(x_small, y_small)), ('n=100', stats.pearsonr(x_large, y_large))]:
    ci = res.confidence_interval(0.95)
    print(f"{name:<6} 95% CI for r: {ci.low:.2f} to {ci.high:.2f}")
OUTPUT
Small sample (n=6): r = 0.600 p = 0.208 Large sample (n=100): r = 0.611 p = 1.46e-11 n=6 95% CI for r: -0.41 to 0.95 n=100 95% CI for r: 0.47 to 0.72

Same r, very different certainty. With 6 points the 95% confidence interval for r runs from −0.41 to 0.95 — the true correlation could even be negative. With 100 points it is 0.47 to 0.72.

एक जैसा r, पर निश्चितता बहुत अलग। 6 points पर r का 95% confidence interval −0.41 से 0.95 तक है — असली correlation negative भी हो सकता है। 100 points पर यह 0.47 से 0.72 है।

同样的 r,可信程度天差地别。6 个点时,r 的 95% 置信区间是 −0.41 到 0.95 —— 真实相关甚至可能是负的。100 个点时则是 0.47 到 0.72。

LIVELIVE互动How Much Does r Wobble? Sample Size in Actionr कितना हिलता है? Sample Size का असरr 会晃动多少?样本量的作用

1,000 samples are drawn from a population with the true correlation you choose. Red bars are "significant" samples. Try ρ = 0 with n = 10, then ρ = 0.3 with n = 20 and n = 200.

आपके चुने असली correlation वाली population से 1,000 samples निकाले जाते हैं। लाल bars "significant" samples हैं। ρ = 0 और n = 10 आज़माएँ, फिर ρ = 0.3 के साथ n = 20 और n = 200.

从你设定真实相关的总体中抽取 1,000 个样本。红色柱是“显著”的样本。先试 ρ = 0、n = 10,再试 ρ = 0.3 时 n = 20 和 n = 200。


SectionSection第 10 节

Correlation Matrix — Many Variables at OnceCorrelation Matrix — एक साथ कई Variables相关矩阵 — 同时看多个变量

Real datasets have many columns. A correlation matrix shows r for every pair at once, and a heatmap makes it easy to scan.

असली datasets में बहुत से columns होते हैं। Correlation matrix हर जोड़े का r एक साथ दिखाती है, और heatmap इसे देखना आसान बनाता है।

真实数据集有很多列。相关矩阵一次展示每一对变量的 r,热力图让人一眼扫完。

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(42)
n = 100

df = pd.DataFrame({
    'study_hours': rng.uniform(1, 12, n),
    'sleep_hours': rng.uniform(4, 9, n),
    'anxiety':     rng.uniform(1, 10, n),
})
# Build realistic relationships
df['exam_score'] = (df['study_hours'] * 6 + df['sleep_hours'] * 3
                    - df['anxiety'] * 2 + rng.normal(20, 6, n)).clip(0, 100)
df['salary_k'] = (df['exam_score'] * 0.4 + rng.normal(30, 8, n)).clip(20, 120)

corr = df.corr().round(2)
print(corr)

fig, ax = plt.subplots(figsize=(7, 5.5))
sns.heatmap(corr, annot=True, fmt='.2f', cmap='coolwarm', vmin=-1, vmax=1, center=0,
            square=True, linewidths=0.5, ax=ax)
ax.set_title('Correlation Matrix — Student Data', fontsize=13)
plt.tight_layout(); plt.show()
OUTPUT
study_hours sleep_hours anxiety exam_score salary_k study_hours 1.00 -0.14 -0.05 0.87 0.63 sleep_hours -0.14 1.00 0.02 0.11 0.12 anxiety -0.05 0.02 1.00 -0.33 -0.35 exam_score 0.87 0.11 -0.33 1.00 0.74 salary_k 0.63 0.12 -0.35 0.74 1.00
Output heatmap.
Output heatmap.
Output heatmap.
输出热力图。
🎯
Reading a Correlation HeatmapCorrelation Heatmap पढ़ना如何读相关热力图

Dark red = strong positive, dark blue = strong negative, pale = near zero. The diagonal is always 1 (each variable with itself), and the matrix is a mirror image across it. Here study hours → exam score (0.87) → salary (0.74) stand out. Note that salary and study hours are linked (0.63) only through exam score in how this data was built — the matrix cannot tell you that.

गहरा लाल = मज़बूत positive, गहरा नीला = मज़बूत negative, हल्का = zero के पास। Diagonal हमेशा 1 होता है (हर variable अपने साथ), और matrix उसके दोनों ओर एक जैसी है। यहाँ study hours → exam score (0.87) → salary (0.74) उभरते हैं। ध्यान दें: इस data को जिस तरह बनाया गया, उसमें salary और study hours (0.63) सिर्फ़ exam score के ज़रिए जुड़े हैं — matrix यह नहीं बता सकती।

深红 = 强正相关,深蓝 = 强负相关,浅色 = 接近零。对角线永远是 1(每个变量和自己),矩阵沿对角线对称。这里突出的是学习时长 → 考试分数(0.87)→ 薪资(0.74)。注意:按这份数据的构造方式,薪资与学习时长(0.63)只是通过考试分数间接相连 —— 矩阵本身无法告诉你这一点。


SectionSection第 11 节

Four Warnings About CorrelationCorrelation के बारे में चार चेतावनियाँ关于相关性的四个警告

Warning 1 — Anscombe's quartetचेतावनी 1 — Anscombe's quartet警告 1 — Anscombe 四重奏

In 1973, statistician Francis Anscombe built four small datasets with the same means, the same correlation (r ≈ 0.816) and the same best-fit line — but completely different pictures.

1973 में statistician Francis Anscombe ने चार छोटे datasets बनाए, जिनके means, correlation (r ≈ 0.816) और best-fit line एक जैसे थे — पर तस्वीरें बिल्कुल अलग।

1973 年,统计学家 Francis Anscombe 构造了四个小数据集,它们的均值、相关系数(r ≈ 0.816)和最佳拟合直线都相同 —— 画出来却截然不同。

import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

x123 = [10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5]
datasets = [
    (x123, [8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68]),
    (x123, [9.14, 8.14, 8.74, 8.77, 9.26, 8.10, 6.13, 3.10, 9.13, 7.26, 4.74]),
    (x123, [7.46, 6.77, 12.74, 7.11, 7.81, 8.84, 6.08, 5.39, 8.15, 6.42, 5.73]),
    ([8, 8, 8, 8, 8, 8, 8, 19, 8, 8, 8],
     [6.58, 5.76, 7.71, 8.84, 8.47, 7.04, 5.25, 12.50, 5.56, 7.91, 6.89]),
]

fig, axes = plt.subplots(2, 2, figsize=(9, 7))
for i, (ax, (x, y)) in enumerate(zip(axes.flatten(), datasets), 1):
    r = np.corrcoef(x, y)[0, 1]
    m, b = np.polyfit(x, y, 1)
    ax.scatter(x, y, color='#378add', s=60, zorder=3)
    xs = np.array([3, 20])
    ax.plot(xs, m * xs + b, color='#f59e0b', linewidth=1.5, linestyle='--')
    ax.set_title(f'Dataset {i}  (r = {r:.3f})', fontsize=11)
    ax.set_xlim(2, 21); ax.set_ylim(2, 14); ax.grid(alpha=0.3)
    rho = stats.spearmanr(x, y)[0]
    print(f"Dataset {i}: mean y = {np.mean(y):.2f}, r = {r:.3f}, "
          f"line y = {m:.2f}x + {b:.2f}, Spearman ρ = {rho:.3f}")

plt.suptitle("Anscombe's Quartet — same r, completely different data", fontsize=13)
plt.tight_layout(); plt.show()
OUTPUT
Dataset 1: mean y = 7.50, r = 0.816, line y = 0.50x + 3.00, Spearman ρ = 0.818 Dataset 2: mean y = 7.50, r = 0.816, line y = 0.50x + 3.00, Spearman ρ = 0.691 Dataset 3: mean y = 7.50, r = 0.816, line y = 0.50x + 3.00, Spearman ρ = 0.991 Dataset 4: mean y = 7.50, r = 0.817, line y = 0.50x + 3.00, Spearman ρ = 0.500
Output plot: same r and same line, four different stories.
Output plot: same r and same line, four different stories.
Output plot: एक ही r और line, चार अलग कहानियाँ।
输出图:同样的 r 和直线,四个不同的故事。
⚠️
Always Plot Your Dataहमेशा अपना Data Plot करें一定要画图

Dataset 1 is a normal linear cloud. Dataset 2 is a smooth curve. Dataset 3 is a perfect line spoiled by one outlier. Dataset 4 has every x equal to 8 except one point, which creates the whole correlation. Spearman ρ differs a lot between them (0.82, 0.69, 0.99, 0.50) — a hint that something is different. Look at the scatter plot before trusting r.

Dataset 1 एक सामान्य linear बादल है। Dataset 2 एक smooth curve है। Dataset 3 एक perfect line है जिसे एक outlier ने बिगाड़ा। Dataset 4 में एक point को छोड़कर हर x = 8 है, और वही point पूरा correlation बनाता है। इनमें Spearman ρ बहुत अलग है (0.82, 0.69, 0.99, 0.50) — संकेत कि कुछ अलग है। r पर भरोसा करने से पहले scatter plot देखें।

数据集 1 是正常的线性点云;数据集 2 是一条平滑曲线;数据集 3 是被一个离群点破坏的完美直线;数据集 4 除一个点外所有 x 都等于 8,正是那一个点制造了全部相关。它们的 Spearman ρ 差别很大(0.82、0.69、0.99、0.50)—— 提示数据有所不同。相信 r 之前,先看散点图。

Warning 2 — Non-linear relationshipsचेतावनी 2 — Non-linear रिश्ते警告 2 — 非线性关系

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

rng = np.random.default_rng(0)
x = np.linspace(-3, 3, 100)
y = x ** 2 + rng.normal(0, 0.2, 100)     # a U-shape plus a little noise

print(f"Pearson r  = {np.corrcoef(x, y)[0, 1]:.4f}")
print(f"Spearman ρ = {stats.spearmanr(x, y)[0]:.4f}")

fig, ax = plt.subplots(figsize=(7, 4))
ax.scatter(x, y, color='#378add', s=30, alpha=0.7)
ax.set_title(f'y ≈ x² — strong relationship, but r = {np.corrcoef(x, y)[0, 1]:.3f}')
ax.set_xlabel('x'); ax.set_ylabel('y'); ax.grid(alpha=0.3)
plt.tight_layout(); plt.show()
OUTPUT
Pearson r = 0.0031 Spearman ρ = -0.0050
Output plot: y depends strongly on x, yet r ≈ 0.
Output plot: y depends strongly on x, yet r ≈ 0.
Output plot: y, x पर बहुत निर्भर है, फिर भी r ≈ 0.
输出图:y 强烈依赖 x,但 r ≈ 0。
💡
r ≈ 0 Does Not Mean "No Relationship"r ≈ 0 का मतलब "कोई रिश्ता नहीं" नहींr ≈ 0 不等于“没有关系”

A U-shape gives r ≈ 0 even though x predicts y very well. Spearman does not help here either (ρ ≈ 0), because a U-shape is not monotonic. Spearman fixes curves that keep going one way; for U-shapes and other patterns you need the scatter plot (or measures such as mutual information).

U-shape पर r ≈ 0 आता है, जबकि x, y को बहुत अच्छी तरह बताता है। यहाँ Spearman भी मदद नहीं करता (ρ ≈ 0), क्योंकि U-shape monotonic नहीं है। Spearman सिर्फ़ उन curves को संभालता है जो एक ही दिशा में चलते रहें; U-shapes और दूसरे patterns के लिए scatter plot चाहिए (या mutual information जैसे माप)।

U 形关系的 r ≈ 0,尽管 x 能很好地预测 y。这里 Spearman 也帮不上忙(ρ ≈ 0),因为 U 形不是单调的。Spearman 只能处理一直朝一个方向的曲线;对 U 形等其他模式,需要看散点图(或使用互信息等度量)。

LIVELIVE互动Same r, Different Shapes — Pearson vs Spearmanएक r, अलग Shapes — Pearson vs Spearman同样的 r,不同的形状 — Pearson vs Spearman

Click through Anscombe's four datasets and four other shapes. Compare Pearson r with Spearman ρ, and read why they agree or disagree.

Anscombe के चार datasets और चार दूसरे shapes पर click करें। Pearson r की Spearman ρ से तुलना करें, और पढ़ें कि वे क्यों मेल खाते या नहीं खाते।

依次点击 Anscombe 的四个数据集和另外四种形状。比较 Pearson r 和 Spearman ρ,看看它们为什么一致或不一致。

Warning 3 — Sample size mattersचेतावनी 3 — Sample size मायने रखता है警告 3 — 样本量很重要

See Section 9: with few points, r jumps around a lot, and chance alone can produce a large r. Always report n (and ideally a confidence interval) with r.

Section 9 देखें: कम points पर r बहुत उछलता है, और सिर्फ़ संयोग से बड़ा r बन सकता है। r के साथ हमेशा n (और हो सके तो confidence interval) बताएँ।

见第 9 节:点少时 r 波动很大,仅凭偶然就可能得到很大的 r。报告 r 时一定附上 n(最好再加置信区间)。

Warning 4 — Correlation does not tell you the slopeचेतावनी 4 — Correlation slope नहीं बताता警告 4 — 相关系数不告诉你斜率

📐 SAME r, DIFFERENT SLOPESएक r, अलग SLOPES相同的 r,不同的斜率
Same r, different slopes r = 0.90 · +2 marks per hourr = 0.90 · +2 marks प्रति घंटाr = 0.90 · 每小时 +2 分 study hours →study hours →学习时长 → r = 0.90 · +12 marks per hourr = 0.90 · +12 marks प्रति घंटाr = 0.90 · 每小时 +12 分 study hours →study hours →学习时长 →
⚠️
r Says Nothing About "How Much"r "कितना" के बारे में कुछ नहीं कहताr 不说明“变化多少”

Both panels have r = 0.90. In one, each extra hour adds about 2 marks; in the other, about 12. r tells you how consistently the points follow a line, not how steep the line is. For "how much does y change per unit of x", use linear regression.

दोनों panels में r = 0.90 है। एक में हर extra घंटा लगभग 2 marks जोड़ता है; दूसरे में लगभग 12. r बताता है कि points line को कितनी लगातार follow करते हैं, यह नहीं कि line कितनी खड़ी है। "x की हर unit पर y कितना बदलता है" के लिए linear regression इस्तेमाल करें।

两个小图的 r 都是 0.90。一个每多学 1 小时约多 2 分,另一个约多 12 分。r 告诉你点沿直线分布有多一致,而不是直线有多陡。要回答“x 每变化一个单位,y 变化多少”,请用线性回归。


SectionSection第 12 节

Correlation in Machine LearningMachine Learning में Correlation机器学习中的相关性

Feature selection — find highly correlated featuresFeature selection — बहुत correlated features ढूँढना特征选择 — 找出高度相关的特征

import pandas as pd
import numpy as np

rng = np.random.default_rng(0)
n = 200
df = pd.DataFrame({
    'age':         rng.integers(22, 65, n),
    'performance': rng.uniform(1, 10, n),
    'team_size':   rng.integers(2, 20, n),
    'salary':      rng.normal(60, 15, n),
})
df['years_exp']   = (df['age'] - 22 - rng.integers(0, 6, n)).clip(0)   # tied to age
df['monthly_pay'] = df['salary'] / 12                                   # same info as salary

corr = df.corr().abs()
upper = corr.where(np.triu(np.ones(corr.shape), k=1).astype(bool))
pairs = upper.stack().sort_values(ascending=False)
print("Most correlated pairs:")
print(pairs.head(3).round(3))

to_drop = [col for col in upper.columns if (upper[col] > 0.85).any()]
print(f"\nFeatures to consider dropping: {to_drop}")
OUTPUT
Most correlated pairs: salary monthly_pay 1.000 age years_exp 0.991 performance years_exp 0.058 dtype: float64 Features to consider dropping: ['years_exp', 'monthly_pay']

monthly_pay is just salary / 12 (r = 1.000), and years_exp is almost fully determined by age (r = 0.991). Each pair carries nearly the same information.

monthly_pay बस salary / 12 है (r = 1.000), और years_exp लगभग पूरी तरह age से तय है (r = 0.991)। हर जोड़े में लगभग एक ही जानकारी है।

monthly_pay 就是 salary / 12(r = 1.000),years_exp 几乎完全由 age 决定(r = 0.991)。每一对携带的信息几乎相同。

🎯
MulticollinearityMulticollinearity多重共线性

When two features are highly correlated (a common cut-off is |r| > 0.85–0.9), a linear or logistic regression cannot tell which one deserves the credit, so its coefficients become unstable and hard to interpret. Keep the more meaningful one, combine them, or use regularisation (Ridge) or PCA. Tree models (random forest, XGBoost) predict fine with correlated features, but their feature importances get split between the pair.

जब दो features बहुत correlated हों (आम सीमा |r| > 0.85–0.9), तो linear या logistic regression यह नहीं बता पाता कि credit किसे दे, इसलिए उसके coefficients अस्थिर और समझने में मुश्किल हो जाते हैं। ज़्यादा मतलब वाला रखें, दोनों को मिलाएँ, या regularisation (Ridge) या PCA इस्तेमाल करें। Tree models (random forest, XGBoost) correlated features के साथ ठीक predict करते हैं, पर उनकी feature importance जोड़े में बँट जाती है।

当两个特征高度相关(常用界线 |r| > 0.85–0.9)时,线性或逻辑回归无法判断功劳该归谁,系数会变得不稳定、难以解释。可以保留更有意义的那个、把两者合并,或使用正则化(Ridge)或 PCA。树模型(随机森林、XGBoost)在特征相关时仍能正常预测,但特征重要性会被这对特征瓜分。


SectionSection第 13 节

Golden RulesGolden Rules黄金法则

🎯 Correlation — Key RulesCorrelation — मुख्य नियम相关性 — 关键规则
1
Correlation does not imply causation. Before believing "X causes Y", rule out reverse causation, confounders and chance.
Correlation का मतलब causation नहीं। "X, Y का कारण है" मानने से पहले उल्टा causation, confounders और संयोग को ख़ारिज करें।
相关不等于因果。在相信“X 导致 Y”之前,先排除反向因果、混杂变量和偶然。
2
Always plot your data first. Anscombe's quartet shows four different datasets with the same r. The scatter plot reveals curves, outliers and groups.
हमेशा पहले data plot करें। Anscombe's quartet एक ही r वाले चार अलग datasets दिखाता है। Scatter plot curves, outliers और groups दिखाता है।
一定先画图。Anscombe 四重奏展示了 r 相同的四个不同数据集。散点图能揭示曲线、离群点和分组。
3
Use Pearson for roughly linear, continuous data without extreme outliers. Use Spearman for ranks, ratings, skewed data and one-direction curves. Neither sees a U-shape.
लगभग linear, continuous data जिसमें extreme outliers न हों, उसके लिए Pearson लें। Ranks, ratings, skewed data और एक-दिशा वाले curves के लिए Spearman. कोई भी U-shape नहीं देखता।
大致线性、连续且无极端离群点的数据用 Pearson;名次、评分、偏斜数据和单向曲线用 Spearman。两者都看不出 U 形。
4
Report r with n and a p-value or confidence interval. r = 0.9 from 5 points has p ≈ 0.04; from 4 points p ≈ 0.10. The same r from 100 points is overwhelming evidence.
r के साथ n और p-value या confidence interval बताएँ। 5 points से r = 0.9 पर p ≈ 0.04; 4 points से p ≈ 0.10. 100 points से वही r बहुत मज़बूत सबूत है।
报告 r 时附上 n 以及 p 值或置信区间。5 个点的 r = 0.9 对应 p ≈ 0.04;4 个点时 p ≈ 0.10。同样的 r 来自 100 个点,就是压倒性的证据。
5
r is not the slope. It measures how consistently points follow a line, not how much y changes per unit of x. Use regression for that.
r, slope नहीं है। यह मापता है कि points line को कितनी लगातार follow करते हैं, यह नहीं कि x की हर unit पर y कितना बदलता है। उसके लिए regression लें।
r 不是斜率。它衡量点沿直线分布的一致程度,而不是 x 每变一个单位 y 变多少。那要用回归。
6
In ML, drop or combine features that are highly correlated with each other. A feature's correlation with the target is a useful first look, but a low r does not prove it is useless — it may matter non-linearly or together with other features.
ML में जो features आपस में बहुत correlated हों, उन्हें हटाएँ या मिलाएँ। किसी feature का target से correlation पहली नज़र के लिए उपयोगी है, पर कम r यह साबित नहीं करता कि वह बेकार है — वह non-linear तरीके से या दूसरे features के साथ मायने रख सकता है।
在机器学习中,删除或合并彼此之间高度相关的特征。特征与目标的相关性是很好的初步参考,但 r 低并不能证明它没用 —— 它可能以非线性方式或与其他特征共同起作用。