পাঠ ১৩ · ৩০-এর মধ্যে · মডিউল ২

Chi-square ও ANOVA

Chi-square test & one-way ANOVA
৭ মিনিট পড়া মাঝারি · Intermediate scipy কোডসহ

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

  • Chi-square independence test — categorical relationship
  • One-way ANOVA — multi-group comparison
  • F-statistic-এর intuition
  • Test-এর assumption check ও alternative

১ · কেন chi-square ও ANOVA?

t-test শুধু numerical mean-এর ২ গ্রুপ compare করে। কিন্তু real-world-এ:

  • "লিঙ্গ আর pre-paid/post-paid-এ সম্পর্ক আছে কি?" — দু'টি categorical।
  • "৪ বিভাগের Daraz user-দের গড় order value কি ভিন্ন?" — ৪ গ্রুপ।

এই দু'ধরনের প্রশ্নের উত্তর দেয় chi-square ও ANOVA।

২ · Chi-square independence test

Chi-square testChi-Square TestKarl Pearson (১৯০০)-এর আবিষ্কার — categorical contingency table-এ observed vs expected count compare। Three flavors: goodness-of-fit, independence, homogeneity।: contingency table-এ observed vs expected count compare।

$$\chi^2 = \sum \frac{(O_i - E_i)^2}{E_i}$$

যেখানে $O$ = observed count, $E$ = independent assume করলে expected count।

উদাহরণ: ১০০০ Pathao user — লিঙ্গ ও সেবা-পছন্দ:

BikeCarFoodTotal
পুরুষ৩০০১২০৮০৫০০
নারী১৫০২০০১৫০৫০০
Total৪৫০৩২০২৩০১০০০

$H_0$: লিঙ্গ ও সেবা-পছন্দ independent। যদি independent — পুরুষ ও নারীর মধ্যে service-এর proportion একই হওয়া উচিত।

৩ · Expected count

Expected count if independent: $E_{ij} = \frac{R_i \cdot C_j}{N}$।

পুরুষ-Bike expected: $\frac{500 \times 450}{1000} = 225$। Observed ৩০০ — much higher। হয়তো dependency আছে।

৪ · Chi-square assumption

  • প্রতিটি cell-এর expected count ≥ ৫।
  • Independent observation।
  • Categorical variable।

যদি assumption ভঙ্গ — Fisher's exact test (small sample) বা Yates correction।

৫ · ANOVA — কী এবং কেন

ANOVAAnalysis of Variance (ANOVA)Ronald Fisher (১৯২০s) আবিষ্কৃত — মূলত agriculture experiment-এর জন্য। ৩+ গ্রুপের mean compare একবারে। F-statistic-ভিত্তিক — between/within variance ratio। — ৩+ গ্রুপের mean সমান কি, একবারে test।

কেন একাধিক t-test না?

  • ৪ গ্রুপ → ৬টি pairwise t-test।
  • প্রতিটি α = ০.০৫ → family-wise error ~২৬%।
  • ANOVA single test, single α — clean।

$H_0$: $\mu_1 = \mu_2 = \mu_3 = \ldots = \mu_k$।
$H_1$: অন্তত একটি pair ভিন্ন।

৬ · F-statistic

F-statisticF-statisticR.A. Fisher-এর নামে — দু'টি variance-এর ratio। Between-group / within-group। বড় F → group mean ভিন্ন।:

$$F = \frac{\text{Between-group variance}}{\text{Within-group variance}} = \frac{\text{MS}_\text{between}}{\text{MS}_\text{within}}$$

Intuition:

  • If group mean সবাই same — between-group variance ≈ within-group। F ≈ ১।
  • If group mean ভিন্ন — between-group large। F > ১।
  • F বিশাল → reject $H_0$।

৭ · ANOVA-এর assumption

  • Normality: প্রতি গ্রুপের ডেটা normal — মাঝারি n-এ CLT-এর কারণে robust।
  • Homoscedasticity: প্রতি গ্রুপের variance সমান। Levene's test দিয়ে check।
  • Independence: Observation-এর মধ্যে independence।

Violation-এ:

  • Variance unequal → Welch's ANOVA।
  • Heavily skewed → Kruskal-Wallis (non-parametric)।
  • Repeated measures → Repeated-measures ANOVA।

৮ · Post-hoc test

ANOVA "অন্তত একটি ভিন্ন" বলে — কোনটি নির্দিষ্ট বলে না। Pairwise comparison-এর জন্য:

  • Tukey HSD: সমস্ত pair compare, family-wise error control।
  • Bonferroni: α/k correction।
  • Dunnett: একটি control-এর সাথে বাকিরা।
Variable type → কোন test দু'টি variable কোন ধরনের? cat × cat Chi-square test independence / homogeneity expected ≥ 5; else Fisher exact cat × num (3+) One-way ANOVA F-test post-hoc: Tukey HSD Alternative if assumption violated Chi² → Fisher exact | ANOVA → Welch's / Kruskal-Wallis
Test বাছাই — variable-এর ধরন অনুযায়ী। ২ categorical → chi-square; ১ categorical (3+ levels) × numerical → ANOVA।

৯ · scipy দিয়ে chi-square

Python · scipy.stats
import numpy as np
from scipy import stats

# Pathao: লিঙ্গ × সেবা-পছন্দ contingency
observed = np.array([
    [300, 120, 80],   # পুরুষ:  bike, car, food
    [150, 200, 150],  # নারী
])

chi2, p, dof, expected = stats.chi2_contingency(observed)

print(f"Observed:\n{observed}")
print(f"\nExpected (if independent):\n{expected.astype(int)}")
print(f"\nChi-square : {chi2:.2f}")
print(f"df         : {dof}")
print(f"p-value    : {p:.6f}")

if p < 0.05:
    print("→ লিঙ্গ ও সেবা-পছন্দ independent নয়")
else:
    print("→ Independence reject করতে পারিনি")

    
Output-এ p অত্যন্ত ছোট হবে — পুরুষ Bike-এ over-represented, নারী Food-এ। Independence reject।

১০ · One-way ANOVA

Python · scipy + tukey
import numpy as np
from scipy import stats

np.random.seed(42)

# ৪ বিভাগের Daraz user-এর order value
dhaka     = np.random.normal(550, 150, 80)
ctg       = np.random.normal(480, 140, 70)
sylhet    = np.random.normal(420, 130, 60)
rajshahi  = np.random.normal(450, 120, 50)

# One-way ANOVA
f_stat, p_val = stats.f_oneway(dhaka, ctg, sylhet, rajshahi)

print(f"F-statistic : {f_stat:.3f}")
print(f"p-value     : {p_val:.6f}")

# Group means
for name, g in [("Dhaka", dhaka), ("Ctg", ctg),
                ("Sylhet", sylhet), ("Rajshahi", rajshahi)]:
    print(f"  {name:9s}: mean={g.mean():.0f}, n={len(g)}")

# Post-hoc Tukey (manual approximation via pairwise)
from itertools import combinations
groups = {"D": dhaka, "C": ctg, "S": sylhet, "R": rajshahi}
print("\nPairwise (Bonferroni-corrected):")
for (a, ga), (b, gb) in combinations(groups.items(), 2):
    t, p = stats.ttest_ind(ga, gb, equal_var=False)
    print(f"  {a} vs {b}: p={p*6:.4f} (×6 correction)")

    
F-statistic বড়, p তুচ্ছ — অন্তত একটি pair ভিন্ন। Post-hoc-এ দেখুন কোনটি — সাধারণত ঢাকা vs সিলেট ও চট্টগ্রাম vs সিলেট significant।

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

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

প্র ০১ Chi-square test দু'টি variable association detect করে — কিন্তু causation না। আপনি Daraz-এ "shipping speed" ও "satisfaction" association পেয়েছেন। কী conclusion সঠিক?

এই প্রশ্নটি data scientist-এর সবচেয়ে গুরুত্বপূর্ণ epistemic discipline-এর parikkha।

সঠিক conclusion:

  • "Faster shipping ও higher satisfaction-এর মধ্যে statistical association আছে" — সঠিক।
  • "দ্রুত shipping → higher satisfaction" — strong claim, evidence insufficient।
  • "Slow shipping causes dissatisfaction" — ditto।

Alternative explanations:

  • Reverse causation: High-tier user (paid more) — দ্রুত shipping পান এবং তারা platform-এ already satisfied। Cause-এর দিক উল্টো।
  • Confounding (third variable): Premium product-এ — দ্রুত shipping ও satisfaction দু'টোই higher। Product quality lurking variable।
  • Selection bias: যারা feedback দেন — biased subset। Slow shipping-এ unhappy customers usually drop, complain less।
  • Measurement issue: Satisfaction ratings 5-star — বেশিরভাগ ৫ দেয়। Variation কম।

Causation establish-এ চাই:

  • RCT (gold standard): Random কিছু order-এ artificial delay। Compare satisfaction।
  • Natural experiment: Driver shortage-এ দু'এলাকা delay হলো — control vs treated comparison।
  • Instrumental variable: Random-but-correlated cause (e.g., specific weather)।
  • DiD (Difference-in-Differences): পরিবর্তনের আগে-পরে দু'group।

Bangladesh context:

  • Daraz Big Sale-এর সময় delay বাড়ে — natural experiment।
  • রমজানে অর্ডার pattern change — confounder।
  • Pathao Pandemic — service-disruption pre/post compare।

Pragmatic action:

  • Association establish — proceed with hypothesis।
  • Domain reasoning — "logically delivery speed satisfaction-এ effect feel-able"।
  • A/B test — small intervention (express shipping option toggle)।
  • Long-term tracking — service improvement-এর effect।

Communication-এ সাবধানতা:

  • "Delivery speed predicts satisfaction" — observational, neutral।
  • "Faster delivery causes higher satisfaction" — strong claim।
  • "Reduce delivery time → satisfaction up by X%" — quantitative claim, test ছাড়া দাবি না।

মূল উপলব্ধি: Statistical test correlation দেয়; causation establish করতে experimental design বা causal inference framework চাই।

প্র ০২ "৪ গ্রুপ — pairwise t-test ৬টি; ANOVA single test।" — gain কী? Family-wise error rate কীভাবে কাজ করে এবং কখন pairwise t-test acceptable?

এই এতে ANOVA-র সবচেয়ে practical justification লুকিয়ে।

Family-wise error problem:

  • Single test-এ α = ০.০৫ → ৫% chance of false positive।
  • ৬ independent test → $1 - 0.95^6 \approx 26.5\%$ chance অন্তত একটিতে false positive।
  • "Significant!" claim করলে ১/৪ chance noise।
  • ৩০ test হলে — false positive almost guaranteed।

ANOVA এই সমস্যা solve করে:

  • Single F-test — single α = ০.০৫।
  • "কোনো group ভিন্ন" বললে ৫% false positive rate।
  • প্রতিটি specific pair-এর claim hold-back।

ANOVA significant হলে — তারপর কী?

  • Post-hoc test দিয়ে কোন group ভিন্ন তা চিহ্নিত।
  • Tukey HSD: সব pair, family-wise α = ০.০৫।
  • Bonferroni: প্রতিটি p × ৬, comparison-wise।
  • Holm: stepdown — Bonferroni-এর চেয়ে powerful।

Post-hoc-এর math (Bonferroni):

  • ৬ comparison, family-wise α = ০.০৫।
  • প্রতিটিতে α/6 = ০.০০৮৩।
  • p < ০.০০৮৩ হলে significant claim।
  • Conservative — কিন্তু safe।

কখন pairwise t-test acceptable:

  • Pre-specified: Study design-এ একটি specific pair-only interest (control vs new drug) — multiple না।
  • Hypothesis-driven: Prior theory একটি specific comparison demand করে।
  • Exploratory analysis (clearly labeled): "Hypothesis-generating" — confirmation needed।
  • Independent samples for each comparison: Different studies।

কখন pairwise problematic:

  • "Let me test all pairs and report whichever significant" — fishing।
  • "৬ test-এ একটি p < ০.০৫ — finding!" — false positive likely।
  • "Sample large, all pairs significant" — effect size verify।

Modern alternative:

  • Bayesian — credible interval, prior-aware।
  • Multilevel modeling — group structure model।
  • Permutation test — non-parametric ANOVA।

Daraz/Pathao practical:

  • ৪ city user-এর engagement compare → ANOVA + Tukey।
  • ৩ pricing tier compare → ANOVA + Dunnett (control: current price)।
  • Pre vs post update single comparison → t-test enough।

মূল উপলব্ধি: Multiple comparison — invisible inflation। ANOVA + post-hoc structured approach। Pairwise t-test আগ্রহজনক কিন্তু dangerous unless controlled।

প্র ০৩ ANOVA-এর "homoscedasticity" assumption ভাঙলে কী হয়? Levene's test, Welch's ANOVA, ও Kruskal-Wallis-এর তুলনা করুন।

ANOVA-এর assumption violations practical reality — alternative-গুলো জানা গুরুত্বপূর্ণ।

Homoscedasticity-এর গুরুত্ব:

  • Classical ANOVA assume — সব group-এর variance সমান।
  • F-test pooled variance ব্যবহার করে।
  • Variance unequal হলে — F-distribution wrong, p-value misleading।

Variance ভিন্ন হওয়ার কারণ:

  • Mean বাড়লে variance বাড়ে (Poisson-like, heteroscedasticity)।
  • Different sub-population sizes।
  • Outliers in some group।
  • Different processes underlying (e.g., experienced vs new users)।

Levene's test:

  • $H_0$: সব variance সমান।
  • Group-mean থেকে absolute deviation-এর ANOVA।
  • Robust — non-normal-এও কাজ করে।
  • p < ০.০৫ → unequal variance। Welch's-এ shift।

Welch's ANOVA:

  • F-test variant — pooled variance ব্যবহার করে না।
  • Each group-এর own variance, weighted।
  • Heteroscedasticity-এ accurate।
  • Sample size unequal হলে preferred।
  • scipy: stats.f_oneway না; manual বা pingouin.welch_anova।

Kruskal-Wallis:

  • Non-parametric — distribution assumption নেই।
  • Rank-based, mean না median compare।
  • Heavy skew, ordinal data, small sample-এ ভাল।
  • scipy: stats.kruskal।

Decision tree:

  • Visual: histograms, boxplots — distribution shapes দেখুন।
  • Levene p > ০.০৫ + roughly normal → classical ANOVA।
  • Levene p < ০.০৫, normal-ish → Welch's।
  • Heavily skewed/outlier → Kruskal-Wallis।
  • সবচেয়ে safe? — Welch's by default (no harm even if assumption hold)।

Power comparison:

  • Classical > Welch's > Kruskal — assumption met হলে।
  • Welch's most robust to heteroscedasticity।
  • Kruskal lose ~৫% power vs ANOVA-when-normal — tax for robustness।

Daraz/Pathao examples:

  • ৪ city order value compare — log-transform-এর পর ANOVA। Variance similar।
  • ৩ ride-type duration — heavily skewed, outliers — Kruskal।
  • ৫ payment method conversion — Welch's (variance-mean correlation)।

Modern recommendation:

  • Default to Welch's — minimal assumption।
  • Always visual check first।
  • Permutation test if uncertain।
  • Bayesian model — sex flexibility for hierarchical structure।

মূল উপলব্ধি: Real data rarely fit textbook assumption। Robust alternative অনায়াসে বেছে নিন — power loss small, validity gain large।

প্র ০৪ আপনি Pathao app-এ ride-type (bike/car/food) ও complaint-rate-এর association পরীক্ষা করতে চান। Chi-square আপনাকে কী বলবে এবং কী বলবে না? কীভাবে actionable insight পাবেন?

এই scenario-এ chi-square-এর strength ও limitation দু'টোই বুঝা যাবে।

Chi-square যা বলবে:

  • Ride-type ও complaint-rate independent কি না।
  • Statistically significant association আছে কি।
  • Effect size (Cramér's V) — association-এর strength।

Chi-square যা বলবে না:

  • কোন ride-type সবচেয়ে complaint-prone — শুধু "association"।
  • Cause-effect — কেন এই pattern।
  • Direction of effect।
  • Magnitude actual (count vs percentage)।
  • Time trend — সম্পর্ক বদলাচ্ছে কি না।

Actionable insight পেতে:

  1. (১) Standardized residuals:
    • প্রতি cell-এ $(O - E) / \sqrt{E}$।
    • |residual| > ২ → notably high/low cell।
    • "Bike-এ complaint expected-এর চেয়ে ৩০% বেশি" — এই specifics।
  2. (২) Cramér's V (effect size):
    • $V = \sqrt{\chi^2 / [n \cdot (k-1)]}$।
    • 0.1 small, 0.3 medium, 0.5 large।
    • "Significant but trivially small" — possible।
  3. (৩) Subgroup analysis:
    • Time-of-day, route, driver experience — control।
    • "Bike-night-এ complaint 5×" — actionable।
  4. (৪) Mosaic plot বা heatmap:
    • Visual inspection — pattern সরাসরি।
    • Stakeholder communication।

Pathao-specific applications:

  • Operations: Food delivery-এ complaint বেশি হলে — packaging, restaurant partnership audit।
  • Driver training: Bike-এ আক্রান্ত — safety briefing, GPS routing improvement।
  • Pricing: Car-এ price sensitivity high — complaint correlate-এর সাথে।
  • UX: App-এ complaint-prone scenarios-এ proactive support।

Beyond chi-square:

  • Logistic regression: complaint (yes/no) ~ ride-type + controls।
  • Predict complaint probability per ride-type, conditional on covariates।
  • Deeper causal inference — A/B test new packaging on food।

Reporting template:

  • "Chi-square: $\chi^2$ = ৪৮.২, p < ০.০০১, V = ০.১৪ (small effect)।"
  • "Standardized residuals — Food highest +৩.১, Car lowest −২.৪।"
  • "Recommendation: food-delivery operation review; specific drivers/routes-এ deep dive।"

Common mistakes:

  • "Significant!" → directly action। Effect size check।
  • Sample very large → trivial association significant। Cramér's V verify।
  • Not adjusting for confounders।

মূল উপলব্ধি: Chi-square — gateway test। Significant হলে — actionable detail-এ যান (residual, effect size, sub-group)। Significant না হলে — null finding-ও business-relevant।

অনুশীলন

  1. Test বাছুন: প্রতিটি scenario-এ chi-square না ANOVA?
    • (ক) ৫টি Daraz product-category × payment-method (cash/digital)।
    • (খ) ৩ city × মাসিক gym attendance (numerical hours)।
    • (গ) Pre-paid vs post-paid × Grameenphone churn।
    • (ক) Chi-square — categorical × categorical।
    • (খ) ANOVA — categorical (city) × numerical (hours)।
    • (গ) Chi-square — দু'টি categorical।
  2. Chi-square in scipy: ২×৩ contingency [[৫০, ৩০, ২০], [৪০, ৪০, ৩০]] — independence test।
    import numpy as np
    from scipy import stats
    table = np.array([[50, 30, 20], [40, 40, 30]])
    chi2, p, dof, exp = stats.chi2_contingency(table)
    print(f"chi2={chi2:.2f}, p={p:.4f}, dof={dof}")

    p ≈ ০.১৩ — significant না। Independence reject করতে পারিনি।

  3. ভাবুন: ৪ region-এর Daraz user-এর order frequency compare করতে চান। কোন test, কোন assumption-check, কোন post-hoc?
    1. Visual — boxplot, histogram per region।
    2. Levene's test — variance equal?
    3. Equal → ANOVA; unequal → Welch's; heavily skewed → Kruskal-Wallis।
    4. Significant → Tukey HSD post-hoc।
    5. Effect size — η² (eta-squared)।

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

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