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

Inferential Statistics — Hypothesis Testing

Lesson opener

In one line: How to frame null and alternative hypotheses for business experiments. What a p-value actually measures - and what it cannot tell you. How to run and interpret an independent-samples t-test when comparing two group avera.

Why it matters: This shows up at work when you need to how to frame null and alternative hypotheses for business experiments. What a p-value actually measures - and what it cannot tell you. How to run and interpret an independent-sample

Before this lesson: Foundations / Relationships

Before you start

ResourceLink
GlossaryStatistics glossary
PreviousRelationships
NextApplied ML statistics
PrerequisitesFoundations, Relationships
Time~45 minutes

What you will learn

How to frame null and alternative hypotheses for business experiments. What a p-value actually measures — and what it cannot tell you. How to run and interpret an independent-samples t-test when comparing two group averages.

A/B test decision cheat sheet
A/B test decision cheat sheet
Statistics for data science cheat sheet
Statistics for data science cheat sheet

Null Hypothesis and Alternative Hypothesis

Layer 1 — Plain English Definition

A hypothesis test starts with two competing stories about the world. The null hypothesis is the sceptic’s default: nothing special happened, the new checkout is the same as the old one, the training programme changed nothing. The alternative hypothesis is the claim you want evidence for: there is a difference, an improvement, or a drop. You collect data, compute a test statistic, and ask how compatible your results are with the null story. You never “prove” the alternative — you only gather evidence strong enough to reject the sceptic’s default.

Layer 2 — Real Life Analogy

A Delhi quick-commerce ops manager rolls out a new picker routing app in five dark stores (treatment) and leaves five matched stores on the old app (control). The null story: “Average orders per hour is the same with or without the new app — any gap is just daily noise.” The alternative: “The new app changes average orders per hour.” The experiment is the referee between those two stories.

Layer 3 — Visual (SVG diagram)

Two competing stories H₀ Null No real change H₁ Alternative Real difference Collect data → compute test → compare to H₀

Layer 4 — Terminology Table

TermSymbolPlain English Meaning
Null hypothesisH₀Default claim: no effect, no difference
Alternative hypothesisH₁ (or Hₐ)Claim you seek evidence for: there is an effect
Significance levelαCutoff for “unusual enough” (often 0.05)
Test statistict, z, etc.Number summarising how far data sits from H₀
Reject H₀—Data is inconsistent enough with “no change”
Fail to reject H₀—Not enough evidence to abandon the sceptic’s story

Layer 5 — Hand Calculation

Experiment: Five control stores vs five treatment stores — daily orders per hour.

Step 1 — State hypotheses

Step 2 — Group means

Step 3 — Is this surprising if H₀ were true?

Under H₀ we expect means to differ only by sampling noise. With n = 5 per group and low spread, a 2.0 gap is large relative to each group’s variation (values only swing between 8–9 vs 10–11). That is the intuition the formal t-test quantifies in the next section.

Now verify this in Python:

Layer 6 — Formula with Symbol Breakdown

Hypothesis pair (two-sided mean difference):

SymbolWhat it isWhat it doesWhy it is there
μ₁True mean of treatment populationThe unknowable average if we ran the app everywhereDefines what we compare against control
μ₂True mean of control populationBaseline world without the changeAnchor for “no effect”
H₀Null statementClaims μ₁ = μ₂Gives a precise sceptic story to test
H₁Alternative statementClaims means differMatches the business question (“did the app help?”)
αSignificance levelMaximum false-alarm rate you tolerateTurns test output into a yes/no decision rule

Layer 7 — Python Verification

control = [8, 9, 8, 9, 8]
treatment = [10, 11, 10, 11, 10]

mean_c = sum(control) / len(control)
mean_t = sum(treatment) / len(treatment)

print(f"H0: no difference in means")
print(f"H1: means differ")
print(f"Control mean:   {mean_c:.1f}")
print(f"Treatment mean: {mean_t:.1f}")
print(f"Observed gap:   {mean_t - mean_c:.1f}")

Expected output:

H0: no difference in means
H1: means differ
Control mean:   8.4
Treatment mean: 10.4
Observed gap:   2.0

Layer 8 — Real Dataset Application

An Indian ed-tech pilot: five classrooms use a new Hindi quiz app (treatment); five matched classrooms use worksheets only (control). Outcome: average quiz score (0–15).

import pandas as pd

df = pd.DataFrame({
    "classroom": ["C1","C2","C3","C4","C5","T1","T2","T3","T4","T5"],
    "group": ["control"]*5 + ["treatment"]*5,
    "score": [8, 9, 8, 9, 8, 10, 11, 10, 11, 10],
})

summary = df.groupby("group")["score"].agg(["mean", "count"])
print(summary)
print("\nH0: app does not change mean score")
print("H1: app changes mean score")
print(f"Lift: {summary.loc['treatment','mean'] - summary.loc['control','mean']:.1f} points")

Interpretation: Treatment averages 10.4 vs control 8.4 — a 2-point lift. Before telling the state partner “roll out statewide,” you still need a p-value (next section) and a rupee-per-student cost story. Hypotheses frame the question; they do not finish the decision.

Layer 9 — Common Mistakes

❌ Wrong: Write H₁ as “the new app improves scores” but run a two-sided test without realising you wanted a one-sided “improvement only” question.

✅ Right: Match H₁ to the business claim before collecting data — two-sided for “any change,” one-sided for “improvement only.”

💡 Why: Changing direction after seeing data inflates false positives — “HARKing” (hypothesising after results are known).

❌ Wrong: Treat “fail to reject H₀” as proof that nothing changed.

✅ Right: Say “we lack evidence of a change” — maybe the sample was too small or the effect too tiny to detect.

💡 Why: Absence of evidence is not evidence of absence; small pilots often cannot see real but modest lifts.

Layer 10 — ML Connection

When you compare two recommendation models on holdout click-through rate, you implicitly set H₀: “both models have the same true CTR.” Offline A/B analysis on logged data uses the same logic as store pilots — if you skip stating H₀/H₁, teams debate “model B is 0.3% better” without asking whether that gap exceeds random split noise. Frame the comparison before peeking at dashboards.


p-value

Layer 1 — Plain English Definition

The p-value answers one narrow question: if the null hypothesis were true — if there really were no difference — how often would we see a gap as large as the one we observed, or even larger, just because of random luck? A very small p-value means “this would be a rare outcome under the sceptic’s story,” so the sceptic story looks shaky. A large p-value means “a gap this size could easily happen by chance,” so you do not have strong grounds to reject the null. The p-value is not the probability that your hypothesis is true, and it says nothing about business impact in rupees.

Layer 2 — Real Life Analogy

You flip a coin 10 times and get 9 heads. The p-value asks: if the coin were fair (H₀), how often would you see 9 or 10 heads? Not often — so you suspect the coin. But if you got 6 heads, that happens all the time with a fair coin — high p-value, no reason to accuse the coin. Same logic for “treatment mean beat control by this much.”

Layer 3 — Visual (SVG diagram)

If H₀ were true — how extreme is our result? Observed gap p = tail area Common outcomes (high p) Rare outcomes (low p)

Layer 4 — Terminology Table

TermSymbolPlain English Meaning
p-valuepProbability of seeing data this extreme if H₀ is true
Significance levelαPre-set cutoff (often 0.05) for calling result “significant”
Statistically significantp < αUnusual enough under H₀ to reject the sceptic story
Effect size—Actual size of difference (points, ₹, %) — separate from p
Type I error—Rejecting H₀ when it was actually true (false alarm)

Layer 5 — Hand Calculation

Same experiment: control [8, 9, 8, 9, 8], treatment [10, 11, 10, 11, 10]

Step 1 — Means (from previous section)

Step 2 — Variability in each group

Control deviations from 8.4: −0.4, +0.6, −0.4, +0.6, −0.4

Treatment deviations from 10.4: same pattern → s²_t = 0.30, s_t ≈ 0.548

Step 3 — t-statistic (preview of next section)

\[

t = \frac{\bar{x}_t - \bar{x}_c}{s_p\sqrt{\frac{1}{n_t}+\frac{1}{n_c}}}

\]

Step 4 — p-value intuition

With t ≈ 5.77 and 8 degrees of freedom, the tail probability is tiny — about 0.0004 (0.04%). Under “no real difference,” a gap this large is very unlikely. At α = 0.05, we reject H₀.

Now verify this in Python:

Layer 6 — Formula with Symbol Breakdown

Decision rule (two-sided):

SymbolWhat it isWhat it doesWhy it is there
pp-valueMeasures compatibility of data with H₀Single number teams recognise
αSignificance levelYour false-alarm tolerancePrevents moving the goalposts after seeing p
tTest statisticStandardised distance between groupsFeeds into p via t-distribution
dfDegrees of freedomn₁ + n₂ − 2 for independent t-testAdjusts tail areas for sample size

Layer 7 — Python Verification

SciPy is Python's core library for scientific computing; here we use its stats module to run the actual hypothesis test instead of hand-calculating the p-value.

from scipy import stats

control = [8, 9, 8, 9, 8]
treatment = [10, 11, 10, 11, 10]

t_stat, p_value = stats.ttest_ind(treatment, control)

print(f"t-statistic: {t_stat:.2f}")
print(f"p-value:     {p_value:.4f}")
print(f"Significant at 5%? {p_value < 0.05}")

Expected output:

t-statistic: 5.77
p-value:     0.0004
Significant at 5%? True

Layer 8 — Real Dataset Application

A Hyderabad fintech runs a two-week UPI cashback test. Control: 500 users, 3.8% conversion. Treatment: 500 users, 4.2% conversion. Analytics runs a proportion test; p = 0.03.

def experiment_report(control_rate, treatment_rate, p_value, monthly_lift_lakh):
    alpha = 0.05
    sig = "statistically significant" if p_value < alpha else "not statistically significant"
    print(f"Control:   {control_rate:.1%}")
    print(f"Treatment: {treatment_rate:.1%}")
    print(f"Lift:      {(treatment_rate - control_rate)*100:.1f} pp")
    print(f"p-value:   {p_value:.3f} ({sig} at α={alpha})")
    print(f"Est. monthly impact: ₹{monthly_lift_lakh:.1f} lakh")
    if p_value < alpha and monthly_lift_lakh > 2:
        print("Recommendation: staged rollout")
    else:
        print("Recommendation: extend test or revisit design")

experiment_report(0.038, 0.042, 0.03, 8.5)

Interpretation: p = 0.03 < 0.05 — under “no effect,” a lift this large is uncommon. But also ask: is +0.4 pp worth ₹8.5 lakh/month after cashback cost? p-value supports “likely real”; finance supports “worth doing.”

Layer 9 — Common Mistakes

❌ Wrong: Tell leadership “p = 0.03 means a 97% chance the app works.”

✅ Right: Say “if there were truly no effect, we’d see a gap this large only about 3% of the time.”

💡 Why: p is about the data given H₀, not about H₁ being true — a common misread that over-sells results.

❌ Wrong: Ignore effect size because p < 0.05 and launch nationwide.

✅ Right: Pair p-value with lift in rupees, conversion points, or orders/hour — practical significance.

💡 Why: Huge samples make tiny, useless differences “significant”; small samples miss big wins.


❌ Wrong: Run the test, peek daily, and stop the moment p < 0.05.

✅ Right: Pre-specify sample size and duration; use proper sequential methods if you must peek.

💡 Why: Repeated peeking inflates false positives — you will “find significance” by accident.

Layer 10 — ML Connection

After retraining a fraud classifier, you see validation AUC rise from 0.912 to 0.915 with p = 0.02 on a bootstrap test. The p-value says the bump is unlikely under “models are equally good” — but 0.003 AUC may stop zero fraudulent UPI transactions at scale. ML deployment gates should require both statistical evidence and a threshold on blocked fraud value (₹), not p alone.


t-test (independent samples)

Layer 1 — Plain English Definition

The independent-samples t-test compares the average of one group to the average of another when observations in group A are not paired with specific observations in group B — different stores, different users, different batches. It asks whether the observed mean difference is large relative to the natural spread inside each group and relative to how small the samples are. The output is a t-statistic and a p-value you can plug into the hypothesis framework above.

Layer 2 — Real Life Analogy

Five Swiggy cloud kitchens try a new packaging that keeps biryani hotter; five matched kitchens keep old packaging. Each kitchen reports average delivery rating that week. The t-test compares the two group averages — kitchens are independent, not the same rider measured twice.

Layer 3 — Visual (SVG diagram)

Independent samples t-test Control x̄ = 8.4 n = 5 Treatment x̄ = 10.4 n = 5 Δ = 2.0 t = gap ÷ standard error → p-value

Layer 4 — Terminology Table

TermSymbolPlain English Meaning
Independent samples—Two separate groups, not paired row-by-row
t-statistictMean difference measured in “noise units”
Pooled std devs_pCombined spread estimate from both groups
Standard errorSETypical variability of a mean difference
Degrees of freedomdfn₁ + n₂ − 2 for equal-variance t-test
Two-sample t-test—scipy: stats.ttest_ind

Layer 5 — Hand Calculation

Control: [8, 9, 8, 9, 8] → x̄_c = 8.4

Treatment: [10, 11, 10, 11, 10] → x̄_t = 10.4

Step 1 — Sample variances (ddof = 1)

Control squared deviations sum = 1.20 → s²_c = 1.20 ÷ 4 = 0.30

Treatment: identical pattern → s²_t = 0.30

Step 2 — Pooled variance

Step 3 — Standard error of the difference

Step 4 — t-statistic

Step 5 — p-value

With df = 8, |t| = 5.77 lies far in the tail → p ≈ 0.0004 → reject H₀ at α = 0.05.

Now verify this in Python:

Layer 6 — Formula with Symbol Breakdown

Independent two-sample t-statistic (equal variance):

\[

t = \frac{\bar{x}_1 - \bar{x}_2}{s_p\sqrt{\frac{1}{n_1}+\frac{1}{n_2}}}

\]

\[

s_p^2 = \frac{(n_1-1)s_1^2 + (n_2-1)s_2^2}{n_1+n_2-2}

\]

SymbolWhat it isWhat it doesWhy it is there
x̄₁, x̄₂Sample meansNumerator — raw gap observedWhat the business cares about first
s_pPooled standard deviationEstimates common spreadMore stable than either group alone when spreads are similar
n₁, n₂Group sizesInside SE formulaLarger n → smaller SE → easier to detect real gaps
dfn₁ + n₂ − 2For t-distributionSmall samples need wider tails

Layer 7 — Python Verification

from scipy import stats

control = [8, 9, 8, 9, 8]
treatment = [10, 11, 10, 11, 10]

t_stat, p_value = stats.ttest_ind(treatment, control)

print(f"Control mean:   {sum(control)/len(control):.1f}")
print(f"Treatment mean: {sum(treatment)/len(treatment):.1f}")
print(f"t-statistic:    {t_stat:.2f}")
print(f"p-value:        {p_value:.4f}")

Expected output:

Control mean:   8.4
Treatment mean: 10.4
t-statistic:    5.77
p-value:        0.0004

Layer 8 — Real Dataset Application

A Chennai manufacturing line tests a new preventive maintenance schedule on five machines (treatment) vs five machines on the old schedule (control). Outcome: downtime hours per week.

import pandas as pd
from scipy import stats

df = pd.DataFrame({
    "machine": ["M1","M2","M3","M4","M5","M6","M7","M8","M9","M10"],
    "group": ["control"]*5 + ["treatment"]*5,
    "downtime_hrs": [8, 9, 8, 9, 8, 10, 11, 10, 11, 10],
})

ctrl = df.loc[df["group"]=="control", "downtime_hrs"]
treat = df.loc[df["group"]=="treatment", "downtime_hrs"]

t, p = stats.ttest_ind(treat, ctrl)
print(f"Control avg:   {ctrl.mean():.1f} hrs")
print(f"Treatment avg: {treat.mean():.1f} hrs")
print(f"t = {t:.2f}, p = {p:.4f}")
print(f"Saved {treat.mean() - ctrl.mean():.1f} hrs/week — wait, higher is worse!")
print("Re-code: lower downtime is better — here treatment is WORSE; do not roll out.")

Interpretation: Means differ significantly (p ≈ 0.0004) but direction matters — if treatment increases downtime, significance tells you the change is real, not that it is good. Always align the metric with business preference.

Layer 9 — Common Mistakes

❌ Wrong: Use ttest_ind when the same ten employees are measured before and after training (paired data).

✅ Right: Use stats.ttest_rel for paired measurements; ttest_ind only when groups are independent.

💡 Why: Pairing removes person-to-person noise; ignoring pairs wastes power or gives wrong p-values.

❌ Wrong: Run t-tests on binary yes/no outcomes with tiny samples.

✅ Right: Use proportion tests or chi-square for conversion; t-test assumes roughly continuous, normal-ish outcomes.

💡 Why: Click/no-click is not “average of a bell curve” — wrong tool, misleading p.


❌ Wrong: Assume equal variance without checking; always use default equal_var=True.

✅ Right: Compare spreads (boxplots, std); use equal_var=False (Welch) when variances differ sharply.

💡 Why: Very different group spreads distort the pooled t-test.

Layer 10 — ML Connection

To compare two forecast models’ per-store weekly error on holdout data (independent stores), collect MAE per store for model A and model B and run ttest_ind on the error vectors. A significant p-value means one model’s average error is consistently lower — but deploy only if the MAE gap covers retraining cost. The t-test is the statistical layer on top of a business ROI check.


Essential commands

Command / actionWhat it does
stats.ttest_ind(a, b)Independent two-sample t-test
stats.ttest_rel(before, after)Paired t-test (same units twice)
p_value < 0.05Common significance cutoff (not sacred)
State H₀ / H₁ firstFrames every p-value you report

Practice

Do this now: Using control [8, 9, 8, 9, 8] and treatment [10, 11, 10, 11, 10], write H₀ and H₁ in plain English. Compute both means, pooled standard deviation, t-statistic, and p-value by hand. Verify with stats.ttest_ind. Then write four sentences for a manager: what you tested, what you saw, statistical evidence, and business recommendation (include effect size even if p is small).

Checklist

  • [ ] Can you state H₀ and H₁ for a store pilot without jargon?
  • [ ] Can you compute control mean 8.4 and treatment mean 10.4 from the practice data?
  • [ ] Can you define p-value as a “surprise if H₀ were true” score?
  • [ ] Can you name two things a p-value does not tell you?
  • [ ] Can you hand-compute t ≈ 5.77 and p ≈ 0.0004 for the practice groups?
  • [ ] Can you run stats.ttest_ind and pair results with a rupee or operational impact?