5.4.14Scientific Computing (Python)

scipy.stats — distributions, hypothesis tests

1,998 words9 min readdifficulty · medium

WHY does this module exist?

WHAT you actually compute every time:

  • "How likely is exactly this value?" → density (PDF).
  • "How likely is up to this value?" → cumulative (CDF).
  • "What value sits at the 95th percentile?" → quantile (PPF).
  • "Is my observed effect surprising?" → p-value.

The four functions, derived from one idea

from scipy import stats
n = stats.norm(loc=0, scale=1)      # mean 0, sd 1
n.pdf(0)        # 0.3989  height of the bell at center
n.cdf(1.96)     # 0.9750  area to the left of 1.96
n.sf(1.96)      # 0.0250  area to the right (= 1 - cdf)
n.ppf(0.975)    # 1.96    inverse of cdf
n.rvs(size=5)   # 5 random samples

Standardizing: the z-score, derived


Hypothesis testing, from scratch

data = [5.1, 4.9, 5.3, 5.0, 4.8]
stats.ttest_1samp(data, popmean=5.0)
# TtestResult(statistic=-0.0, pvalue=1.0)  -> no evidence mean ≠ 5

Worked examples


Common mistakes


Recall Feynman: explain to a 12-year-old

Imagine a bag of marbles where some sizes are common and some rare. A distribution is the rulebook saying how common each size is. The PDF is "how popular is exactly this size," the CDF is "how many marbles are this size or smaller." A hypothesis test is like a friend claiming the bag is "all medium marbles." You grab a handful: if you keep pulling giants, you say "no way that's just luck — your claim is wrong!" The p-value is how often pure luck could have given you a handful this weird. Tiny p = "luck can't explain this" = your friend was wrong.


Flashcards

What does stats.norm.cdf(x) return?
P(Xx)P(X \le x), the area under the PDF to the left of xx.
What does .sf(x) compute and why prefer it over 1-cdf?
The survival function P(X>x)=1F(x)P(X>x)=1-F(x); it's numerically more accurate in the far right tail.
What is the PPF (.ppf(p))?
The inverse CDF: the value xx where F(x)=pF(x)=p — i.e. the pp-quantile.
Define a p-value precisely.
P(a test statistic at least as extreme as observedH0 true)P(\text{a test statistic at least as extreme as observed} \mid H_0 \text{ true}).
Why divide by n\sqrt n in the standard error?
Variance of a sample mean is σ2/n\sigma^2/n, so its sd is σ/n\sigma/\sqrt n; averaging nn values shrinks noise.
Derive the t-statistic for a one-sample test.
t=(xˉμ0)/(s/n)t=(\bar x-\mu_0)/(s/\sqrt n) — center on μ0\mu_0, scale by the estimated standard error; follows tn1t_{n-1}.
Why tt instead of zz?
Because σ\sigma is estimated by ss, adding uncertainty; the heavier-tailed Student-t with n1n-1 df accounts for it.
What does stats.chisquare measure?
(OE)2/E\sum (O-E)^2/E, total scaled squared mismatch between observed and expected counts.
Common error: does small p prove H0H_0 false?
No — it's P(dataH0)P(\text{data}\mid H_0), not P(H0data)P(H_0\mid\text{data}); it only says data is surprising under H0H_0.
For stats.expon, what does scale mean?
scale = 1/λ (the mean), not the rate λ.
What does stats.norm.fit(data) return?
Maximum-likelihood estimates (μ^,σ^)(\hat\mu,\hat\sigma) that best fit the data.
Two-sided p-value from a t value?
22\cdotstats.t.sf(abs(t), df).

Connections

  • Normal Distribution — the N(μ,σ)N(\mu,\sigma) workhorse standardized by the z-score.
  • Central Limit Theoremwhy sample means are ~normal, justifying t/z tests.
  • p-values and Significance — the decision logic of α\alpha and rejection.
  • Maximum Likelihood Estimation — what .fit does under the hood.
  • numpy.random — lower-level sampling vs. .rvs.
  • Chi-square Distribution — sum of squared normals; basis of goodness-of-fit.

Concept Map

differentiate

1 minus F

invert

bundles

provides

maps any normal to

gives 1.96 cutoff

assumes

computes

extremeness under H0

measured via

CDF F of x = P X leq x

PDF density

Survival S of x

PPF quantile

Distribution object stats.norm

Z-score transform

Standard normal N 0,1

Hypothesis test

Test statistic

p-value

Null hypothesis H0

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, scipy.stats basically ek statistics ka toolbox hai. Iska pehla kaam hai distributions — jaise stats.norm jo normal (bell curve) ko represent karta hai. Iske andar chaar important functions hote hain: .pdf (kisi exact point pe density kitni hai), .cdf (us point tak ka total area, yaani P(Xx)P(X \le x)), .sf (upar wala tail, P(X>x)P(X>x)), aur .ppf (ulta — probability do, value milegi, yaani percentile). Yaad rakho: sab kuch CDF se nikalta hai — PDF uska derivative hai, PPF uska inverse hai.

Doosra bada kaam hai hypothesis testing. Idea simple hai: tum maan lo "kuch khaas nahi ho raha" (yeh hai H0H_0, null hypothesis). Phir tum ek statistic banate ho jiska distribution H0H_0 ke under pata hota hai. Phir p-value nikalta hai — iska matlab hai "agar H0H_0 sach hota, toh itna ya isse zyada extreme data milne ka chance kitna tha." Agar p chhota hai (jaise <0.05<0.05), toh bolte ho "yeh luck se nahi ho sakta", aur H0H_0 ko reject kar dete ho.

Sabse common galti yeh hai ki students sochte hain p-value ka matlab "H0H_0 sach hone ki probability" hai — yeh galat hai. p-value hai P(dataH0)P(\text{data} \mid H_0), ulta nahi. Aur ek aur trick: t-test mein zz ki jagah tt isliye use karte hain kyunki hum σ\sigma ko sample se estimate (ss) karte hain, jisse thodi extra uncertainty aati hai. Standard error mein n\sqrt n se divide karte hain kyunki average lene se noise kam hota hai. Yeh module DS, ML, aur research papers — har jagah kaam aata hai, isliye iski feel banana zaroori hai.

Go deeper — visual, from zero

Test yourself — Scientific Computing (Python)

Connections