Classical parametric tests: t, proportions, chi-squared and correlation
Apply classical parametric tests, examine their assumptions and robustness, and choose paired, Welch, proportion, contingency, agreement and correlation methods appropriately.
After this lesson you can
- Derive one-sample, paired and two-sample t tests and choose Welch for unequal variance.
- Apply proportion, contingency-table and goodness-of-fit tests and inspect their assumptions.
- Interpret chance-corrected agreement and Fisher-transformed correlations.
- Assess the impact of skew, unequal variance and dependence by simulation.
Before you start
- 05Hypothesis testp-valueNormal sampling theory: chi-squared, Student t and F distributionsScore (Lagrange multiplier) testGeneralized likelihood ratio testDelta methodPearson, Spearman and Kendall correlation coefficientsPower and power functionBinomial proportion confidence intervalsSimulation study (ADEMP)
- 04Bernoulli-trial distributions
Motivation: the test you use daily, and when it misleads
A team tests a product change with two groups: a pilot of 10 highly heterogeneous users (metric standard deviation 3 units) and 40 fairly homogeneous production users (standard deviation 1). The change does nothing: means are equal. They analyze it using the usual two-sample Student test with pooled variance at 5 %. The next cell repeats that “no-effect experiment” twenty thousand times and counts how often the test announces a difference.
import numpy as np
from scipy import stats
rng = np.random.default_rng(13)
n1, s1, n2, s2, R = 10, 3.0, 40, 1.0, 20000 # grupo 1 pequeño y variable; H0 cierta: las dos medias valen 0
x = rng.normal(0, s1, (R, n1))
y = rng.normal(0, s2, (R, n2))
p_student = stats.ttest_ind(x, y, axis=1).pvalue # varianza común
p_welch = stats.ttest_ind(x, y, axis=1, equal_var=False).pvalue # sin suponer varianzas iguales
print(f"Student rechaza H0 en el {np.mean(p_student < 0.05):.1%} de los experimentos (nominal 5 %)")
print(f"Welch rechaza H0 en el {np.mean(p_welch < 0.05):.1%} de los experimentos")Student errs once in four: five times its promised level. Data are normal, samples independent, and calculation correct; the only failure is an assumption rarely checked, equal variances, in the most damaging combination of sizes. Welch, which does not require equality, rejects 5 %.
Almost any applied analysis, from an A/B test to benchmark model comparison or annotator agreement, ends with one of this lesson’s seven or eight tests. Recognize them through four recurring questions rather than formulas:
- What is the statistic? What data quantity summarizes discrepancy with ?
- What is its null distribution? Exact (under a normal model) or asymptotic (by the central limit theorem).
- What assumptions are really needed? Normality, independence, equal variances, large counts.
- What happens when they fail? Measure the test’s actual size: the rejection fraction under true , which should be .
We assume familiarity with hypothesis tests and p-values, normal sampling theory (, , ), and the ADEMP simulation-study structure.
One- and two-sample t tests
Two questions share a statistic: whether one group’s mean equals a given value, and whether two groups share a mean. Both arise from the same problem: is unknown and must be estimated from the data.
Proof
For one sample, under , and is independent of (normal sampling theory). Thus with independent of , defining . For two samples, and is a sum of two independent variables with and degrees of freedom, hence , also independent of the means. The same ratio gives . Inverting acceptance regions yields intervals (test–interval duality).
∎This is also the likelihood-ratio test for the problem (see optimal tests and the trinity): with likelihood ratio , in one sample , so increases with , and “” and “likelihood ratio” are the same test with different calibration.
What it really requires
The theorem requires normality, independence and, for two samples, equal variances. Rank them by the cost of violation:
- Normality: usually forgivable. Without normality but with finite variance, by the CLT and Slutsky’s lemma. The test is asymptotically valid, but convergence is slow with highly skewed data. For centered exponential data, the two-sided one-sample rejects 10.0 % at , 8.1 % at , 6.5 % at and 5.3 % at . Heavy tails hurt power more than size.
- Equal variances: forgivable only with balanced groups. This assumption ruins the motivating example; we study it under Welch.
- Independence: unforgivable. There is no simple correction: positive dependence between observations multiplies size by five or more (the last interactive). Address it through design (pairing, clustering) or another model.
Pairing: within-subject design
To learn whether an interface change speeds a task, recruit 12 users for the old version and another 12 for the new, or have the same 12 try both. In the second design each person is their own control: between-user variation (baseline speed) appears in both measurements and cancels when subtracted.
Pairing’s value appears in difference variance. With ,
versus if and were independent groups of units. Paired standard error is times unpaired, and noncentrality moves from to . In other words, pairs with correlation have the power of units per group in an independent design (normal approximation): at , five times as many.
Three consequences:
- Pairing is a design property, not analysis. Analyze as paired only if pairing is real (same unit, or two units linked before outcomes by something predictive of response). Pairing afterward to favor results destroys level.
- It costs degrees of freedom. Paired has , unpaired . With near 0 and very small , pairing loses slightly; with it truly loses because differences are more variable than each measurement.
- There are two errors. Treating positively correlated paired data as independent is conservative: the test overestimates noise, rejects under 5 % and loses almost all power, as the next cell shows. The reverse, treating positively correlated clustered data as independent (multiple user sessions, exam questions), is worse: size inflates.
import numpy as np
from scipy import stats
def estudio(rho, n=12, delta=0.5, R=10000, seed=3):
"""R estudios de n sujetos con efecto delta (en desviaciones) y correlación intrasujeto rho."""
rng = np.random.default_rng(seed)
u = rng.standard_normal((R, n)) # nivel propio de cada sujeto
x = np.sqrt(rho) * u + np.sqrt(1 - rho) * rng.standard_normal((R, n))
y = delta + np.sqrt(rho) * u + np.sqrt(1 - rho) * rng.standard_normal((R, n))
p_unp = stats.ttest_ind(y, x, axis=1).pvalue
p_par = stats.ttest_rel(y, x, axis=1).pvalue
return np.mean(p_unp < 0.05), np.mean(p_par < 0.05), np.median(p_unp), np.median(p_par)
print(" rho potencia no pareado potencia pareado p mediano (no pareado, pareado)")
for rho in (0.0, 0.5, 0.8, 0.95):
pu, pp, mu, mp = estudio(rho)
print(f"{rho:5.2f} {pu:18.3f} {pp:16.3f} {mu:10.3f} {mp:12.5f}")
pu0, pp0 = estudio(0.8, delta=0.0)[:2]
print(f"\nnivel con efecto nulo y rho = 0.8: no pareado {pu0:.4f} pareado {pp0:.4f}")Unpaired power falls as rises (22 % to just over 4 %), although effect is unchanged and data more informative, because the test assumes independent-group noise and its statistic shrinks. Paired power rises from 20 % to almost 100 %. The last line checks that with zero effect paired rejects 5 % and unpaired almost never: a test that does not reject even when it should.
In machine learning, comparing models on the same test examples or the same seeds and splits is paired: each example’s difficulty is the “subject level”. The default is paired on per-example or per-seed metric differences (revisited in evaluation module m31). For 0/1 outcomes (correct or wrong), the analogue is McNemar’s test among proportion tests.
Two samples with unequal variances: Welch
Return to the motivation. What does Student do wrong with unequal sizes and variances? It estimates difference variance using the size-weighted pooled mean, , assuming the groups share a variance. Otherwise that estimate targets a value different from true variance .
Proof
The numerator’s true variance is . Since in probability, . The true-to-assumed variance ratio is , and the numerator is exactly normal; Slutsky gives the limiting normal. For the sign, .
∎With the motivating numbers (, , , ), , so Student uses a standard error times smaller than truth and asymptotically rejects of the time, near the cell’s 25.6 % (finite-size effects account for the rest, especially the small group’s 9 effective degrees of freedom). If the larger group is more variable, and the test becomes conservative, no better because it wastes power.
The solution is not to pool variances. Estimate each group separately and studentize by estimated difference variance.
The numerator of is normal; the issue is denominator , a linear combination of two independent variables with different coefficients and no simple distribution. Satterthwaite proposed approximating it by scaled , , choosing and to match mean and variance: the mean gives and variance gives ; replacing true variances by estimates gives the formula (full derivation is an exercise). Remember three facts:
- , with equality at the upper bound when , in particular if and (Cauchy–Schwarz). When one group is much more variable, approaches that group’s degrees of freedom: the test recognizes that information comes from fewer observations.
- Under , for any variance ratio. It is not exact (the Behrens–Fisher problem of normal means with unequal unknown variances has no simple exact test), but actual size stays close to .
- If variances are equal it loses little: with and , is near .
import numpy as np
rng = np.random.default_rng(2)
n1, s1, n2, s2, R = 10, 3.0, 40, 1.0, 200000
# V = s1²/n1 + s2²/n2 con s_i² = σ_i² · χ²_{n_i - 1} / (n_i - 1)
v1 = s1**2 * rng.chisquare(n1 - 1, R) / (n1 - 1) / n1
v2 = s2**2 * rng.chisquare(n2 - 1, R) / (n2 - 1) / n2
V = v1 + v2
nu_momentos = 2 * V.mean() ** 2 / V.var() # igualando media y varianza
a, b = s1**2 / n1, s2**2 / n2
nu_formula = (a + b) ** 2 / (a**2 / (n1 - 1) + b**2 / (n2 - 1)) # Welch-Satterthwaite
print(f"gl por momentos (simulación): {nu_momentos:.2f} fórmula de Welch-Satterthwaite: {nu_formula:.2f}")
print(f"gl de Student: {n1 + n2 - 2}; cota inferior min(n) - 1 = {min(n1, n2) - 1}")Degrees of freedom fall from 48 (Student) to 9.5: Welch sees almost all uncertainty comes from the small variable group, and its tails are therefore heavier.
Why default to Welch
“Student is the classical test” is not an argument. Welch has real reasons:
- Its cost is nearly zero when variances match, its benefit huge when they do not. This is asymmetric-risk policy: Welch is the better bet when the case is unknown. On a grid of 5–100 per group and deviation ratios from 1/4 to 4, its actual size stays between 4.5 % and 6 % (worst cases have a group of 5; Monte Carlo error ±0.3 points); Student reaches 53 % with , and .
- Pretesting equal variance does not fix this. Choosing Student or Welch based on a variance test is a two-stage procedure: the pretest has low power in small samples (where it matters most) and its own error, so combined procedure level is no longer . Delacre, Lakens and Leys (2017) recommend Welch whenever comparing two-group means.
- Unequal sample sizes are normal, not exceptional: participant losses, pilot versus production, cases versus controls.
Welch does not fix distribution shape: with skewness and small samples or very heavy tails, neither Student nor Welch is reliable; move to permutation tests, rank tests, or bootstrap resampling.
Proportions: from z to exact tests
For binary data the model is as simple as possible: , and the test compares with a value. The binomial distribution permits exact calculation; normality approximates it.
Notice standard error uses variance under : in one sample and (the common estimate) in two. This is not stylistic: it defines the score test, which evaluates variance at the -restricted estimator. Wald intervals instead use , variance at the estimate, and the Wilson interval (proportion intervals) is the inverted score test. Thus a correct test and Wald interval can disagree: for two proportions the test uses pooled standard error and the difference interval uses unpooled, so duality is approximate.
There is a bridge to the rest of the lesson. With a count table (row 1: successes and failures of ; row 2: and of ), Pearson’s independence statistic, covered next, and the two-proportion test are the same test.
Proof
With and , numerator . Also and , and . Then
Meanwhile expected counts under independence are and analogues, and computing across four cells gives the same expression, since all four residuals have absolute value .
∎The next cell implements both tests from scratch for a table with known answer (the numeric exercise below): 30 of 40 treated users convert versus 20 of 60 untreated. Add Fisher’s exact test, conditional on margins and the reference for small counts (developed in permutation), and Yates’ continuity correction.
import numpy as np
from scipy import stats
def z_dos_proporciones(x1, n1, x2, n2):
"""Contraste z con varianza conjunta (el test score)."""
p1, p2, pc = x1 / n1, x2 / n2, (x1 + x2) / (n1 + n2)
return (p1 - p2) / np.sqrt(pc * (1 - pc) * (1 / n1 + 1 / n2))
def pearson_g(tabla, yates=False):
"""Estadísticos χ² de Pearson (con corrección de Yates opcional) y G de una tabla de recuentos."""
O = np.asarray(tabla, float)
E = np.outer(O.sum(1), O.sum(0)) / O.sum()
dif = np.abs(O - E)
if yates:
dif = np.maximum(dif - 0.5, 0)
return (dif**2 / E).sum(), 2 * (O * np.log(O / E)).sum()
tabla = [[30, 10], [20, 40]] # fila 1: 30 de 40; fila 2: 20 de 60
z = z_dos_proporciones(30, 40, 20, 60)
x2, g = pearson_g(tabla)
x2_yates, _ = pearson_g(tabla, yates=True)
print(f"z = {z:.4f} z² = {z**2:.4f} χ² de Pearson = {x2:.4f} (coinciden)")
print(f"G (razón de verosimilitudes) = {g:.4f}; χ² con corrección de Yates = {x2_yates:.4f}")
print(f"valores p: z -> {2 * stats.norm.sf(abs(z)):.2e} χ²₁ con Yates -> {stats.chi2.sf(x2_yates, 1):.2e} "
f"Fisher exacto -> {stats.fisher_exact(tabla)[1]:.2e}")
# una proporción: exacto binomial frente a z con la varianza bajo H0, para 7 éxitos de 20 con p0 = 0.5
x, n, p0 = 7, 20, 0.5
z1 = (x / n - p0) / np.sqrt(p0 * (1 - p0) / n)
print(f"\n7 de 20 frente a p0 = 0.5: z -> {2 * stats.norm.sf(abs(z1)):.4f} "
f"exacto -> {stats.binomtest(x, n, p0).pvalue:.4f}")The three table p-values agree in magnitude: about (between and ), with Fisher and Yates slightly more cautious than pure (continuity correction and conditioning approximate the exact test). With small counts the normal approximation shows: 7 of 20 versus gives and exact . There is little reason to debate: exact costs the same and needs no approximation.
When pairs are matched with 0/1 outcomes (a classifier correct or wrong on each test example, two classifiers on the same examples), only discordant pairs matter: examples A gets right and B wrong, the reverse. McNemar’s test compares and with (or exact if is small): the paired counterpart of this section.
Pearson’s χ²: goodness of fit, independence and homogeneity
Category counts are the third major data family. Tests compare observations with what expects.
Proof
Let . By the multivariate CLT, with : multinomial covariance is , and scaling each coordinate by gives . Since , is the orthogonal projection onto the complement of , with rank . Thus the limit of has the law of with (because ), and continuous mapping gives , squared norm of a Gaussian vector projected onto a subspace of dimension .
∎Projection explains degrees of freedom: counts have one constraint (), losing direction . Each parameter leaves free and must be estimated removes another degree of freedom, imposing another linear residual constraint. In an independence table, leaves row and column marginal probabilities free, so
the dimension difference between saturated and models, exactly as Wilks’ theorem says.
Two statistics for the same test
is the multinomial likelihood-ratio test, the score test: two of the previous lesson’s trinity. Expanding around ,
and since , . They are asymptotically equivalent and differ for small counts. decomposes (a table’s splits into subtable s), connecting to log-linear models and cross-entropy; usually approaches its limiting more closely at moderate samples and is almost every package’s default.
Estimated parameters in goodness of fit
Often fixes a family rather than probabilities: “counts are Poisson” without specifying . Estimate the parameter, making data-dependent. Fisher’s (1924) rule: if a parameter of dimension is maximum-likelihood estimated from grouped counts, the statistic converges to . Chernoff and Lehmann (1954) completed the picture: if estimated by maximum likelihood from ungrouped data (usual, e.g. ), the limiting distribution lies between and . In practice is a reasonable, slightly liberal approximation. The next cell checks Poisson , seven categories (0 through 5 and “6 or more”), and .
import numpy as np
from scipy import stats
rng = np.random.default_rng(5)
n, R, lam, k = 100, 6000, 2.0, 7 # categorías 0, 1, ..., 5 y «6 o más»
x = rng.poisson(lam, (R, n))
lam_hat = x.mean(1) # EMV con los datos sin agrupar
obs = np.stack([(np.minimum(x, k - 1) == c).sum(1) for c in range(k)], axis=1)
def probs(l):
p = stats.poisson.pmf(np.arange(k - 1)[None, :], np.atleast_1d(l)[:, None])
return np.concatenate([p, 1 - p.sum(1, keepdims=True)], axis=1)
X2_est = ((obs - n * probs(lam_hat)) ** 2 / (n * probs(lam_hat))).sum(1) # λ estimada
X2_fijo = ((obs - n * probs(lam)) ** 2 / (n * probs(lam))).sum(1) # λ conocida
print(f"cuantil 0.95 de χ²_5 = {stats.chi2.ppf(0.95, 5):.2f}, de χ²_6 = {stats.chi2.ppf(0.95, 6):.2f}")
for nombre, X2 in (("λ conocida", X2_fijo), ("λ estimada", X2_est)):
print(f"{nombre}: media de X² = {X2.mean():.2f} rechaza con χ²_6: {np.mean(X2 > stats.chi2.ppf(0.95, 6)):.3f} "
f"rechaza con χ²_5: {np.mean(X2 > stats.chi2.ppf(0.95, 5)):.3f}")With known the mean is and rejects 5 %. With estimated the mean drops to and correct level uses ( with ); forgetting to subtract the parameter and using yields under-rejection (just under 3 %) and loses power. The numeric exercise repeats this calculation.
Residuals, effect sizes and small counts
Large says there is association, not where. Cell residuals provide that information. The Pearson residual is a signed cell contribution (), but its variance is below 1: , where and are row and column marginal proportions. Divide by the square root for the adjusted standardized residual , approximately under independence: absolute values above 2 flag unusual cells (bearing in mind many cells are inspected, nine in a table). Effect size uses Cramér’s , , between 0 and 1 and unlike not increasing with .
The approximation is asymptotic and requires no small expected counts. The usual Cochran rule requires in at least 80 % of cells and in all. Otherwise calibrate by simulation or permutation conditional on margins (Monte Carlo test), or use Fisher’s exact test for tables. With many categories, rare ones can be combined before seeing data.
Independence also scores machine-learning features (selecting words or categorical variables most associated with class in supervised-learning module m11). There the p-value is not interpreted, since with many variables it loses meaning without adjustment (multiple comparisons); the ranking is used.
Annotator agreement: Cohen’s kappa
The question changes from “is there association?” to “how much do two annotators agree?” Labeling data to train or evaluate a model, and comparing language-model judges to humans, are tasks where label reliability limits everything else. Percentage agreement is poor: if 90 % of examples belong to one class, two annotators randomly saying “majority class” 90 % of the time without looking agree on of examples.
Approximate standard error treating as constant is . This is indicative and somewhat optimistic; for small or near boundaries prefer a bootstrap. Landis and Koch’s verbal bands (“substantial” from 0.61 to 0.80, etc.) are a convention without statistical foundation: use only for communication and always give the interval.
The prevalence paradox
The best-known defect of is dependence on class distribution. In a simple model, each annotator is independently correct with probability , and positive prevalence is . Observed agreement is , independent of . But each positive marginal is and changes: as positives become rare, and chance “explains” more agreement. Two annotators at 90 % accuracy have at 50 % prevalence but only at 5 %, without getting worse.
Methodological conclusion: low with high observed agreement signals extreme prevalence, not bad annotators (Feinstein and Cicchetti, 1990). Always report the table or marginals alongside , perhaps also PABAK (prevalence-adjusted bias-adjusted kappa), for two categories: this is with , as if marginals were uniform, so it is prevalence-independent but does not use actual marginals to discount chance; it merely rescales . And belongs to annotators, task and example population, not annotators alone: studies with different prevalences are not comparable.
Three extensions cover what Cohen’s does not: Fleiss’ generalizes agreement to annotators (possibly different per example); Krippendorff’s , with observed and expected disagreement, permits missing data and any scale (nominal, ordinal, interval); quadratic weighted closely resembles intraclass correlation.
The next cell implements (simple and weighted) and applies it to three tables with the same observed agreement and increasingly skewed marginals. In the last agreement is unchanged and is negative: annotators never agree on the rare class and all their agreement is chance-expected from marginals.
import numpy as np
def kappa(tabla, pesos=None):
"""Kappa de Cohen (ponderado si se dan pesos de acuerdo w_ij en [0, 1]) y su error estándar aproximado."""
T = np.asarray(tabla, float)
N = T.sum()
P = T / N
r, c = P.sum(1), P.sum(0)
w = np.eye(len(T)) if pesos is None else pesos
po, pe = (w * P).sum(), (w * np.outer(r, c)).sum()
k = (po - pe) / (1 - pe)
return po, pe, k, np.sqrt(po * (1 - po) / (N * (1 - pe) ** 2))
print("mismo acuerdo observado del 90 %, distinta prevalencia")
for nombre, T in (("equilibrada ", [[45, 5], [5, 45]]), ("sesgada ", [[85, 5], [5, 5]]), ("muy sesgada ", [[90, 5], [5, 0]])):
po, pe, k, se = kappa(T)
print(f" {nombre} p_o = {po:.2f} p_e = {pe:.3f} kappa = {k:6.3f} ± {1.96 * se:.3f}")
# tres categorías ordenadas: kappa simple, ponderado lineal y cuadrático
T = np.array([[20, 5, 0], [4, 15, 6], [1, 4, 20]])
i = np.arange(3)
d = np.abs(np.subtract.outer(i, i))
print("\ntres categorías ordenadas")
print(f" simple {kappa(T)[2]:.3f} lineal {kappa(T, 1 - d / 2)[2]:.3f} cuadrático {kappa(T, 1 - (d / 2) ** 2)[2]:.3f}")Correlation: the t test and Fisher’s z transform
For continuous variables, Pearson correlation (correlation coefficients) measures linear association. Testing is straightforward; inference on (intervals, comparing correlations) is trickier because is highly skewed.
Testing . For pairs independent across pairs and bivariate normal (it suffices that conditional on , is normal with mean linear in and constant variance), under
This is exactly the statistic for the slope of regression of on (OLS sampling distribution, covered in the linear model): with and , ratio is . A usage warning: with large samples is already “highly significant” (, ) while explaining 1 % of variance. Significance does not measure importance, and correlation, seeing only linear association, can be zero under perfect dependence ( with symmetric ).
Inference for . Asymptotic standard error of is : parameter-dependent, shrinking near , with a highly skewed distribution at large . Interval performs poorly. Fisher’s (1915) solution transforms to a constant-variance scale using the delta method with a deliberately chosen function.
Intervals and comparisons follow immediately. With :
- Level- interval for : . It always lies in and is asymmetric around , as it should be.
- Two independent correlations (different samples), :
Careful: this tests a difference on the scale, not . An interval for combines individual Fisher intervals (Zou’s method, 2007), the coding exercise. If correlations use the same sample (e.g. versus ) they are dependent and this test fails; variants use their correlation (Steiger, Williams).
import numpy as np
rng = np.random.default_rng(6)
n, rho, R = 20, 0.7, 20000
cov = [[1, rho], [rho, 1]]
xy = rng.multivariate_normal([0, 0], cov, (R, n))
xc = xy[:, :, 0] - xy[:, :, 0].mean(1, keepdims=True)
yc = xy[:, :, 1] - xy[:, :, 1].mean(1, keepdims=True)
r = (xc * yc).sum(1) / np.sqrt((xc**2).sum(1) * (yc**2).sum(1)) # R correlaciones muestrales
# intervalo ingenuo r ± 1.96 (1 - r²)/√n frente al de Fisher
cubre_ingenuo = np.abs(r - rho) < 1.96 * (1 - r**2) / np.sqrt(n)
z = np.arctanh(r)
cubre_fisher = np.abs(z - np.arctanh(rho)) < 1.96 / np.sqrt(n - 3)
def asimetria(v):
return ((v - v.mean()) ** 3).mean() / v.std() ** 3
print(f"cobertura nominal 95 %: ingenuo {cubre_ingenuo.mean():.3f} Fisher {cubre_fisher.mean():.3f}")
print(f"asimetría de r: {asimetria(r):.2f} asimetría de z: {asimetria(z):.2f}")
print(f"desviación típica de z: {z.std():.4f} 1/√(n - 3) = {1 / np.sqrt(n - 3):.4f}")The transform turns a distribution with skewness into an almost symmetric one and covers 95 % versus 89.5 % for the naive interval. Two limits: variance of depends on kurtosis, so with heavy tails Fisher’s interval also undercovers (bootstrap is a robust alternative); rank correlations (Spearman, Kendall) use corrected standard errors, such as Bonett–Wright for Spearman.
Comparing variances: F test and fragility
Sometimes variance itself matters: is one system more stable? Under normality ratio follows when (normal sampling theory). But sample variance is more sensitive to distribution shape than mean: for independent observations with excess kurtosis ,
so for large , variance of is multiplied by relative to normal, a factor ignores. Actual asymptotic size at is : with Laplace tails () 21.5 %, and with 32.7 %. Unlike means, the CLT does not rescue this test: more data do not correct the factor.
Alternatives are Levene’s test (one-way analysis of variance on ) and Brown–Forsythe (same with median instead of mean, more robust to skew): both compare means of absolute deviations, where the CLT works.
import numpy as np
from scipy import stats
rng = np.random.default_rng(7)
n, R = 30, 20000
def tamano(gen):
x, y = gen((R, n)), gen((R, n)) # mismas varianzas: H0 cierta
F = x.var(1, ddof=1) / y.var(1, ddof=1)
p_F = 2 * np.minimum(stats.f.sf(F, n - 1, n - 1), stats.f.cdf(F, n - 1, n - 1))
dx, dy = np.abs(x - np.median(x, 1, keepdims=True)), np.abs(y - np.median(y, 1, keepdims=True))
m1, m2, m = dx.mean(1), dy.mean(1), (dx.mean(1) + dy.mean(1)) / 2
ssb = n * ((m1 - m) ** 2 + (m2 - m) ** 2)
ssw = ((dx - m1[:, None]) ** 2).sum(1) + ((dy - m2[:, None]) ** 2).sum(1)
p_bf = stats.f.sf(ssb / (ssw / (2 * n - 2)), 1, 2 * n - 2) # ANOVA sobre |x - mediana|
return np.mean(p_F < 0.05), np.mean(p_bf < 0.05)
print("distribución curtosis exceso F Brown-Forsythe")
for nombre, ek, gen in (("normal", 0, lambda s: rng.normal(size=s)), ("Laplace", 3, lambda s: rng.laplace(size=s)),
("t con 5 gl", 6, lambda s: rng.standard_t(5, size=s)), ("exponencial", 6, lambda s: rng.exponential(size=s))):
f, bf = tamano(gen)
print(f"{nombre:14s} {ek:12d} {f:.3f} {bf:.3f}")At the test rejects 18 %–28 % for the three non-normal distributions, while Brown–Forsythe stays near 5 %. The recommendation matches mean comparison: no preliminary check is needed. For variances use Brown–Forsythe or bootstrap; for means use Welch without a preliminary variance test.
Robustness by simulation: actual size under violations
Everything above promises actual test size. The systematic check is an ADEMP simulation study focused on rejection rate under various generating mechanisms. Three violations deserve measurement: distribution shape (tails, skew, outliers), variance heterogeneity and dependence. Dependence hurts most and is monitored least.
A time series with (first-order autoregression, AR(1): the autocorrelation function is ) has mean zero, and we test with a one-sample . The mean of correlated values is less informative than independent ones: its variance approaches , where is marginal series variance. But , so the iid test underestimates standard error by , with
The statistic converges to and rejection occurs of the time: with , and 25.8 %; with , 41 %; with , 65 %. The sample is “worth” fewer observations than it contains.
There are three remedies, none free:
- Autocorrelation-robust standard errors (Newey–West HAC): estimate long-run variance by summing sample autocovariances with decreasing weights up to lag . They partly fix the issue but need large relative to lag and persistence: at and they still reject 14 % (and at lose something: 7 %).
- Correct for : estimate and multiply variance by . This works if AR(1) is true and reliable (8.5 % in the same case, 11 % with ), but short highly persistent series defeat even this: at rejection is 24 %.
- Block resampling (advanced bootstrap) or explicit dependence modeling (time series, module m26).
The same logic applies to non-temporal dependence: repeated measurements per user, prompt or document (clustering, in sampling design), or model evaluations on overlapping test sets. Treating these as independent easily produces spurious significance.
The next cell checks this section’s numbers by simulation with .
import numpy as np
from scipy import stats
def serie_ar1(R, n, phi, rng):
e = rng.standard_normal((R, n))
x = np.empty((R, n))
x[:, 0] = e[:, 0] / np.sqrt(1 - phi**2) # arranque en la ley estacionaria
for t in range(1, n):
x[:, t] = phi * x[:, t - 1] + e[:, t]
return x
def varianza_nw(x, L):
"""Varianza de largo plazo de Newey-West (pesos de Bartlett) por filas."""
xc = x - x.mean(1, keepdims=True)
n = x.shape[1]
v = (xc**2).sum(1) / n
for l in range(1, L + 1):
v += 2 * (1 - l / (L + 1)) * (xc[:, l:] * xc[:, :-l]).sum(1) / n
return v
rng = np.random.default_rng(8)
n, R = 50, 8000
L = int(np.floor(4 * (n / 100) ** (2 / 9)))
crit = stats.t.ppf(0.975, n - 1)
print(f"n = {n}, retardo de Newey-West = {L}")
print(" phi t i.i.d. Newey-West ajuste AR(1) teoría asintótica n efectivo")
for phi in (0.0, 0.3, 0.5, 0.7, 0.9):
x = serie_ar1(R, n, phi, rng)
xc = x - x.mean(1, keepdims=True)
phi_hat = (xc[:, 1:] * xc[:, :-1]).sum(1) / (xc**2).sum(1) # autocorrelación de orden 1
t_iid = x.mean(1) / (x.std(1, ddof=1) / np.sqrt(n))
t_nw = x.mean(1) / np.sqrt(varianza_nw(x, L) / n)
t_ar = x.mean(1) / np.sqrt(x.var(1, ddof=1) * (1 + phi_hat) / (1 - phi_hat) / n)
lam = (1 + phi) / (1 - phi)
teoria = 2 * stats.norm.sf(1.96 / np.sqrt(lam))
print(f"{phi:5.1f} {np.mean(abs(t_iid) > crit):8.3f} {np.mean(abs(t_nw) > crit):10.3f} {np.mean(abs(t_ar) > crit):12.3f} "
f"{teoria:17.3f} {n / lam:10.1f}")Test battery from scratch
We have seen tests individually. Practical mastery means building and validating them yourself, without a black box. The first cell implements the full set using only scipy.stats distribution functions (never its tests); the second validates through property-based checks against the library on random data and theoretical properties every valid test must satisfy (uniform p-values under , symmetry, invariance).
import numpy as np
from scipy import stats
def t_una_muestra(x, mu0=0.0):
x = np.asarray(x, float)
n = len(x)
t = (x.mean() - mu0) / (x.std(ddof=1) / np.sqrt(n))
return t, n - 1, 2 * stats.t.sf(abs(t), n - 1)
def t_student(x, y):
"""Dos muestras con varianza común."""
x, y = np.asarray(x, float), np.asarray(y, float)
n, m = len(x), len(y)
sp2 = ((n - 1) * x.var(ddof=1) + (m - 1) * y.var(ddof=1)) / (n + m - 2)
t = (x.mean() - y.mean()) / np.sqrt(sp2 * (1 / n + 1 / m))
return t, n + m - 2, 2 * stats.t.sf(abs(t), n + m - 2)
def t_welch(x, y):
"""Dos muestras con grados de libertad de Welch-Satterthwaite."""
x, y = np.asarray(x, float), np.asarray(y, float)
a, b = x.var(ddof=1) / len(x), y.var(ddof=1) / len(y)
t = (x.mean() - y.mean()) / np.sqrt(a + b)
nu = (a + b) ** 2 / (a**2 / (len(x) - 1) + b**2 / (len(y) - 1))
return t, nu, 2 * stats.t.sf(abs(t), nu)
def t_pareado(x, y):
return t_una_muestra(np.asarray(x, float) - np.asarray(y, float))
def z_una_proporcion(x, n, p0):
z = (x / n - p0) / np.sqrt(p0 * (1 - p0) / n)
return z, 2 * stats.norm.sf(abs(z))
def z_dos_proporciones(x1, n1, x2, n2):
pc = (x1 + x2) / (n1 + n2)
z = (x1 / n1 - x2 / n2) / np.sqrt(pc * (1 - pc) * (1 / n1 + 1 / n2))
return z, 2 * stats.norm.sf(abs(z))
def chi2_independencia(tabla):
O = np.asarray(tabla, float)
E = np.outer(O.sum(1), O.sum(0)) / O.sum()
gl = (O.shape[0] - 1) * (O.shape[1] - 1)
x2 = ((O - E) ** 2 / E).sum()
return x2, gl, stats.chi2.sf(x2, gl)
def g_test(tabla):
O = np.asarray(tabla, float)
E = np.outer(O.sum(1), O.sum(0)) / O.sum()
gl = (O.shape[0] - 1) * (O.shape[1] - 1)
g = 2 * np.sum(np.where(O > 0, O * np.log(np.where(O > 0, O, 1) / E), 0.0))
return g, gl, stats.chi2.sf(g, gl)
# comprobación rápida con los ejemplos de la lección
print("Welch (10 frente a 40, sigma 3 y 1):", [round(float(v), 4) for v in t_welch(np.random.default_rng(0).normal(0, 3, 10), np.random.default_rng(1).normal(0, 1, 40))])
print("tabla 2x2 [[30, 10], [20, 40]] chi2, gl, p :", [round(float(v), 6) for v in chi2_independencia([[30, 10], [20, 40]])])
print(" G, gl, p :", [round(float(v), 6) for v in g_test([[30, 10], [20, 40]])])import numpy as np
from scipy import stats
# (usa las funciones de la celda anterior: t_una_muestra, t_student, t_welch, t_pareado, z_dos_proporciones, chi2_independencia, g_test)
rng = np.random.default_rng(42)
def max_diferencia(n_casos=200):
"""Diferencia máxima entre nuestros valores p y los de scipy en datos y tamaños aleatorios."""
d = np.zeros(6)
for _ in range(n_casos):
n, m = rng.integers(3, 40, 2)
x, y = rng.normal(rng.normal(), rng.uniform(0.5, 3), n), rng.normal(rng.normal(), rng.uniform(0.5, 3), m)
xp = rng.normal(size=n)
d[0] = max(d[0], abs(t_una_muestra(x, 0.3)[2] - stats.ttest_1samp(x, 0.3).pvalue))
d[1] = max(d[1], abs(t_student(x, y)[2] - stats.ttest_ind(x, y).pvalue))
d[2] = max(d[2], abs(t_welch(x, y)[2] - stats.ttest_ind(x, y, equal_var=False).pvalue))
d[3] = max(d[3], abs(t_pareado(x, xp)[2] - stats.ttest_rel(x, xp).pvalue))
tabla = rng.integers(2, 60, (3, 3))
d[4] = max(d[4], abs(chi2_independencia(tabla)[2] - stats.chi2_contingency(tabla, correction=False)[1]))
d[5] = max(d[5], abs(g_test(tabla)[2] - stats.chi2_contingency(tabla, correction=False, lambda_="log-likelihood")[1]))
return d
nombres = ["t una muestra", "t Student", "t Welch", "t pareado", "χ² independencia", "G-test"]
for nombre, v in zip(nombres, max_diferencia()):
print(f" {nombre:18s} máx |Δp| frente a scipy = {v:.1e}")
# propiedad 1: bajo H0 los valores p son uniformes (Kolmogórov-Smirnov), también con varianzas distintas en Welch
R = 3000
p_stu = [t_student(rng.normal(0, 1, 12), rng.normal(0, 1, 15))[2] for _ in range(R)]
p_wel = [t_welch(rng.normal(0, 1, 12), rng.normal(0, 3, 15))[2] for _ in range(R)]
print(f"\nuniformidad de p bajo H0 (KS): Student, σ iguales: p = {stats.kstest(p_stu, 'uniform').pvalue:.2f} "
f"Welch, σ distintas: p = {stats.kstest(p_wel, 'uniform').pvalue:.2f}")
# propiedad 2: invarianzas: intercambiar las dos muestras no cambia p; z² = χ² en tablas 2x2
x, y = rng.normal(size=9), rng.normal(0.4, 2, 14)
print("p con las muestras intercambiadas coincide:", np.isclose(t_welch(x, y)[2], t_welch(y, x)[2]))
z, _ = z_dos_proporciones(31, 120, 52, 140)
print("z² = χ² en la tabla 2x2:", np.isclose(z**2, chi2_independencia([[31, 89], [52, 88]])[0]))Robustness audit: when is each test reliable?
Build a map summarizing the lesson using complete ADEMP: aim (A) is comparing two means; data-generating mechanisms (D) are seven (one ideal and six violations); estimand (E) is equal means, with zero effect for size and a -standard-deviation shift for power; methods (M) are Student, Welch and Mann–Whitney rank sum (in nonparametric tests); performance measures (P) are rejection rate and Monte Carlo error.
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from scipy.stats import rankdata
R = 2500
def normal(rng, n, s=1.0):
return s * rng.standard_normal((R, n))
def colas(rng, n): # t con 3 gl, normalizada a varianza 1
return rng.standard_t(3, (R, n)) / np.sqrt(3)
def asimetrica(rng, n): # exponencial centrada, varianza 1
return rng.exponential(1.0, (R, n)) - 1.0
def contaminada(rng, n): # 5 % de valores con desviación 6, normalizada a varianza 1
x = rng.standard_normal((R, n))
x[rng.random((R, n)) < 0.05] *= 6
return x / np.sqrt(0.95 + 0.05 * 36)
def serie_ar1(rng, n, phi=0.5): # cada fila es una serie AR(1), normalizada a varianza 1
e = rng.standard_normal((R, n))
x = np.empty((R, n))
x[:, 0] = e[:, 0] / np.sqrt(1 - phi**2)
for t in range(1, n):
x[:, t] = phi * x[:, t - 1] + e[:, t]
return x * np.sqrt(1 - phi**2)
ESCENARIOS = { # nombre: (generador del grupo 1, generador del grupo 2, n1, n2)
"ideal": (normal, normal, 20, 20),
"colas pesadas": (colas, colas, 20, 20),
"asimetría\n(10 y 40)": (asimetrica, asimetrica, 10, 40),
"contaminación": (contaminada, contaminada, 20, 20),
"σ distinta\n(10 var., 40)": (lambda r, n: normal(r, n, 3.0), normal, 10, 40),
"σ distinta\n(40 var., 10)": (lambda r, n: normal(r, n, 3.0), normal, 40, 10),
"serie AR(1)": (serie_ar1, serie_ar1, 30, 30),
}
def pvalores(x, y):
n1, n2 = x.shape[1], y.shape[1]
p_student = stats.ttest_ind(x, y, axis=1).pvalue
p_welch = stats.ttest_ind(x, y, axis=1, equal_var=False).pvalue
r = rankdata(np.concatenate([x, y], axis=1), axis=1)
z = (r[:, :n1].sum(1) - n1 * (n1 + n2 + 1) / 2) / np.sqrt(n1 * n2 * (n1 + n2 + 1) / 12)
return p_student, p_welch, 2 * stats.norm.sf(np.abs(z))
metodos = ["Student", "Welch", "Mann-Whitney"]
tam, pot = np.zeros((3, len(ESCENARIOS))), np.zeros((3, len(ESCENARIOS)))
rng = np.random.default_rng(2024)
for j, (g1, g2, n1, n2) in enumerate(ESCENARIOS.values()):
tam[:, j] = [np.mean(p < 0.05) for p in pvalores(g1(rng, n1), g2(rng, n2))]
pot[:, j] = [np.mean(p < 0.05) for p in pvalores(g1(rng, n1), g2(rng, n2) + 0.6)]
print(f"error de Monte Carlo del tamaño: ±{1.96 * np.sqrt(0.05 * 0.95 / R):.3f}")
for i, m in enumerate(metodos):
print(f"tamaño {m:13s}", " ".join(f"{v:5.3f}" for v in tam[i]))
fig, ax = plt.subplots(1, 2, figsize=(10.5, 3.6), sharey=True)
etiquetas = list(ESCENARIOS)
for a, datos, titulo in ((ax[0], tam, "tamaño real (nominal 0.05)"), (ax[1], pot, "potencia frente a un desplazamiento de 0.6")):
if datos is tam:
im = a.imshow(np.clip(datos - 0.05, -0.1, 0.25), cmap="RdBu_r", vmin=-0.25, vmax=0.25, aspect="auto")
else:
im = a.imshow(datos, cmap="Blues", vmin=0, vmax=1, aspect="auto")
a.set_xticks(range(len(etiquetas)), etiquetas, fontsize=7)
a.set_title(titulo, fontsize=10)
for i in range(3):
for j in range(len(etiquetas)):
oscuro = abs(datos[i, j] - 0.05) > 0.15 if datos is tam else datos[i, j] > 0.6
a.text(j, i, f"{datos[i, j]:.2f}", ha="center", va="center", fontsize=8, color="white" if oscuro else "black")
ax[0].set_yticks(range(3), metodos)
plt.tight_layout()
plt.show()Reading the map (Monte Carlo error ±1 point in sizes):
- Ideal: all three control level; Student and Welch almost coincide, Mann–Whitney loses little.
- Heavy tails and contamination: none violates level, but ranks gain substantial power (tails penalize means, not ranks).
- Skewness with unequal sizes (10 and 40): mean tests are miscalibrated in opposite directions: Welch rejects about 8 %, Student near 4 %, while Mann–Whitney, comparing identical distributions, attains 5 %. This calls for permutation or bootstrap.
- Unequal variances: Student fails in both directions (26 % or almost no rejection), Welch stays near 5 %, and the rank test, which tests the whole distribution rather than means, also fails (14 % and 1 %), though less.
- Serial dependence: all three reject almost once in four. No two-sample test lacking a dependence model is valid here, and its power is meaningless: it is the power of a test that rejects anything. This row is hardest to notice, because no “are my data normal?” diagnostic detects it.
Using libraries: scipy.stats and statsmodels
scipy.stats implements all lesson tests. Two arguments in ttest_ind and chi2_contingency deserve attention: equal_var=False activates Welch (not the default, though it should be), and correction applies Yates correction in tables (the default). With lambda_="log-likelihood", chi2_contingency computes the -test, and chisquare accepts ddof to subtract estimated parameters.
import numpy as np
from scipy import stats
from statsmodels.stats.proportion import proportions_ztest, proportion_confint
from statsmodels.stats.inter_rater import cohens_kappa, fleiss_kappa
from sklearn.metrics import cohen_kappa_score
rng = np.random.default_rng(21)
x, y = rng.normal(0, 3, 10), rng.normal(0, 1, 40)
print("Student :", stats.ttest_ind(x, y))
print("Welch :", stats.ttest_ind(x, y, equal_var=False))
a = rng.normal(size=25)
b = a + rng.normal(0.4, 0.5, 25)
print("pareado :", stats.ttest_rel(b, a))
print("una muestra :", stats.ttest_1samp(a, 0.0))
# proporciones: z con varianza conjunta y exacto de una proporción
z, p = proportions_ztest([30, 20], [40, 60])
print(f"\nz de dos proporciones: z = {z:.4f}, p = {p:.2e}; intervalo de Wilson de 30/40: {proportion_confint(30, 40, method='wilson')}")
# χ²: independencia, G-test y bondad de ajuste con un parámetro estimado
tabla = np.array([[40, 20, 10], [30, 35, 25], [10, 15, 25]])
chi2, p, gl, esperados = stats.chi2_contingency(tabla)
g, pg, _, _ = stats.chi2_contingency(tabla, lambda_="log-likelihood")
print(f"\nχ² = {chi2:.2f} (gl = {gl}, p = {p:.2e}); G = {g:.2f} (p = {pg:.2e})")
recuentos = rng.poisson(2.0, 100) # 100 recuentos; categorías 0, 1, ..., 4 y «5 o más»
obs = np.bincount(np.minimum(recuentos, 5), minlength=6)
lam = recuentos.mean() # EMV con los datos sin agrupar
esp = 100 * np.append(stats.poisson.pmf(np.arange(5), lam), stats.poisson.sf(4, lam))
print("bondad de ajuste Poisson (6 categorías, ddof=1, gl = 4):", stats.chisquare(obs, esp, ddof=1))
# correlación, comparación de varianzas, kappa
u = rng.normal(size=30)
v = 0.6 * u + 0.8 * rng.normal(size=30)
r, p = stats.pearsonr(u, v)
ic = stats.pearsonr(u, v).confidence_interval()
print(f"\nPearson r = {r:.3f}, p = {p:.2e}, intervalo de Fisher: ({ic.low:.3f}, {ic.high:.3f})")
print("Brown-Forsythe :", stats.levene(x, y, center="median"))
etq1 = rng.integers(0, 2, 200)
etq2 = np.where(rng.random(200) < 0.85, etq1, 1 - etq1)
print(f"kappa de Cohen: sklearn {cohen_kappa_score(etq1, etq2):.4f}, statsmodels {cohens_kappa(np.histogram2d(etq1, etq2, bins=2)[0]).kappa:.4f}")
verdad = rng.integers(0, 3, 30) # 30 sujetos, 4 anotadores que aciertan el 80 %
votos = np.where(rng.random((30, 4)) < 0.8, verdad[:, None], rng.integers(0, 3, (30, 4)))
sujetos = np.stack([np.bincount(v, minlength=3) for v in votos]) # recuento de votos por categoría y sujeto
print(f"kappa de Fleiss (30 sujetos, 4 anotadores, 3 categorías): {fleiss_kappa(sujetos):.3f}")Two notes: pearsonr(...).confidence_interval() gives the Fisher interval derived above, and statsmodels.stats.weightstats offers ttest_ind with usevar="unequal" and variants with intervals and power. For HAC time-series errors use statsmodels.api.OLS(...).fit(cov_type="HAC", cov_kwds={"maxlags": L}) with a constant as the sole regressor, giving the robust from the dependence section.
Common mistakes
Exercises
Step 1 of 4. What are the mean and variance of ?
comparar_correlaciones(r1, n1, r2, n2, alpha). Return (est, p, (lo, hi)): (a) est, statistic ; (b) p, two-sided normal p-value; (c) (lo, hi), a level- confidence interval for by Zou's method: calculate each Fisher interval (using to return to the scale) and take and .import numpy as np
from scipy.stats import norm
def comparar_correlaciones(r1, n1, r2, n2, alpha=0.05):
"""Contraste de rho1 = rho2 e intervalo para rho1 - rho2 con la transformación z de Fisher."""
zc = norm.ppf(1 - alpha / 2)
# tu código: z de Fisher de cada r, estadístico, valor p, intervalos individuales e intervalo de Zou
est = 0.0
p = 1.0
lo, hi = 0.0, 0.0
return est, p, (lo, hi)More than one answer may be correct.
Summary
- tests. One-sample and two-sample Student are exact under normality (the latter also requires equal variances); without normality they are asymptotically valid by the CLT, slowly under skew. Dependence is their worst enemy.
- Paired. One-sample on differences; with within-pair , standard error is times unpaired and pairs equal independent subjects. Paired analyzed as independent: conservative. Clustered analyzed as independent: inflated size.
- Welch. Student over-rejects when the small group is more variable, with ; Welch estimates variances separately with Satterthwaite degrees of freedom , keeping 5 %. Default to it without a variance pretest.
- Proportions. with variance under is score; in a table . Use exact tests for small counts. McNemar handles paired 0/1.
- χ² and G. and are asymptotically equivalent ( for goodness of fit, for independence; one fewer degree per estimated parameter). Adjusted residuals locate effects, Cramér’s measures size, and Monte Carlo or Fisher handles expected counts below 5.
- Kappa. measures chance-adjusted agreement but falls under extreme prevalence even if does not: report marginals. Weighted, Fleiss and Krippendorff versions exist.
- Correlation. tests ; gives intervals and comparisons of independent correlations.
- Variances. is highly sensitive to kurtosis (at , 18 %–28 % size with heavy tails or skew), uncorrected by the CLT; Brown–Forsythe avoids this.
- Dependence. For AR(1), iid rejects with : 25.8 % at . Use HAC errors, effective size, blocks or a dependence model.