#!/usr/bin/env python3 """ PAIRED t-TEST (step-by-step, exam style) ========================================= Course : COMP 4112 Intro to Data Science, Unit 08b "Hypothesis Testing" Slides : pages 23-25 (concept p.23, worked numbers p.24, vertical-jump data p.25) QUESTION ANSWERED Do two MEASUREMENTS ON THE SAME SUBJECTS (before/after) differ on average? Reduce to one sample of differences d_i = after_i - before_i and do a one-sample t-test of H0: mu_d = 0. FORMULAS d_i = after_i - before_i d_bar = mean(d), s_d = sample SD of d (n-1 divisor) SE(d_bar) = s_d / sqrt(n) t = d_bar / SE(d_bar), df = n - 1 Reject H0 if |t| > t_crit (two-sided) <=> p < alpha SLIDE p.24 NUMBERS (data table not in slides): d_bar = 2.05, s_d = 2.837, n = 20 SE = 2.837/sqrt(20) = 0.634, t = 3.231 on 19 df, t_crit = 2.093 -> reject. Reproduce with --example slide24 (summary-stats mode). HOW TO RUN python3 u08b_paired_t_test.py # slide p.25 vertical-jump data python3 u08b_paired_t_test.py --example slide24 # slide p.24 summary stats python3 u08b_paired_t_test.py --before 22,20,19 --after 24,22,19 --alternative greater python3 u08b_paired_t_test.py --dbar 2.05 --sd 2.837 --n 20 python3 u08b_paired_t_test.py --csv d.csv --cols before,after python3 u08b_paired_t_test.py --interactive Note: the slide p.25 table lists Difference = BEFORE - AFTER; here d = AFTER - BEFORE (positive = improvement), so the sign of t is opposite; |t| and p are identical. R <-> PYTHON CHEAT SHEET (slides 23-25; slide formulas SE(d)=s_d/sqrt(n), T=d_bar/SE(d)) R Python (this file) Meaning d <- after - before d = after - before pair differences mean(d); sd(d) d.mean(); d.std(ddof=1) d_bar and s_d (n-1) se <- sd(d)/sqrt(n) sd/math.sqrt(n) SE(d_bar) = 2.837/sqrt(20) = 0.634 on slide t <- mean(d)/se dbar/se t = 2.05/0.634 = 3.231, df = 19 qt(0.975, 19) (=2.093) stats.t.ppf(0.975, 19) critical value t.test(after, before, paired=TRUE) stats.ttest_rel(after, before) library call GOTCHAS: order matters: after-before flips the sign of t (p unchanged); pass paired=TRUE in R or it runs Welch on independent groups. Paired df = n-1 (number of pairs), not 2n-2. "Increase" => alternative="greater". """ import argparse import math import sys import numpy as np from scipy import stats # ---------------------------------------------------------------------------- # EDIT HERE: defaults = slide p.25 (max vertical jump, inches, 20 players) # ---------------------------------------------------------------------------- DATA = { "before": [22, 20, 19, 24, 25, 25, 28, 22, 30, 27, 24, 18, 16, 19, 19, 28, 24, 25, 25, 23], "after": [24, 22, 19, 22, 28, 26, 28, 24, 30, 29, 25, 20, 17, 18, 18, 28, 26, 27, 27, 24], "alpha": 0.05, "alternative": "two-sided", # use "greater" for "did training INCREASE the jump?" } def parse_list(text): """Turn '1, 2,3' into floats.""" return [float(v) for v in text.replace(",", " ").split()] def p_value(t, df, alt): """Tail probability for the chosen alternative.""" # R: 2 * pt(abs(t), df, lower.tail = FALSE) WHY: sf = P(T > |t|); x2 for two tails. if alt == "two-sided": return 2 * stats.t.sf(abs(t), df) return stats.t.sf(t, df) if alt == "greater" else stats.t.cdf(t, df) def crit(alpha, df, alt): """t-table critical value.""" # R: qt(1 - alpha/2, df) WHY: t-table lookup (ppf == qt). if alt == "two-sided": return stats.t.ppf(1 - alpha / 2, df) return stats.t.ppf(1 - alpha, df) if alt == "greater" else stats.t.ppf(alpha, df) def synthetic_sample(n, mean, sd): """Build a sample of size n whose mean and sample SD (n-1) are EXACTLY mean and sd. Used so scipy's raw-data t-test can independently check summary-statistic input.""" z = np.arange(n, dtype=float) z = (z - z.mean()) / z.std(ddof=1) # standardize: mean 0, sd 1 return mean + sd * z def pick_columns(df, cols, k): """Return k column names: those given in --cols, else the first k numeric columns (clear error if none).""" if cols: names = [c.strip() for c in cols.split(",")] missing = [c for c in names if c not in df.columns] if len(names) < k or missing: sys.exit(f"--cols must name {k} existing column(s); problem with {missing or names}. CSV has: {list(df.columns)}") return names[:k] num = list(df.select_dtypes("number").columns) if len(num) < k: sys.exit(f"--csv needs {k} numeric column(s) (or --cols); found {num}.") print(f"(no --cols given: using first numeric column(s) {num[:k]})") return num[:k] def paired_t(n, dbar, sd, alpha, alt, before=None, after=None, flip=False): """Hand-compute the paired t-test from n, d_bar, s_d; cross-check scipy if raw pairs given.""" sym = {"two-sided": "!=", "greater": ">", "less": "<"}[alt] if sd < 0: sys.exit(f"--sd must be >= 0 (got {sd}).") if sd == 0 or n < 2: print(f"SD of differences = {sd} (n = {n}) -> SE = 0, t undefined; the test cannot be run.") return None print("=" * 70 + "\nPAIRED t-TEST - step by step\n" + "=" * 70) print("\nASSUMPTIONS CHECKLIST (slide 21) - state these on the exam; the test is valid only if:\n" " [ ] observations are INDEPENDENT (values not related to one another)\n" " [ ] data are CONTINUOUS (numeric measurements, not categories)\n" " [ ] data come from a SIMPLE RANDOM SAMPLE of the population\n" " [ ] (small n) data roughly normal / no extreme outliers; each PAIR is independent of other pairs; differences roughly normal") print(f"\nSTEP 1 Hypotheses\n H0: mu_d = 0 (true mean difference is zero)\n H1: mu_d {sym} 0 ({alt}); d = {'before - after' if flip else 'after - before'}") print(f"\nSTEP 2 alpha = {alpha}") if before is not None: d = (before - after) if flip else (after - before) print(f"\nSTEP 3 Differences d_i = {'before_i - after_i' if flip else 'after_i - before_i'}:\n {d.astype(float).tolist()}") print(f"\nSTEP 4 n = {n} pairs\n d_bar = {dbar:.4f}\n s_d = {sd:.4f}") # R: sd(d)/sqrt(n) WHY: SE of the mean difference; a paired test is a one-sample test on d. se = sd / math.sqrt(n) # SE of mean difference print(f"\nSTEP 5 SE(d_bar) = s_d/sqrt(n) = {sd:.4f}/sqrt({n}) = {se:.4f}") t = dbar / se # null value of mean difference is 0 print(f"\nSTEP 6 t = d_bar/SE = {dbar:.4f}/{se:.4f} = {t:.4f}") df = n - 1 print(f"\nSTEP 7 df = n - 1 = {df}") tc = crit(alpha, df, alt) print(f"\nSTEP 8 Critical value = {'+/-' if alt == 'two-sided' else ''}{tc:.4f}") p = p_value(t, df, alt) print(f"\nSTEP 9 p-value = {p:.6f}") rej = p < alpha if alt == "two-sided": cmp = f"|t| = {abs(t):.3f} {'>' if abs(t) > tc else '<='} {tc:.3f}" elif alt == "greater": cmp = f"t = {t:.3f} {'>' if t > tc else '<='} {tc:.3f}" else: cmp = f"t = {t:.3f} {'<' if t < tc else '>='} {tc:.3f}" print(f"\nSTEP 10 Decision: p {'<' if rej else '>='} alpha -> {'REJECT H0' if rej else 'FAIL TO REJECT H0'} ({cmp})") print("\nSTEP 11 Conclusion\n " + ("There IS a significant difference between before and after (mean change = %.3f)." % dbar if rej else "No significant difference between before and after.")) print(f"\nCROSS-CHECK (R: t.test({'before, after' if flip else 'after, before'}, paired=TRUE))") if before is not None: # R: t.test(after, before, paired = TRUE) # WHY: ttest_rel pairs element i of each array and tests the differences against 0. r = stats.ttest_rel(*((before, after) if flip else (after, before)), alternative=alt) ok = math.isclose(r.statistic, t, rel_tol=1e-9) and math.isclose(r.pvalue, p, rel_tol=1e-7) print(f" scipy.stats.ttest_rel: t = {r.statistic:.4f}, p = {r.pvalue:.6f}") else: # Summary stats only: INDEPENDENT check = synthetic differences with exactly this n, mean, SD, # tested against 0 with scipy's one-sample t-test (separate code path from the hand calculation). r = stats.ttest_1samp(synthetic_sample(n, dbar, sd), 0.0, alternative=alt) ok = math.isclose(r.statistic, t, rel_tol=1e-6) and math.isclose(r.pvalue, p, rel_tol=1e-6) print(f" [synthetic differences, same n, d_bar, s_d] scipy.stats.ttest_1samp(d, 0): t = {r.statistic:.4f}, p = {r.pvalue:.6f}") print(f" Hand calculation {'MATCHES' if ok else 'DOES NOT MATCH'} the library.") if before is not None: print("\nNOTE (slide p.25): the slide's Difference column is BEFORE - AFTER (mostly negative). With d = %s the sign of d_bar and t is %s,\n" " but |t|, df and the p-value are identical for a two-sided test, so the conclusion is the same. Use --diff before-after to match the slide." % ('before - after (slide convention)' if flip else 'after - before (this script default)', 'as on the slide' if flip else 'opposite to the slide')) def main(): ap = argparse.ArgumentParser(description="Paired t-test, step by step.", epilog="Negative values: use --before=-1,-2, --after=-3,-4 or --dbar=-1 (with =), otherwise argparse treats them as flags.") ap.add_argument("--before", help="values before, comma separated (default: slide p.25 data)"); ap.add_argument("--after", help="values after, same order and length as --before (default: slide p.25 data)") ap.add_argument("--csv", help="path to CSV with paired columns (default: none)"); ap.add_argument("--cols", help="column names before,after in the CSV (default: none)") ap.add_argument("--dbar", type=float, help="summary mode: mean of differences (default: none)"); ap.add_argument("--sd", type=float, help="summary mode: SD of differences s_d (default: none)"); ap.add_argument("--n", type=int, help="summary mode: number of pairs (default: none)") ap.add_argument("--alpha", type=float, help="significance level (default: 0.05)"); ap.add_argument("--alternative", choices=["two-sided", "greater", "less"], help="tail of H1; greater = after > before (default: two-sided)") ap.add_argument("--example", choices=["jump", "slide24"], default="jump", help="jump = slide p.25 data, slide24 = p.24 summary stats (default: jump)") ap.add_argument("--diff", choices=["after-before", "before-after"], default="after-before", help="sign convention of d: slide p.25 table uses before-after. Two-sided: |t| and p are identical, only the sign of t/d_bar flips. One-sided: with before-after, 'greater' means before > after, so p differs from after-before (default: after-before)") ap.add_argument("--interactive", action="store_true", help="prompt for values with input() instead of flags (default: off)") a = ap.parse_args() d = dict(DATA); summ = None if a.example == "slide24": summ = (20, 2.05, 2.837) if a.interactive: raw = input("Before values (blank = summary stats instead): ").strip() if raw: d["before"] = parse_list(raw); d["after"] = parse_list(input("After values: ")) else: summ = (int(input("n = ")), float(input("d_bar = ")), float(input("s_d = "))) d["alpha"] = float(input("alpha [0.05]: ") or 0.05) d["alternative"] = input("alternative two-sided/greater/less [two-sided]: ").strip() or "two-sided" else: if a.before: d["before"], summ = parse_list(a.before), None if a.after: d["after"] = parse_list(a.after) if a.csv: import pandas as pd df = pd.read_csv(a.csv); c1, c2 = pick_columns(df, a.cols, 2) df = df[[c1, c2]].dropna() # drop incomplete pairs d["before"], d["after"], summ = df[c1].tolist(), df[c2].tolist(), None if (a.dbar, a.sd, a.n).count(None) not in (0, 3): sys.exit("Summary-stats mode needs all of --dbar, --sd and --n.") if a.dbar is not None: summ = (a.n, a.dbar, a.sd) if a.alpha is not None: d["alpha"] = a.alpha if a.alternative: d["alternative"] = a.alternative if summ: paired_t(summ[0], summ[1], summ[2], d["alpha"], d["alternative"]) else: b, af = np.array(d["before"], float), np.array(d["after"], float) if len(b) != len(af) or len(b) < 2: sys.exit("before and after must have the same length (>= 2).") # R: d <- after - before; mean(d); sd(d) WHY ddof=1: sample SD (n-1) like R's sd(). flip = a.diff == "before-after" # slide p.25 convention: Difference = before - after diff = (b - af) if flip else (af - b) paired_t(len(b), diff.mean(), diff.std(ddof=1), d["alpha"], d["alternative"], b, af, flip) if __name__ == "__main__": try: main() except EOFError: sys.exit("--interactive needs typed input, but stdin is closed.")