Module contents
Lesson 13 of 27Core 100 min

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

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 tt 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.

[ ]Twenty thousand comparisons with no true effectBrowser
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:

  1. What is the statistic? What data quantity summarizes discrepancy with H0H_0?
  2. What is its null distribution? Exact (under a normal model) or asymptotic (by the central limit theorem).
  3. What assumptions are really needed? Normality, independence, equal variances, large counts.
  4. What happens when they fail? Measure the test’s actual size: the rejection fraction under true H0H_0, which should be α\alpha.

We assume familiarity with hypothesis tests and p-values, normal sampling theory (χ2\chi^2, tt, FF), 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: σ\sigma is unknown and must be estimated from the data.

Proof

For one sample, Z=n(Xˉ−μ0)/σ∼N(0,1)Z = \sqrt n(\bar X - \mu_0)/\sigma \sim \Normal(0, 1) under H0H_0, and (n−1)S2/σ2∼χn−12(n-1)S^2/\sigma^2 \sim \chi^2_{n-1} is independent of Xˉ\bar X (normal sampling theory). Thus T=Z/V/(n−1)T = Z/\sqrt{V/(n-1)} with V∼χn−12V \sim \chi^2_{n-1} independent of ZZ, defining tn−1t_{n-1}. For two samples, (Yˉ−Xˉ)/(σ1/n+1/m)∼N(0,1)(\bar Y - \bar X)/(\sigma\sqrt{1/n + 1/m}) \sim \Normal(0,1) and (n+m−2)Sp2/σ2(n + m - 2)S_p^2/\sigma^2 is a sum of two independent χ2\chi^2 variables with n−1n-1 and m−1m-1 degrees of freedom, hence χn+m−22\chi^2_{n+m-2}, also independent of the means. The same ratio gives tn+m−2t_{n+m-2}. 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 Λ\Lambda, in one sample Λ2/n=1/(1+T2/(n−1))\Lambda^{2/n} = 1/\big(1 + T^2/(n - 1)\big), so T2T^2 increases with W=−2log⁡ΛW = -2\log\Lambda, and “tt” 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, n(Xˉ−μ)/S→N(0,1)\sqrt n(\bar X - \mu)/S \to \Normal(0, 1) 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 tt rejects 10.0 % at n=10n = 10, 8.1 % at n=20n = 20, 6.5 % at n=50n = 50 and 5.3 % at n=200n = 200. 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 σX=σY=σ\sigma_X = \sigma_Y = \sigma,

Var⁡(Dˉ)=σX2+σY2−2ρ σXσYn=2σ2(1−ρ)n,\Var(\bar D) = \frac{\sigma_X^2 + \sigma_Y^2 - 2\rho\,\sigma_X\sigma_Y}{n} = \frac{2\sigma^2(1 - \rho)}{n},

versus 2σ2/n2\sigma^2/n if XX and YY were independent groups of nn units. Paired standard error is 1−ρ\sqrt{1 - \rho} times unpaired, and noncentrality moves from λ=δn/(σ2)\lambda = \delta\sqrt n/(\sigma\sqrt 2) to λpar=δn/(σ2(1−ρ))\lambda_{\mathrm{par}} = \delta\sqrt n/(\sigma\sqrt{2(1 - \rho)}). In other words, nn pairs with correlation ρ\rho have the power of n/(1−ρ)n/(1 - \rho) units per group in an independent design (normal approximation): at ρ=0.8\rho = 0.8, five times as many.

InteractiveThe power of pairing
12 subjects measured before and after (each segment is a subject)
mean: +5.6
  • subject increases
  • subject decreases
  • group mean
Evidence −log⁡10p-\log_{10} p for each test as ρ\rho varies (same perturbations)
  • paired
  • unpaired
  • p=0.05p = 0.05
0.80
5.0
12
Mean difference dˉ\bar d5.57
Sample correlation rr (before, after)0.63
Unpaired | paired standard error3.42 | 2.08 (×1.6)
Unpaired p value0.12
Paired p value0.022
The same data: not significant as independent groups (p=0.12p = 0.12) and significant as pairs (p=0.022p = 0.022). The only difference is the model: the paired test knows each subject is compared with themselves.
Twelve subjects measured before and after; true effect is 5 points with deviation 10 per measurement. Left: each subject is a segment. Right: evidence −log⁡10p-\log_{10} p for each test as ρ\rho varies with the same random perturbations. Raise ρ\rho from 0 to 0.9: segments align, paired standard error collapses and paired p-value falls from 0.2 to a few thousandths; unpaired stays put because it does not know each row is the same person. At ρ=0\rho = 0 p-values are similar. Reduce nn to 6 and ρ\rho low: when does pairing lose? Press 'Another sample' and compare threshold crossings.

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 n−1n - 1, unpaired 2n−22n - 2. With ρ\rho near 0 and very small nn, pairing loses slightly; with ρ<0\rho < 0 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.
[ ]Paired versus unpaired as correlation growsBrowser
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 ρ\rho 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 tt 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, Sp2(1/n+1/m)S_p^2(1/n + 1/m), assuming the groups share a variance. Otherwise that estimate targets a value different from true variance σ12/n+σ22/m\sigma_1^2/n + \sigma_2^2/m.

Proof

The numerator’s true variance is σ12/n+σ22/m=(mσ12+nσ22)/(nm)\sigma_1^2/n + \sigma_2^2/m = (m\sigma_1^2 + n\sigma_2^2)/(nm). Since Sp2→(nσ12+mσ22)/(n+m)S_p^2 \to (n\sigma_1^2 + m\sigma_2^2)/(n + m) in probability, Sp2(1/n+1/m)→(nσ12+mσ22)/(nm)S_p^2(1/n + 1/m) \to (n\sigma_1^2 + m\sigma_2^2)/(nm). The true-to-assumed variance ratio is τ2\tau^2, and the numerator is exactly normal; Slutsky gives the limiting normal. For the sign, (mσ12+nσ22)−(nσ12+mσ22)=(m−n)(σ12−σ22)(m\sigma_1^2 + n\sigma_2^2) - (n\sigma_1^2 + m\sigma_2^2) = (m - n)(\sigma_1^2 - \sigma_2^2).

∎

With the motivating numbers (n=10n = 10, m=40m = 40, σ1=3\sigma_1 = 3, σ2=1\sigma_2 = 1), τ2=370/130=2.85\tau^2 = 370/130 = 2.85, so Student uses a standard error τ=1.69\tau = 1.69 times smaller than truth and asymptotically rejects 2{1−Φ(1.96/1.69)}=24.5 %2\{1 - \Phi(1.96/1.69)\} = 24.5\ \% 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, τ2<1\tau^2 < 1 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 TWT_{\mathrm{W}} is normal; the issue is denominator V=SX2/n+SY2/mV = S_X^2/n + S_Y^2/m, a linear combination of two independent χ2\chi^2 variables with different coefficients and no simple distribution. Satterthwaite proposed approximating it by scaled χ2\chi^2, V≈θ χν2/νV \approx \theta\,\chi^2_\nu/\nu, choosing θ\theta and ν\nu to match mean and variance: the mean gives θ=E[V]\theta = \E[V] and variance gives ν=2 E[V]2/Var⁡(V)\nu = 2\,\E[V]^2/\Var(V); replacing true variances by estimates gives the formula (full derivation is an exercise). Remember three facts:

  • min⁡(n,m)−1≤ν^≤n+m−2\min(n, m) - 1 \le \hat\nu \le n + m - 2, with equality at the upper bound when SX2/(n(n−1))=SY2/(m(m−1))S_X^2/(n(n-1)) = S_Y^2/(m(m-1)), in particular if n=mn = m and SX=SYS_X = S_Y (Cauchy–Schwarz). When one group is much more variable, ν^\hat\nu approaches that group’s degrees of freedom: the test recognizes that information comes from fewer observations.
  • Under H0H_0, TW→N(0,1)T_{\mathrm{W}} \to \Normal(0,1) 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 α\alpha.
  • If variances are equal it loses little: with n=mn = m and σ1=σ2\sigma_1 = \sigma_2, ν^\hat\nu is near 2n−22n - 2.
[ ]Checking Satterthwaite's approximation by simulationBrowser
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.

InteractiveStudent versus Welch
P values from 4000 comparisons without an effect (line is the 5% each bin should have)
Student: rejects 24.1 %Welch: rejects 5.1 %
  • Student (pooled variance)
  • Welch
  • rejection region p<0.05p < 0.05
  • ideal uniform
Actual size versus σ1/σ2\sigma_1/\sigma_2 with n1=10n_1 = 10 and n2=40n_2 = 40
nominal 5 %
  • Student
  • Welch
  • nominal
  • Monte Carlo error (1000 replicates per point)
10
40
3
Actual Student size (nominal 5%)24.1 % ± 0.7
Actual Welch size5.1 % ± 0.7
True standard error / Student's assumed error1.72
Degrees of freedom: Student | Welch (mean)48 | 9.7 (theoretical 9.5)
With n1=10n_1 = 10, n2=40n_2 = 40 and σ1/σ2=3\sigma_1/\sigma_2 = 3, Student's tt rejects 24.1 % of the time when there is no effect, 4.8 times nominal: its assumed standard error is 1.72 times smaller than the true one. Welch stays at 5.1 %.
Two normal groups with equal mean. Each histogram is the p-value distribution from 4000 comparisons; if valid, each bin should be 5 % (dashed line), and the first, red, is rejection rate. Right: actual size versus standard-deviation ratio. Start from n1=10n_1 = 10 versus n2=40n_2 = 40 and σ1/σ2=3\sigma_1/\sigma_2 = 3: Student rejects once in four. Reverse sizes: it almost never rejects. Use equal sizes and σ1/σ2=2\sigma_1/\sigma_2 = 2 and see Student survive: the combination is the problem. What does Welch do in each case?

Why default to Welch

“Student is the classical test” is not an argument. Welch has real reasons:

  1. 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 n1=5n_1 = 5, n2=100n_2 = 100 and σ1/σ2=4\sigma_1/\sigma_2 = 4.
  2. 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 α\alpha. Delacre, Lakens and Leys (2017) recommend Welch whenever comparing two-group means.
  3. 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: X∼Bin⁡(n,p)X \sim \Bin(n, p), and the test compares p^=X/n\hat p = X/n with a value. The binomial distribution permits exact calculation; normality approximates it.

Notice standard error uses variance under H0H_0: p0(1−p0)p_0(1 - p_0) in one sample and pˉ(1−pˉ)\bar p(1 - \bar p) (the common estimate) in two. This is not stylistic: it defines the score test, which evaluates variance at the H0H_0-restricted estimator. Wald intervals instead use p^(1−p^)\hat p(1 - \hat p), variance at the estimate, and the Wilson interval (proportion intervals) is the inverted score test. Thus a correct zz 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 2×22 \times 2 count table (abcd)\begin{pmatrix} a & b \\ c & d \end{pmatrix} (row 1: aa successes and bb failures of n1=a+bn_1 = a + b; row 2: cc and dd of n2=c+dn_2 = c + d), Pearson’s independence χ2\chi^2 statistic, covered next, and the two-proportion zz test are the same test.

Proof

With p^1=a/n1\hat p_1 = a/n_1 and p^2=c/n2\hat p_2 = c/n_2, numerator p^1−p^2=(an2−cn1)/(n1n2)=(ad−bc)/(n1n2)\hat p_1 - \hat p_2 = (a n_2 - c n_1)/(n_1 n_2) = (ad - bc)/(n_1 n_2). Also pˉ=(a+c)/N\bar p = (a + c)/N and 1−pˉ=(b+d)/N1 - \bar p = (b + d)/N, and 1/n1+1/n2=N/(n1n2)1/n_1 + 1/n_2 = N/(n_1 n_2). Then

Z2=(ad−bc)2/(n1n2)2(a+c)(b+d)N2⋅Nn1n2=N(ad−bc)2n1n2(a+c)(b+d).Z^2 = \frac{(ad - bc)^2/(n_1 n_2)^2}{\dfrac{(a + c)(b + d)}{N^2}\cdot\dfrac{N}{n_1 n_2}} = \frac{N(ad - bc)^2}{n_1 n_2 (a + c)(b + d)}.

Meanwhile expected counts under independence are E11=n1(a+c)/NE_{11} = n_1(a + c)/N and analogues, and computing ∑(O−E)2/E\sum(O - E)^2/E across four cells gives the same expression, since all four residuals O−EO - E have absolute value (ad−bc)/N(ad - bc)/N.

∎

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.

[ ]Two proportions: z, table χ², likelihood ratio and FisherBrowser
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 2×22\times2 table p-values agree in magnitude: about 10−410^{-4} (between 4.5×10−54.5\times10^{-5} and 1.05×10−41.05\times10^{-4}), with Fisher and Yates slightly more cautious than pure χ2\chi^2 (continuity correction and conditioning approximate the exact test). With small counts the normal approximation shows: 7 of 20 versus p0=0.5p_0 = 0.5 gives p=0.180p = 0.180 and exact p=0.263p = 0.263. 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: bb examples A gets right and B wrong, cc the reverse. McNemar’s test compares bb and cc with X2=(b−c)2/(b+c)∼χ12X^2 = (b - c)^2/(b + c) \sim \chi^2_1 (or exact Bin⁡(b+c,1/2)\Bin(b + c, 1/2) if b+cb + c 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 H0H_0 expects.

Proof

Let Zj=(Oj−npj)/npjZ_j = (O_j - np_j)/\sqrt{np_j}. By the multivariate CLT, Z→N(0,I−qq⊤)Z \to \Normal(0, \mat{I} - \vb{q}\vb{q}\T) with q=(p1,…,pk)⊤\vb{q} = (\sqrt{p_1}, \dots, \sqrt{p_k})\T: multinomial covariance is n(diag⁡(p)−pp⊤)n(\diag(p) - pp\T), and scaling each coordinate by 1/npj1/\sqrt{np_j} gives I−qq⊤\mat{I} - \vb{q}\vb{q}\T. Since ∥q∥=1\norm{\vb{q}} = 1, P=I−qq⊤\mat{P} = \mat{I} - \vb{q}\vb{q}\T is the orthogonal projection onto the complement of q\vb{q}, with rank k−1k - 1. Thus the limit of ZZ has the law of PW\mat{P}\vb{W} with W∼N(0,Ik)\vb{W} \sim \Normal(0, \mat{I}_k) (because PP⊤=P\mat{P}\mat{P}\T = \mat{P}), and continuous mapping gives X2=∥Z∥2→∥PW∥2∼χk−12X^2 = \norm{Z}^2 \to \norm{\mat{P}\vb{W}}^2 \sim \chi^2_{k-1}, squared norm of a Gaussian vector projected onto a subspace of dimension k−1k - 1.

∎

Projection explains degrees of freedom: kk counts have one constraint (∑Oj=n\sum O_j = n), losing direction q\vb{q}. Each parameter H0H_0 leaves free and must be estimated removes another degree of freedom, imposing another linear residual constraint. In an independence table, H0H_0 leaves r−1r - 1 row and c−1c - 1 column marginal probabilities free, so

gl=(rc−1)−[(r−1)+(c−1)]=(r−1)(c−1).\mathrm{gl} = (rc - 1) - \big[(r - 1) + (c - 1)\big] = (r - 1)(c - 1).

the dimension difference between saturated and H0H_0 models, exactly as Wilks’ theorem says.

Two statistics for the same test

GG is the multinomial likelihood-ratio test, X2X^2 the score test: two of the previous lesson’s trinity. Expanding Olog⁡(O/E)O\log(O/E) around O=EO = E,

Olog⁡OE=(O−E)+(O−E)22E+O ⁣((O−E)3E2),O\log\frac{O}{E} = (O - E) + \frac{(O - E)^2}{2E} + \bigO\!\left(\frac{(O - E)^3}{E^2}\right),

and since ∑j(Oj−Ej)=0\sum_j(O_j - E_j) = 0, G=X2+oP(1)G = X^2 + o_P(1). They are asymptotically equivalent and differ for small counts. GG decomposes (a table’s GG splits into subtable GGs), connecting to log-linear models and cross-entropy; X2X^2 usually approaches its limiting χ2\chi^2 more closely at moderate samples and is almost every package’s default.

Estimated parameters in goodness of fit

Often H0H_0 fixes a family rather than probabilities: “counts are Poisson” without specifying λ\lambda. Estimate the parameter, making EjE_j data-dependent. Fisher’s (1924) rule: if a parameter of dimension ss is maximum-likelihood estimated from grouped counts, the statistic converges to χk−1−s2\chi^2_{k - 1 - s}. Chernoff and Lehmann (1954) completed the picture: if estimated by maximum likelihood from ungrouped data (usual, e.g. λ^=xˉ\hat\lambda = \bar x), the limiting distribution lies between χk−1−s2\chi^2_{k-1-s} and χk−12\chi^2_{k-1}. In practice k−1−sk - 1 - s is a reasonable, slightly liberal approximation. The next cell checks Poisson λ=2\lambda = 2, seven categories (0 through 5 and “6 or more”), and n=100n = 100.

[ ]Degrees of freedom when estimating a parameterBrowser
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 λ\lambda the mean is k−1=6k - 1 = 6 and χ62\chi^2_6 rejects 5 %. With estimated λ\lambda the mean drops to 55 and correct level uses χ52\chi^2_5 (k−1−sk - 1 - s with s=1s = 1); forgetting to subtract the parameter and using χ62\chi^2_6 yields under-rejection (just under 3 %) and loses power. The numeric exercise repeats this calculation.

Residuals, effect sizes and small counts

Large X2X^2 says there is association, not where. Cell residuals provide that information. The Pearson residual rij=(Oij−Eij)/Eijr_{ij} = (O_{ij} - E_{ij})/\sqrt{E_{ij}} is a signed cell contribution (X2=∑rij2X^2 = \sum r_{ij}^2), but its variance is below 1: (1−fi)(1−cj)(1 - f_i)(1 - c_j), where fif_i and cjc_j are row and column marginal proportions. Divide by the square root for the adjusted standardized residual rij/(1−fi)(1−cj)r_{ij}/\sqrt{(1 - f_i)(1 - c_j)}, approximately N(0,1)\Normal(0,1) under independence: absolute values above 2 flag unusual cells (bearing in mind many cells are inspected, nine in a 3×33\times3 table). Effect size uses Cramér’s VV, V=X2/(Nmin⁡(r−1,c−1))V = \sqrt{X^2/(N\min(r-1, c-1))}, between 0 and 1 and unlike X2X^2 not increasing with NN.

InteractiveContingency-table residuals
Entry channel (rows) by subscribed plan (columns), N=210N = 210
Free
Pro
Enterprise
total
Search
E = 26.7
res +4.0
E = 23.3
res −1.0
E = 20.0
res −3.2
70
Direct
E = 34.3
res −1.2
E = 30.0
res +1.5
E = 25.7
res −0.2
90
Social
E = 19.0
res −3.0
E = 16.7
res −0.6
E = 14.3
res +3.8
50
total
80
70
60
210
Dashed border: expected count below 5.
Statistic distribution under independence: 2000 permutations versus χ42\chi^2_{4}
observed 26.0
  • permutations (fixed margins)
  • theoretical χ42\chi^2_{4}
  • observed statistic
Color by
Pearson statistic X2X^2 | ratio GG26.03 | 25.71
Degrees of freedom (r−1)(c−1)(r-1)(c-1)4
Asymptotic p value (χ²)3.1·10⁻⁵
Simulated p value (2000 permutations)5.0·10⁻⁴
Cramér's VV | minimum expected0.25 | 14.3
Independence is rejected (p=3.1⋅10−5p = 3.1·10⁻⁵). The “Social and Enterprise” cell contributes 31 % of the statistic; consider it when interpreting the result.
Entry channel by subscription plan. Edit any count (buttons or typing) and inspect expected counts, residuals and colors. Right: the null statistic distribution obtained by permuting columns across units (preserving margins), versus χ2\chi^2 with (r−1)(c−1)(r-1)(c-1) degrees of freedom. Start with 'Moderate association': which cells contribute most? Select 'One deviating cell' and switch coloring by residual or contribution. Under 'Few data' dashed borders mark expected counts below 5: compare asymptotic and simulated p-values and see the theoretical curve stop fitting the histogram.

The χ2\chi^2 approximation is asymptotic and requires no small expected counts. The usual Cochran rule requires Eij≥5E_{ij} \ge 5 in at least 80 % of cells and Eij≥1E_{ij} \ge 1 in all. Otherwise calibrate by simulation or permutation conditional on margins (Monte Carlo test), or use Fisher’s exact test for 2×22\times 2 tables. With many categories, rare ones can be combined before seeing data.

Independence χ2\chi^2 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 0.92+0.12=82 %0.9^2 + 0.1^2 = 82\ \% of examples.

Approximate standard error treating pep_e as constant is po(1−po)/(N(1−pe)2)\sqrt{p_o(1 - p_o)/(N(1 - p_e)^2)}. This is indicative and somewhat optimistic; for small NN 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 κ\kappa is dependence on class distribution. In a simple model, each annotator is independently correct with probability aa, and positive prevalence is π\pi. Observed agreement is po=a2+(1−a)2p_o = a^2 + (1 - a)^2, independent of π\pi. But each positive marginal is m=πa+(1−π)(1−a)m = \pi a + (1 - \pi)(1 - a) and pe=m2+(1−m)2p_e = m^2 + (1 - m)^2 changes: as positives become rare, m→1−am \to 1 - a and chance “explains” more agreement. Two annotators at 90 % accuracy have κ=0.64\kappa = 0.64 at 50 % prevalence but only 0.250.25 at 5 %, without getting worse.

InteractiveThe prevalence paradox
Expected agreement table (area = probability) and decomposition of κ\kappa
41 %9.0 %9.0 %41 %A says +A says −B «+»B «−»chance 50 %above chance 32 %annotator agreement (100% = all)possible improvement above chance: 50 %κ = 0.32 / 0.50 = 0.64
κ\kappa versus prevalence for annotators of fixed accuracy
PABAKa = 80 %a = 90 %a = 95 %a = 99 %
  • curve for selected accuracy
  • PABAK
50.0 %
90.0 %
Observed agreement pop_o82.0 %
Chance agreement pep_e (using marginals)50.0 %
Cohen's kappa κ\kappa0.640
PABAK 2po−12p_o - 10.640
With balanced prevalence and annotators who are 90 % accurate, κ=0.64\kappa = 0.64. Lower prevalence without changing accuracy.
Two independent annotators, each with accuracy aa. Left: expected agreement table (area is probability) and agreement bar: grey is expected by chance, and κ\kappa is the fraction of what remains achieved. Right: κ\kappa versus prevalence. Fix a=90 %a = 90\ \% and lower π\pi from 50 % to 5 %: pop_o stays fixed, κ\kappa moves from 0.64 to 0.25. What accuracy at π=5 %\pi = 5\ \% achieves κ\kappa 0.8? The dashed line is PABAK 2po−12p_o - 1, which stays constant.

Methodological conclusion: low κ\kappa with high observed agreement signals extreme prevalence, not bad annotators (Feinstein and Cicchetti, 1990). Always report the table or marginals alongside κ\kappa, perhaps also PABAK (prevalence-adjusted bias-adjusted kappa), 2po−12p_o - 1 for two categories: this is κ\kappa with pe=1/2p_e = 1/2, as if marginals were uniform, so it is prevalence-independent but does not use actual marginals to discount chance; it merely rescales pop_o. And κ\kappa belongs to annotators, task and example population, not annotators alone: studies with different prevalences are not comparable.

Three extensions cover what Cohen’s κ\kappa does not: Fleiss’ κ\kappa generalizes agreement to mm annotators (possibly different per example); Krippendorff’s α\alpha, α=1−Do/De\alpha = 1 - D_o/D_e with observed and expected disagreement, permits missing data and any scale (nominal, ordinal, interval); quadratic weighted κ\kappa closely resembles intraclass correlation.

The next cell implements κ\kappa (simple and weighted) and applies it to three tables with the same observed agreement po=0.90p_o = 0.90 and increasingly skewed marginals. In the last agreement is unchanged and κ\kappa is negative: annotators never agree on the rare class and all their agreement is chance-expected from marginals.

[ ]Kappa from scratch: same observed agreement, three prevalencesBrowser
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 rr (correlation coefficients) measures linear association. Testing H0:ρ=0H_0: \rho = 0 is straightforward; inference on ρ≠0\rho \neq 0 (intervals, comparing correlations) is trickier because rr is highly skewed.

Testing ρ=0\rho = 0. For pairs (Xi,Yi)(X_i, Y_i) independent across pairs and bivariate normal (it suffices that conditional on XX, YY is normal with mean linear in XX and constant variance), under H0H_0

T=rn−21−r2∼tn−2.T = \frac{r\sqrt{n - 2}}{\sqrt{1 - r^2}} \sim t_{n-2}.

This is exactly the tt statistic for the slope of regression of YY on XX (OLS sampling distribution, covered in the linear model): with b=r sy/sxb = r\,s_y/s_x and SE(b)=sy1−r2/(sxn−2)\mathrm{SE}(b) = s_y\sqrt{1 - r^2}/(s_x\sqrt{n - 2}), ratio b/SE(b)b/\mathrm{SE}(b) is TT. A usage warning: with large samples r=0.1r = 0.1 is already “highly significant” (n=1000n = 1000, p=0.0015p = 0.0015) while explaining 1 % of variance. Significance does not measure importance, and correlation, seeing only linear association, can be zero under perfect dependence (y=x2y = x^2 with symmetric xx).

Inference for ρ≠0\rho \neq 0. Asymptotic standard error of rr is (1−ρ2)/n(1 - \rho^2)/\sqrt n: parameter-dependent, shrinking near ±1\pm 1, with a highly skewed distribution at large ∣ρ∣\abs{\rho}. Interval r±1.96 SEr \pm 1.96\,\mathrm{SE} performs poorly. Fisher’s (1915) solution transforms to a constant-variance scale using the delta method with a deliberately chosen function.

n (r−ρ)→dN(0, (1−ρ2)2)\sqrt n\,(r - \rho) \xrightarrow{d} \Normal\big(0,\ (1 - \rho^2)^2\big)
Asymptotic normality of rr for bivariate normals (second moments and delta method on covariance divided by deviations).
1/4

Intervals and comparisons follow immediately. With zα=Φ−1(1−α/2)z_\alpha = \Phi^{-1}(1 - \alpha/2):

  • Level-1−α1 - \alpha interval for ρ\rho: [tanh⁡(z−zα/n−3), tanh⁡(z+zα/n−3)]\big[\tanh(z - z_\alpha/\sqrt{n-3}),\ \tanh(z + z_\alpha/\sqrt{n-3})\big]. It always lies in (−1,1)(-1, 1) and is asymmetric around rr, as it should be.
  • Two independent correlations (different samples), H0:ρ1=ρ2H_0: \rho_1 = \rho_2:
Z=arctanh⁡r1−arctanh⁡r21/(n1−3)+1/(n2−3)≈N(0,1).Z = \frac{\operatorname{arctanh} r_1 - \operatorname{arctanh} r_2}{\sqrt{1/(n_1 - 3) + 1/(n_2 - 3)}} \approx \Normal(0, 1).

Careful: this tests a difference on the zz scale, not ρ1−ρ2\rho_1 - \rho_2. An interval for ρ1−ρ2\rho_1 - \rho_2 combines individual Fisher intervals (Zou’s method, 2007), the coding exercise. If correlations use the same sample (e.g. Corr⁡(X,Y)\Corr(X, Y) versus Corr⁡(X,W)\Corr(X, W)) they are dependent and this test fails; variants use their correlation (Steiger, Williams).

[ ]Fisher interval coverage versus naive intervalBrowser
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 −1-1 into an almost symmetric one and covers 95 % versus 89.5 % for the naive interval. Two limits: variance of rr 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 (1+rs2/2)/(n−3)\sqrt{(1 + r_s^2/2)/(n - 3)} for Spearman.

Comparing variances: F test and fragility

Sometimes variance itself matters: is one system more stable? Under normality ratio F=SX2/SY2F = S_X^2/S_Y^2 follows Fn−1, m−1F_{n-1,\,m-1} when σX=σY\sigma_X = \sigma_Y (normal sampling theory). But sample variance is more sensitive to distribution shape than mean: for independent observations with excess kurtosis γ2\gamma_2,

Var⁡(S2)=σ4(2n−1+γ2n),\Var(S^2) = \sigma^4\left(\frac{2}{n - 1} + \frac{\gamma_2}{n}\right),

so for large nn, variance of log⁡S2\log S^2 is multiplied by 1+γ2/21 + \gamma_2/2 relative to normal, a factor FF ignores. Actual asymptotic size at α=0.05\alpha = 0.05 is 2{1−Φ(1.96/1+γ2/2)}2\{1 - \Phi(1.96/\sqrt{1 + \gamma_2/2})\}: with Laplace tails (γ2=3\gamma_2 = 3) 21.5 %, and with γ2=6\gamma_2 = 6 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 ∣Xi−Xˉ∣\abs{X_i - \bar X}) and Brown–Forsythe (same with median instead of mean, more robust to skew): both compare means of absolute deviations, where the CLT works.

[ ]F versus Brown–Forsythe with non-normal dataBrowser
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 n=30n = 30 the FF 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 xt=φ xt−1+εtx_t = \varphi\,x_{t-1} + \varepsilon_t with ∣φ∣<1\abs{\varphi} < 1 (first-order autoregression, AR(1): the autocorrelation function is φh\varphi^h) has mean zero, and we test H0:μ=0H_0: \mu = 0 with a one-sample tt. The mean of nn correlated values is less informative than nn independent ones: its variance approaches γ0(1+φ)/((1−φ)n)\gamma_0(1 + \varphi)/((1 - \varphi)n), where γ0\gamma_0 is marginal series variance. But S2→γ0S^2 \to \gamma_0, so the iid test underestimates standard error by λ\sqrt{\lambda}, with

λ=1+φ1−φ,nef=nλ.\lambda = \frac{1 + \varphi}{1 - \varphi}, \qquad n_{\mathrm{ef}} = \frac{n}{\lambda}.

The tt statistic converges to N(0,λ)\Normal(0, \lambda) and rejection occurs 2{1−Φ(1.96/λ)}2\{1 - \Phi(1.96/\sqrt\lambda)\} of the time: with φ=0.5\varphi = 0.5, λ=3\lambda = 3 and 25.8 %; with φ=0.7\varphi = 0.7, 41 %; with φ=0.9\varphi = 0.9, 65 %. The sample is “worth” fewer observations than it contains.

InteractiveDependence inflates false positives
Three zero-mean series (H0H_0 true), first 80 time points
Actual size versus φ\varphi with n=50n = 50 (500 series per point)
nominal 5 %
i.i.d. tt statistic in 2500 series versus its assumed t49t_{49} distribution
±2.01
Fraction of series in which each test rejects (nominal 5%)
0 %20 %40 %60 %80 %t i.i.d.27.0 %Newey-West14.6 %AR(1) adjustment9.3 %
  • tt i.i.d.
  • theoretical tn−1t_{n-1}
  • i.i.d. tt rejection
  • asymptotic theory
  • Newey-West
  • AR(1) adjustment
0.50
50
i.i.d. tt rejects (nominal 5%)27.0 % ± 0.9
Asymptotic theory 2{1−Φ(1.96/λ)}2\{1 - \Phi(1.96/\sqrt{\lambda})\}25.8 %
Variance inflation λ=(1+φ)/(1−φ)\lambda = (1+\varphi)/(1-\varphi)×3.00
Effective sample size nef=n/λn_{\mathrm{ef}} = n/\lambda16.7
Newey-West | AR(1) adjustment reject14.6 % | 9.3 %
With φ=0.50\varphi = 0.50 each observation provides only 1/3.01/3.0 as much information: the sample is worth nef=16.7n_{\mathrm{ef}} = 16.7, not 5050. The i.i.d. tt rejects 27.0 %; asymptotic theory gives 25.8 %. Newey-West falls to 14.6 % and the AR(1) adjustment to 9.3 %: they improve, but at this persistence and nn do not reach 5%.
Zero-mean AR(1) series, i.e. true H0H_0. Top left: three trajectories; larger φ\varphi keeps them away from zero longer. Below: actual iid tt size versus φ\varphi (dotted line is asymptotic theory). Right: histogram of tt in 2500 series versus Student's tt assumed by the test, and rejection rates. Raise φ\varphi to 0.5 with n=50n = 50: how many in 100 experiments 'discover' a nonexistent effect? Raise nn to 500: does it improve? Enable robust standard errors: what do they gain, and when are they insufficient?

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 LL. They partly fix the issue but need large nn relative to lag and persistence: at n=50n = 50 and φ=0.5\varphi = 0.5 they still reject 14 % (and at φ=0\varphi = 0 lose something: 7 %).
  • Correct for nefn_{\mathrm{ef}}: estimate φ^\hat\varphi and multiply variance by (1+φ^)/(1−φ^)(1 + \hat\varphi)/(1 - \hat\varphi). This works if AR(1) is true and φ^\hat\varphi reliable (8.5 % in the same case, 11 % with φ=0.7\varphi = 0.7), but short highly persistent series defeat even this: at φ=0.9\varphi = 0.9 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 n=50n = 50.

[ ]Size of iid t on AR(1) series and robust standard errorsBrowser
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 H0H_0, symmetry, invariance).

[ ]Test battery: one-sample t, Student, Welch, paired, proportion z, χ² and GBrowser
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]])])
[ ]Property-based validation against scipy.statsBrowser
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 0.60.6-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.

[ ]Size and power map of three tests under seven mechanismsBrowser
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 2×22\times2 tables (the default). With lambda_="log-likelihood", chi2_contingency computes the GG-test, and chisquare accepts ddof to subtract estimated parameters.

[ ]The battery with scipy.stats and statsmodelsBrowser
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 tt from the dependence section.

Common mistakes

Exercises

ProofWelch–Satterthwaite degrees of freedom
Prove: Let SX2S_X^2 and SY2S_Y^2 be independent sample variances from normal samples of sizes nn and mm and true variances σ12\sigma_1^2 and σ22\sigma_2^2. Set V=SX2/n+SY2/mV = S_X^2/n + S_Y^2/m. Choose c>0c > 0 and ν>0\nu > 0 so c χν2c\,\chi^2_\nu has the same mean and variance as VV, and prove ν=(σ12/n+σ22/m)2/[(σ12/n)2/(n−1)+(σ22/m)2/(m−1)]\nu = (\sigma_1^2/n + \sigma_2^2/m)^2\big/\big[(\sigma_1^2/n)^2/(n-1) + (\sigma_2^2/m)^2/(m-1)\big]. Replacing variances by estimates gives Welch–Satterthwaite degrees of freedom.
0
Write θ=E[V]\theta = \E[V] and a1=σ12/na_1 = \sigma_1^2/n, a2=σ22/ma_2 = \sigma_2^2/m. Recall (n−1)SX2/σ12∼χn−12(n - 1)S_X^2/\sigma_1^2 \sim \chi^2_{n-1} and variance of χk2\chi^2_k is 2k2k.

Step 1 of 4. What are the mean and variance of VV?

Numericχ² for a 2×2 table
A treatment produces 30 conversions among 40 users (first row: 30 conversions, 10 not) and control 20 of 60 (second row: 20 and 40). Calculate Pearson independence χ2\chi^2 for (30102040)\begin{pmatrix}30 & 10\\20 & 40\end{pmatrix}, without continuity correction.
NumericDegrees of freedom with an estimated parameter
You test whether counts follow a Poisson distribution grouped into 7 categories (0, 1, 2, 3, 4, 5 and '6 or more'). Parameter λ\lambda is unspecified and estimated from data. How many degrees of freedom calibrate Pearson χ2\chi^2?
NumericEffective sample size of an AR(1) series
An AR(1) series with φ=0.6\varphi = 0.6 has n=100n = 100 observations. Using the lesson's asymptotic approximation, what is effective sample size nefn_{\mathrm{ef}} for estimating its mean?
NumericThe value of pairing
In a paired design the correlation between each subject's measurements is ρ=0.75\rho = 0.75 and variances are equal. Under the normal approximation, by what factor must the number of subjects nn in an independent design (with nn subjects per group) be multiplied to match the power of nn pairs?
CodeCompare two independent correlations with Fisher
Complete comparar_correlaciones(r1, n1, r2, n2, alpha). Return (est, p, (lo, hi)): (a) est, statistic Z=(arctanh⁡r1−arctanh⁡r2)/1/(n1−3)+1/(n2−3)Z = (\operatorname{arctanh} r_1 - \operatorname{arctanh} r_2)/\sqrt{1/(n_1 - 3) + 1/(n_2 - 3)}; (b) p, two-sided normal p-value; (c) (lo, hi), a level-1−α1 - \alpha confidence interval for ρ1−ρ2\rho_1 - \rho_2 by Zou's method: calculate each Fisher interval (li,ui)(l_i, u_i) (using tanh⁡\tanh to return to the rr scale) and take lo=r1−r2−(r1−l1)2+(u2−r2)2\text{lo} = r_1 - r_2 - \sqrt{(r_1 - l_1)^2 + (u_2 - r_2)^2} and hi=r1−r2+(u1−r1)2+(r2−l2)2\text{hi} = r_1 - r_2 + \sqrt{(u_1 - r_1)^2 + (r_2 - l_2)^2}.
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)
Shift+Enter to run
QuizSame users, before and after
You measure task completion time for 25 users with an old interface and, one week later, a new one. Which test compares means?
QuizA pilot of 12 and production of 150
You compare a metric's mean between 12 pilot and 150 production users. Sample deviations are 8 and 3. What do you do?
QuizA table with small counts
You have a 3×43\times4 table of N=40N = 40 examples (error type by document type), with expected count below 5 in 8 of 12 cells. How do you test independence?
QuizTwo annotators and a rare class
Two annotators label the same 500 messages 'toxic' or 'not toxic'. 4 % are toxic and they agree on 94 % of labels, but κ=0.21\kappa = 0.21. Which claims are correct?

More than one answer may be correct.

QuizInterval for a correlation with 40 points
On 40 examples you measure correlation between text length and model score, r=0.62r = 0.62. You want a 95 % interval for ρ\rho. What is correct?

Summary

Key idea
Each classical test is signal divided by estimated noise, calibrated with a null distribution valid only under assumptions: reliability depends on actual size when assumptions fail. Welch instead of Student, pairing for common units, χ2\chi^2 only with sufficient expected counts, Fisher zz for correlations and dependence-robust errors are protective choices.
  • tt tests. One-sample (Xˉ−μ0)/(S/n)∼tn−1(\bar X - \mu_0)/(S/\sqrt n) \sim t_{n-1} 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 tt on differences; with within-pair ρ\rho, standard error is 1−ρ\sqrt{1 - \rho} times unpaired and nn pairs equal n/(1−ρ)n/(1 - \rho) 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 τ2=(mσ12+nσ22)/(nσ12+mσ22)\tau^2 = (m\sigma_1^2 + n\sigma_2^2)/(n\sigma_1^2 + m\sigma_2^2); Welch estimates variances separately with Satterthwaite degrees of freedom ν^\hat\nu, keeping 5 %. Default to it without a variance pretest.
  • Proportions. ZZ with variance under H0H_0 is score; in a 2×22\times2 table Z2=X2Z^2 = X^2. Use exact tests for small counts. McNemar handles paired 0/1.
  • χ² and G. X2=∑(O−E)2/EX^2 = \sum(O - E)^2/E and G=2∑Olog⁡(O/E)G = 2\sum O\log(O/E) are asymptotically equivalent (χk−12\chi^2_{k-1} for goodness of fit, (r−1)(c−1)(r-1)(c-1) for independence; one fewer degree per estimated parameter). Adjusted residuals locate effects, Cramér’s VV measures size, and Monte Carlo or Fisher handles expected counts below 5.
  • Kappa. κ=(po−pe)/(1−pe)\kappa = (p_o - p_e)/(1 - p_e) measures chance-adjusted agreement but falls under extreme prevalence even if pop_o does not: report marginals. Weighted, Fleiss and Krippendorff versions exist.
  • Correlation. T=rn−2/1−r2∼tn−2T = r\sqrt{n-2}/\sqrt{1 - r^2} \sim t_{n-2} tests ρ=0\rho = 0; z=arctanh⁡r≈N(arctanh⁡ρ, 1/(n−3))z = \operatorname{arctanh}r \approx \Normal(\operatorname{arctanh}\rho,\ 1/(n-3)) gives intervals and comparisons of independent correlations.
  • Variances. FF is highly sensitive to kurtosis (at n=30n = 30, 18 %–28 % size with heavy tails or skew), uncorrected by the CLT; Brown–Forsythe avoids this.
  • Dependence. For AR(1), iid tt rejects 2{1−Φ(1.96/λ)}2\{1 - \Phi(1.96/\sqrt\lambda)\} with λ=(1+φ)/(1−φ)\lambda = (1 + \varphi)/(1 - \varphi): 25.8 % at φ=0.5\varphi = 0.5. Use HAC errors, effective size, blocks or a dependence model.