পাঠ ১৪ · ৩০-এর মধ্যে · মডিউল ২
Home / AI Courses / ডেটা সায়েন্স / Correlation ও causation

Correlation ও causation

Correlation vs causation
৭ মিনিট পড়া মাঝারি · Intermediate pandas + scipy

এই পাঠে যা শিখবেন

  • Pearson vs Spearman — কোনটা কখন
  • Spurious correlation — random relations
  • Confounders ও lurking variable
  • Simpson's paradox — group বদলালে trend উল্টো
  • Causation establish-এর পদ্ধতি (RCT, IV, DiD)

১ · Correlation কী?

CorrelationCorrelationদু'টি variable-এর co-variation-এর strength + direction-এর measure। -১ থেকে ১। ০ মানে independent (linear), ±১ মানে perfectly co-related। = দু'টি variable একসাথে কীভাবে চলে — তার measure।

Pearson correlation ($r$):

$$r = \frac{\sum (x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum (x_i - \bar{x})^2 \cdot \sum (y_i - \bar{y})^2}}$$

Range: $-1 \leq r \leq 1$।

  • $r = 1$ — perfect positive linear।
  • $r = -1$ — perfect negative linear।
  • $r = 0$ — no linear correlation।

২ · Pearson vs Spearman

Pearson: linear relationship measure। Outlier-এ sensitive। Normal-distributed data-এ accurate।

SpearmanSpearman's rank correlationCharles Spearman (১৯০৪) — Pearson-এর rank-version। Monotonic (linear না হলেও) সম্পর্ক measure। Outlier-resistant। (rank-based): data-কে rank-এ convert করে Pearson। Monotonic (যেকোনো ক্রমবর্ধমান বা ক্রমহ্রাসমান) relationship capture। Outlier-robust।

কখন কোনটা:

  • Linear, normal-ish, no outlier → Pearson।
  • Non-linear monotonic, ordinal, outlier আছে → Spearman।
  • সাবধানতার জন্য — দু'টি report করুন; পার্থক্য অনেক হলে non-linear pattern indicate।
Anscombe's quartet

৪টি ভিন্ন ডেটাসেট — সবার Pearson r ≈ ০.৮২। একটি সরল linear, একটি curve, একটি outlier-এ inflated, একটি constant + outlier। সবসময় visualize — শুধু সংখ্যা trust করবেন না!

৩ · Correlation ≠ Causation

২০০ বছরের statistics-এর সবচেয়ে গুরুত্বপূর্ণ নীতি — যেটা সবচেয়ে বেশি ভঙ্গ হয়।

X ও Y correlated কেন হতে পারে — ৪টি possibility:

  1. X → Y: X cause Y।
  2. Y → X: Y cause X (reverse causation)।
  3. Z → X, Z → Y: তৃতীয় variable Z দুটোকেই cause (confounder)।
  4. Coincidence: random sample-এ chance association।

৪ · Spurious correlation

Spurious correlationSpurious Correlationstatistically significant কিন্তু causally meaningless সম্পর্ক। বড় dataset-এ অনেক variable-এর pairwise correlation random-ভাবেই উঠে আসে।: meaningless সম্পর্ক — যা random data-এ ঘটে।

Famous examples (tylervigen.com):

  • U.S. ক্ষীরের খরচ ও nuclear PhD সংখ্যা — r > ০.৯।
  • Maine-এ divorce rate ও margarine consumption — r > ০.৯।
  • Nicolas Cage-এর film সংখ্যা ও pool drowning — r ≈ ০.৬।

কেন ঘটে:

  • Time-series-এ — দু'টোই trending → spurious।
  • হাজার variable check → কিছু random-ভাবেই correlate।
  • Selection bias — sample-এ ভুল dataset।

৫ · Confounders

ConfounderConfounderএকটি variable যা cause ও outcome দুটোকেই influence করে — observational study-এর সবচেয়ে বড় bias source। Stratification, regression, propensity score দিয়ে adjust।: তৃতীয় variable যা cause ও outcome দু'টোকেই affect করে।

ক্লাসিক উদাহরণ:

  • Ice cream sale ↑, drowning ↑ → কারণ summer (heat, swimming)।
  • Coffee consumption ↑, lung cancer ↑ → smoker-রা coffee বেশি খান।
  • Daraz-এ "free shipping click → high purchase" → both indicate "engaged user"।

বাংলাদেশি examples:

  • "যারা bKash বেশি ব্যবহার করেন তারা সফল ব্যবসায়ী" — confounder: business size।
  • "Pathao app-এ subscribe করলে satisfaction বেশি" — confounder: regular user।
  • "Coaching-এ পড়লে SSC ভাল" — confounder: পরিবারের আগ্রহ।

৬ · Simpson's paradox

Simpson's paradoxSimpson's ParadoxEdward Simpson (১৯৫১) — aggregate trend ও sub-group trend বিপরীত হতে পারে। Confounding-এর extreme manifestation।: aggregate-এ trend একদিকে, sub-group-এ উল্টো।

Berkeley admission (১৯৭৩):

  • Aggregate: পুরুষ admission ৪৪%, নারী ৩৫% — gender bias-এর অভিযোগ।
  • Department-wise: প্রায় প্রতি department-এ নারী-rate higher!
  • কারণ: নারীরা competitive department-এ apply করেন (low admission rate); পুরুষ less-competitive-এ।

Pathao analogue:

  • Aggregate: এক shift-এ avg ride completion time ২৫ min, অন্য shift-এ ২২।
  • Per-area: প্রতি এলাকায় shift A faster!
  • কারণ: shift A বেশি traffic-prone এলাকায় বেশি ride।

৭ · Causation establish-এর পদ্ধতি

Gold standard — RCT (Randomized Controlled Trial):

  • Subject randomly assign — treatment vs control।
  • Confounder average হয়ে যায়।
  • Drug trial, A/B test।

Quasi-experimental:

  • Natural experiment: external shock — random-like condition।
  • Difference-in-Differences (DiD): change pre/post in treated vs untreated।
  • Instrumental Variable (IV): instrument cause-এর সাথে correlated, outcome-এর সাথে না।
  • Regression Discontinuity (RD): threshold-এর around comparison।

Observational + adjustment:

  • Multiple regression — confounder control।
  • Propensity score matching।
  • Causal graph (Judea Pearl) — DAG-based reasoning।
X ও Y correlated — ৪টি সম্ভাব্য কারণ (১) X causes Y X Y straightforward cause (২) Y causes X — reverse X Y "satisfied → engagement" (৩) Confounder Z Z X Y heat → ice cream + drowning (৪) Coincidence — chance X ≈ Y Cage films ↔ drowning Causation establish-এর tools • RCT — random assignment • DiD — pre/post × treated/control • IV — external instrument • Regression with confounders Pure correlation — never enough
Correlation observe হলে — ৪টি সম্ভাব্য underlying mechanism। Causation দাবি করতে — additional evidence (experiment/structured analysis) চাই।

৮ · scipy দিয়ে correlation

Python · scipy + pandas
import numpy as np
import pandas as pd
from scipy import stats

np.random.seed(42)

# Daraz: order count vs total spend (linear)
n = 100
orders   = np.random.poisson(8, n)
spend    = orders * 500 + np.random.normal(0, 1000, n)

# Outlier inject
orders_o = np.append(orders, [50, 60])
spend_o  = np.append(spend,  [200, 200])

# Pearson vs Spearman with/without outlier
pr_clean,  _ = stats.pearsonr(orders, spend)
sp_clean,  _ = stats.spearmanr(orders, spend)
pr_dirty,  _ = stats.pearsonr(orders_o, spend_o)
sp_dirty,  _ = stats.spearmanr(orders_o, spend_o)

print(f"Without outlier  : Pearson={pr_clean:+.3f} | Spearman={sp_clean:+.3f}")
print(f"With outlier     : Pearson={pr_dirty:+.3f} | Spearman={sp_dirty:+.3f}")
print("\nSpearman robust হয় outlier-এ; Pearson collapse করে।")

    

৯ · Simpson's paradox simulation

Python · pandas demo
import pandas as pd

# Pathao 2 areas, 2 shifts — Simpson's paradox
df = pd.DataFrame({
    "area":  ["A","A","B","B"] * 2,
    "shift": ["day"]*4 + ["night"]*4,
    "rides":     [80, 80, 20, 20,    20, 20, 80, 80],
    "completion_pct": [95, 95, 70, 70,  93, 93, 65, 65],  # day better in each area
})

# Aggregate by shift (ignoring area)
agg = df.groupby("shift").apply(
    lambda g: (g["rides"] * g["completion_pct"]).sum() / g["rides"].sum()
)
print("Aggregate completion% by shift:")
print(agg.round(1))

# By area-shift
print("\nWithin each area, by shift:")
print(df.pivot_table(index="area", columns="shift",
                     values="completion_pct", aggfunc="mean"))

    
Aggregate-এ night-shift higher দেখাবে — কারণ night-এ সহজ এলাকার বেশি ride। কিন্তু সব এলাকায় day-shift better। Simpson's paradox classic।

ভাবনার প্রশ্ন

প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।

প্র ০১ "Daraz-এ যারা review লেখে তারা higher-spending customer" — এই correlation থেকে কি conclude করা যায় "review লিখলে spending বাড়বে"? কেন না, এবং কীভাবে test করবেন?

এটি classic correlation-causation confusion — এবং Daraz-এর মতো platform-এ সবসময় ঘটে।

সাবধান interpretation:

  • "Review-writing predicts higher spending" — সঠিক observational claim।
  • "Review লিখতে force করলে spending বাড়বে" — causal claim, evidence insufficient।

৪টি সম্ভাব্য কারণ:

  • (১) Review → Spending: Review লিখলে user platform-এ committed feel করেন → বেশি কেনেন।
  • (২) Spending → Review: অনেক কিনলে — বেশি product-এ experience → review write। Reverse causation।
  • (৩) Confounder: "Engaged user" type — both review লেখে ও বেশি কেনে। Personality variable।
  • (৪) Selection bias: Review-only those who had specific experience।

Likely answer — সম্ভবত (২) ও (৩):

  • বেশি product-এ experience হলেই review-যোগ্যতা।
  • "Engaged personality" — both behaviors।

RCT design — true causation test:

  • Treatment: Random ৫০% user-কে review-prompt পাঠান।
  • Control: বাকি ৫০% — no prompt।
  • Measure: Subsequent ৩ মাসের spending।
  • If treated > control significantly: review-prompt → spending causal lift।
  • If equal: review-spending correlation purely from confounder/reverse causation।

Quasi-experimental alternatives:

  • Natural experiment: "Verified review" feature launch হলে — affected vs unaffected users compare।
  • DiD: Reviewer vs non-reviewer, before/after feature change।
  • IV: "Review prompt show" instrument — show কি না randomized?
  • Propensity score matching: Reviewer-এর সাথে similar non-reviewer match।

Business implications:

  • Naive approach: "review বেশি correlate করে spending-এর সাথে — তাই review feature push করি।" — wasted effort possible।
  • RCT-confirmed: "review-prompt সত্যিই +৫% spending lift দেয়" — actionable।
  • Counter-intuitive: "review-prompt actually decrease — abandon-ed users complain বেশি।"

Modern e-commerce reality:

  • Amazon, Daraz — incentivized review (ছোট credit) — RCT testing চালু।
  • Review systems mostly retention-driver, not direct spend-driver।
  • Causal measurement company-priority।

মূল উপলব্ধি: "Correlation strong" ≠ "intervention will work"। Business decision-এর আগে — RCT-by-default mindset।

প্র ০২ Pearson r = ০.৮ বনাম Spearman r = ০.৩ — দুটোর মধ্যে বিশাল পার্থক্য কী indicate করে? কীভাবে diagnose করবেন?

এটি data scientist-এর জন্য একটি "diagnostic puzzle" — দু'টি correlation-এর difference signal দেয়।

ছোট difference (Pearson ≈ Spearman):

  • সম্পর্ক linear ও monotonic।
  • Outlier কম বা impact-less।
  • "Healthy" correlation।

Pearson >> Spearman:

  • Outlier-driven Pearson — কয়েকটি extreme point linear-fit pull করছে।
  • Underlying সম্পর্ক actually weak।
  • উদাহরণ: ১০০ point random + ২ point at far corner — Pearson 0.9, Spearman 0.05।

Pearson << Spearman (যা প্রশ্নের opposite case):

  • Strong monotonic but non-linear সম্পর্ক।
  • উদাহরণ: $Y = \log(X)$ — Pearson moderate, Spearman ১।
  • Transformation suggest।

আপনার scenario — Pearson 0.8, Spearman 0.3:

  • "Apparent strong linear" but rank-wise weak।
  • সম্ভবত — কয়েকটি outlier inflate করেছে Pearson।
  • আসল সম্পর্ক monotonic-ই দুর্বল।

Diagnosis — step by step:

  1. Scatter plot: সর্বদা প্রথম step। Outlier visible হবে।
  2. Boxplot per variable: Univariate outlier।
  3. Cook's distance / leverage: Influential point identification।
  4. Robust correlation: MCD-based, biweight midcorrelation।
  5. Outlier remove → recompute: Sensitivity check।

Action:

  • Outlier valid? — keep, use Spearman as primary।
  • Outlier error/glitch? — clean, recompute।
  • Outlier business-meaningful (e.g., VIP customer)? — separate model।

Pathao concrete example:

  • "Driver-rating vs earnings": Pearson 0.8, Spearman 0.3।
  • Diagnose: scatter plot — কয়েকজন superdriver-এ both very high।
  • Reality: vast majority-এর rating-earning সম্পর্ক weak; few outlier inflate।
  • Action: report Spearman; investigate top-tier drivers separately।

মূল উপলব্ধি: দু'টি correlation report করুন — পার্থক্য signal। Number-এ ভুল conclude এড়ান; visual-ই truth।

প্র ০৩ Simpson's paradox কেন এত dangerous? Pathao-এর dispatch optimization-এ কীভাবে এটি pitfall হতে পারে?

Simpson's paradox — data scientist-এর nightmare এবং এটি সম্পূর্ণ overlooked করা সবচেয়ে common big mistake।

Why dangerous:

  • Aggregate analysis "intuitive" — defaultly trust।
  • Sub-group breakdown skip।
  • Decision opposite to truth।
  • Detection-এ structural reasoning চাই।

ক্লাসিক structure:

  • Treatment (A vs B) ও subgroup (X vs Y) দু'টি variable।
  • প্রতি subgroup-এ A > B।
  • কিন্তু aggregate-এ B > A।
  • কারণ: subgroup proportion ভিন্ন A vs B-তে।

Pathao dispatch scenario:

Algorithm A vs Algorithm B — completion rate compare।

  • Aggregate: Algorithm B 92%, Algorithm A 88% → "B better"।
  • By area:
    • Easy area: A 95%, B 94%। A better।
    • Hard area: A 80%, B 78%। A better।
    • Both subgroups: A > B!
  • কারণ: Algorithm A বেশি hard-area-এ deploy করা হয়েছে। Algorithm B easy-area-এ। Mix ভিন্ন।

If aggregate trust করে:

  • "B 92% > A 88% — B deploy করি!" — ভুল সিদ্ধান্ত।
  • Actual: A everywhere better — A-ই deploy করা উচিত।

আরও Pathao examples:

  • "Promo coupon group higher cancellation" — কারণ promo high-value ride-এ; high-value ride-এ cancellation higher anyway।
  • "New driver lower rating" — কারণ new driver-রা specific ride-type পান।
  • "Premium tier complaint বেশি" — কারণ premium user বেশি active, exposure বেশি।

Detection technique:

  • Always stratify: Major covariates অনুযায়ী breakdown।
  • Check assignment: Treatment groups balanced কি? Yes → aggregate trust। No → confounding।
  • Multi-level model: Hierarchical structure explicitly model।
  • Causal DAG: Pearl-style graph — confounder visible।

Production防御:

  • Pre-registered analysis plan — subgroup analysis included।
  • Random assignment (RCT) — Simpson's eliminate।
  • Stratified sampling — covariate balance।
  • Code review with stat reviewer।

Real-world cost:

  • UC Berkeley Simpson's discovery — gender-bias lawsuit prevented।
  • Medical: kidney stone treatment — small vs large stone সম্পূর্ণ different optimal treatment।
  • Pathao parallel — wrong algorithm rolled out → ride-completion drop, churn up, revenue lost।

মূল উপলব্ধি: Aggregate alone misleading — always stratify, randomize, structure-aware। Simpson's existence-এর awareness data scientist-এর professional duty।

প্র ০৪ "Smoking causes lung cancer" — এটি observational study-এর মাধ্যমে কীভাবে establish হয়েছে যেহেতু RCT (লোকদের randomly smoke করতে force) সম্ভব না? এই lessons Daraz/Pathao-এ কীভাবে apply করা যায়?

Smoking-cancer link establishment — observational causal inference-এর greatest case study।

চ্যালেঞ্জ:

  • RCT impossible (ethically, practically)।
  • Smoking confounded with: age, ethnicity, socioeconomic status, lifestyle।
  • Tobacco industry actively challenge correlation-only evidence।

Bradford Hill criteria (১৯৬৫):

  • (১) Strength: Smoker-দের ১০-২০× higher cancer risk।
  • (২) Consistency: Multiple studies, populations — same finding।
  • (৩) Specificity: Smoking specifically lung cancer-এ.
  • (৪) Temporality: Smoking precede cancer।
  • (৫) Biological gradient: Dose-response — বেশি smoke = বেশি risk।
  • (৬) Plausibility: Carcinogen exposure mechanism existing।
  • (৭) Coherence: Lab + animal + epi সব align।
  • (৮) Experiment: Animal smoke experiment cancer induce।
  • (৯) Analogy: Other carcinogen-cancer link।

Statistical methods:

  • Cohort study: Doctors-এর smoking-mortality follow (Doll & Hill, ১৯৫০s)।
  • Case-control: Cancer patients vs matched controls — smoking history compare।
  • Twin studies: Genetics control।
  • Quasi-experiment: Tobacco tax → smoking decrease → cancer decrease (lag)।

Daraz/Pathao-এ analogous:

"Push notification user-engagement বাড়ায়" — RCT সম্ভব but expensive। Observational evidence:

  • Strength: Push-receivers ৩০% more engaged। Strong।
  • Temporality: Push pre-engagement।
  • Dose-response: বেশি push = বেশি engagement (until fatigue)।
  • Mechanism: Reminder → recall → action। Plausible।
  • Consistency: Multi-platform replicate।
  • Confounder concern: Push opt-in user-রা already engaged।
  • Final test: RCT — random push-on/off। Causal effect confirmed।

When RCT impossible — what to do:

  • Multiple methods triangulate: Cohort + case-control + natural experiment।
  • Quasi-experimental: Phase rollout → DiD; price change → IV।
  • Sensitivity analysis: "Confounder থাকলে কতটা strong হতে হবে result reverse করতে" — Robins-Rotnitzky।
  • Mediation analysis: Mechanism path।
  • Causal DAG: Assumption-explicit।

Bangladesh-specific:

  • "COVID lockdown → bKash adoption" — natural experiment।
  • "Pathao-এর driver-incentive change → completion rate" — DiD।
  • "Daraz Big Sale → category mix shift" — pre/post analysis।

Modern causal inference:

  • Judea Pearl's "do-calculus" — graphical approach।
  • Potential outcomes framework (Rubin)।
  • Causal ML (DoubleML, EconML libraries)।
  • Instrumental variables in marketing।

মূল উপলব্ধি: RCT impossible বলে causal inference impossible না — multiple evidence triangulation দিয়ে strong conclusion সম্ভব। Daraz/Pathao কিন্তু RCT-friendly platforms — RCT-default mindset adopt করুন।

অনুশীলন

  1. Pearson vs Spearman: $X = [1,2,3,4,5,6,7,8,9,10]$, $Y = [1,4,9,16,25,36,49,64,81,100]$ ($Y = X^2$)। কোনটা ১, কোনটা কম?
    • Spearman = ১ (perfectly monotonic — rank একই)।
    • Pearson ~০.৯৭ (linear approximate, কিন্তু relationship non-linear)।
    • পার্থক্য non-linearity indicate করে।
  2. Identify relation: প্রতিটিতে causation, reverse causation, confounder, বা coincidence?
    • (ক) "Ice cream sale বাড়লে drowning বাড়ে।"
    • (খ) "অসুস্থ মানুষ বেশি hospital যায়; hospital যাওয়া অসুস্থতা বাড়ায়।"
    • (গ) "Bangladesh-এ Pathao subscription growth ও crypto price ২০২২-এ correlated।"
    • (ঘ) "Drug X খেলে blood pressure কমে (RCT-প্রমাণিত)।"
    • (ক) Confounder — গরম season দু'টোকেই increase।
    • (খ) Reverse causation — অসুস্থতা hospital-যাওয়ার কারণ।
    • (গ) Coincidence — দু'টি unrelated trend।
    • (ঘ) Causation — RCT establish।
  3. ভাবুন: "যারা Daraz-এ premium membership নেন তারা ৩×বেশি spend করেন।" এই থেকে কি conclude করা যায় "premium membership push করলে spending বাড়বে"? কী test করবেন?

    না। সম্ভাব্য confounder: high-spending user-রাই premium-এ আগ্রহী (selection bias)। RCT: random ৫০% user-কে premium discount offer। Take-up গ্রহীতা vs নন-grhita compare। Ideally instrumental variable approach। প্র ০৪-এ details।

আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ

কোড রানার কাজ না করলে? ব্রাউজারে কাজ না করলে Google Colab ব্যবহার করুন — Google-এর ফ্রি অনলাইন Python পরিবেশ, শুধু Gmail অ্যাকাউন্ট লাগে।
পূর্ববর্তী পাঠ
পাঠ ১৩ · Chi-square ও ANOVA