Nonparametric tests: ranks, signs and goodness of fit
Understand rank tests, distribution-free inference, asymptotic efficiency and empirical-distribution goodness-of-fit methods, including DKW bands and QQ plots.
After this lesson you can
- Derive sign, Wilcoxon, Mann–Whitney and Kruskal–Wallis rank tests and interpret their assumptions.
- Connect Mann–Whitney to probability of superiority and AUC, and compare efficiency with t tests.
- Construct a simultaneous DKW confidence band and apply ECDF goodness-of-fit tests.
- Diagnose distributions using QQ plots and calibrate tests when parameters are estimated.
Before you start
Motivation: the outlier that silenced the t test
A team compares response time for two service versions using fourteen requests each. The new version is clearly slower on almost every request, but one suffered a network retry and took 2.4 seconds. Welch’s test, measuring mean difference in standard-error units, sees that request as enormous noise and finds no evidence. The next cell calculates this and varies the outlier.
import numpy as np
from scipy import stats
rng = np.random.default_rng(1)
a = np.round(rng.lognormal(4.6, 0.25, 14)) # versión actual, en ms (mediana de unos 100 ms)
b = np.round(rng.lognormal(4.95, 0.25, 14)) # versión nueva: un 40 % más lenta
print(f"medianas: A = {np.median(a):.0f} ms, B = {np.median(b):.0f} ms")
for atipico in (400.0, 2400.0, 24000.0):
b2 = b.copy()
b2[0] = atipico # una petición con reintento de red
pt = stats.ttest_ind(b2, a, equal_var=False).pvalue
pm = stats.mannwhitneyu(b2, a).pvalue
print(f"atípico = {atipico:7.0f} ms | media de B = {b2.mean():7.1f} | p de Welch = {pt:.4f} | p de Mann-Whitney = {pm:.4f}")The Mann–Whitney rank test gives the same value for all three outlier values, not by accident: it ignores how long the slow request took and sees only that it is largest. This lesson studies tests replacing data with ranks (positions in order), with three properties. Validity does not depend on population shape, so values are exact in small samples. They are insensitive to any extreme value and monotone scale change (logarithms, roots). They lose little power under normality and gain much otherwise. Six questions:
- Why is a rank statistic’s null distribution universal? It is a permutation test on .
- What can signs of paired differences say, and what do Wilcoxon signed ranks gain?
- What does Mann–Whitney count? Probability of superiority, exactly classifier AUC, revealing its actual hypothesis.
- How does it compare with ? Asymptotic relative efficiency: under normality, never below , above 1 once tails get heavy.
- How do we test a given distribution? The empirical distribution function, Dvoretzky–Kiefer–Wolfowitz confidence band, and Kolmogorov–Smirnov, Anderson–Darling and Shapiro–Wilk tests.
- How do we look, not just test? QQ plots.
We use hypothesis tests, permutation tests and exchangeability from the previous lesson; power function, tests and paired test; empirical distribution function and probability integral transform.
Ranks and their universal null distribution
Given a vector without repeated values, the rank of is its position sorted from least to greatest:
The smallest has rank 1, largest . With ties, each repeated value receives the average of positions it would occupy (midranks: has ranks ). A rank statistic is any function of rank vector .
Their convenience follows from a nearly trivial fact worth proving carefully, because everything after depends on it.
Proof
Without ties (probability 1), is always a permutation of . Let be any permutation. Reordering variables to produces the same law as by exchangeability. The rank vector of is reordered by , i.e. . Thus for every , and since traverses all permutations as does, all probabilities are equal. They sum to 1, so equal .
∎This is the permutation-test idea with one crucial difference. Permuting raw data assigns labels over observed values, whose reference distribution must be recomputed for each dataset. A rank test assigns labels over , the same for all datasets of that size: the null distribution is computed once, tabulated (textbook Wilcoxon and Mann–Whitney tables), and reused. Three practical consequences:
- Exact values in small samples without normality or other shape assumptions, provided no ties.
- Monotone-transform invariance. If is strictly increasing, ranks of equal those of . Analyzing times or their logarithms is the same test, so measurement scale need not be chosen.
- Robustness. Changing an observation without changing its position leaves the statistic unchanged. A value can be arbitrarily distant: its influence is bounded by its rank.
The cost is discarding magnitude: ranks cannot distinguish a 1 ms difference from 1000 ms if order stays the same. The following tests use ranks by design: one sample or pairs (signs and Wilcoxon), two samples (Mann–Whitney), and samples (Kruskal–Wallis).
The sign test
The simplest statistical test. Given iid with continuous distribution, test the median: . For paired data is each pair difference. If the median is , each observation lies above with probability , so count them.
Proof
Indicators are independent Bernoulli with parameter (the median leaves half the probability on each side, with no mass at ). Their sum is binomial.
∎This binomial also gives a distribution-free median confidence interval. With ordered sample , median falls below exactly when at most observations lie below it, and above when at most lie above. Each event has probability and they are disjoint if , so
With and , interval has exact coverage for any continuous distribution. It is conservative (coverage is discrete), but never fails the guarantee.
The sign test is most robust and least powerful: it uses only bits. Under normality it needs about times the data of for equal power (efficiency below), though wins under heavy tails: for Laplace, the sign test is twice as efficient as .
Wilcoxon signed ranks
The sign test discards difference magnitude. Wilcoxon (1945) recovered part using ranks of absolute values: a large positive difference weighs more than a small one. Given iid differences (e.g. paired data), test whether centered at ; without loss of generality set by subtraction.
The null is stronger than for signs: not just zero median but symmetry around zero. In exchange more information is used. Pairing naturally justifies symmetry: if treatment does nothing, swapping a pair’s values leaves the data law unchanged, and difference has the same law as . This is randomization-test reasoning applied to ranks.
Proof
Symmetry makes a uniform sign independent of , and signs are independent across observations. Since depend only on , signs are independent of all ranks. The observation ranked by absolute value is positive with probability independently of the others and contributes to if positive: this is . Mean is and variance . The coefficient of in counts subsets of summing to , satisfying recursion (element is included or not). Asymptotic normality comes from the Lindeberg central limit theorem for independent nonidentical sums, since each term is bounded by and total variance grows as .
∎Ties, zeros and what is estimated
The theorem’s null distribution holds only without ties among and without zeros. Real data have them (rounded measurements, integer differences), requiring explicit treatment:
- Zeros (): ordinarily drop them, as in the sign test; Pratt’s method retains them when ranking and drops them afterward. Both are valid but differ: report the choice.
- Ties among : assign midranks and the exact distribution no longer applies. The normal approximation remains valid with corrected variance , where is tie-group size.
The estimator accompanying this test, as sample mean accompanies , is the Hodges–Lehmann estimator: the median of all Walsh averages with , with a confidence interval from test inversion. It estimates the pseudomedian, the median of ; under symmetry the pseudomedian equals the center.
Mann–Whitney: comparing two samples
The most practical case. Given independent and , ask whether tends to exceed . Pool observations, rank them and sum the first sample’s ranks.
The figure shows the identity underlying everything: is the area of a pairwise comparison matrix, and is ROC area for “classify as if score exceeds threshold”.
Null distribution and normal approximation
Under , all observations are iid; by the theorem above, first-sample ranks are a sample without replacement of size from . This gives the full null distribution.
Proof
sums a size- sample without replacement from , with mean and variance . Under sampling without replacement, and . Thus and
The recursion conditions on which of observations is largest: if , it beats observations in and adds to (leaving in and in ); if , it adds nothing (leaving and ). Asymptotic normality is the sampling-without-replacement CLT (Hájek). With ties, midranks reduce rank-population variance from to the corrected value.
∎With , the exact table gives and the two-sided test rejects at 5 % if or ; normal approximation with continuity correction is excellent already at . Packages use exact distribution for small untied samples and normal otherwise.
Probability of superiority: AUC
Read the figure’s matrix as an estimate. Let , the probability of superiority of over (psychology’s “common language effect size”). Since sums comparisons each with mean , is an unbiased estimate of (the guided proof below). In machine learning, if scores examples and are positive scores and negative, is classifier AUC: the probability a random positive scores above a random negative. Mann–Whitney is AUC multiplied by , and comparing a model’s AUC with (chance) is a Mann–Whitney test. This also allows AUC confidence intervals from variance of outside the null (DeLong’s method uses the same comparison matrix).
What hypothesis is actually tested
Under , . The converse is false, causing the most common misunderstandings.
Under a shift model , the test concerns : it tests , its natural estimate is the median of differences (Hodges–Lehmann), and intervals for invert the test. Outside that model honestly report (with interval) rather than “median difference”. If variances or shapes differ greatly and the target is , Brunner–Munzel (or Fligner–Policello), not classical Mann–Whitney, maintains level.
Kruskal–Wallis: samples
To compare groups with observations (), pool ranks and compare each group mean rank with overall . Equal groups should all be close.
Proof
Ranks are a permutation of with mean and centered sum of squares , constant regardless of data. Thus between-group rank sum of squares divided by and multiplied by is exactly . By the same without-replacement reasoning, has mean , variance and covariance with , and mean vector is asymptotically normal. is its quadratic form using the (generalized) inverse covariance, of rank and yielding . For , the result is squared , i.e. Mann–Whitney .
∎Kruskal–Wallis rejection says some group differs, not which. Locate it by pairwise Dunn tests, using pooled ranks,
with Holm or Bonferroni multiplicity correction (multiple comparisons). This parallels pairwise comparisons after ANOVA. Like all tests in the lesson, it detects “tends to be greater”, not “has a different mean”.
Implementation from scratch
The four tests fit in a few lines. The first cell implements midranks, exact sign test and Wilcoxon with exact null by convolution and tie-corrected normal approximation, validating against scipy.stats.
import numpy as np
from math import comb
from scipy import stats
def rangos_medios(x):
"""Rangos 1..n; los empates reciben el promedio de los rangos que ocuparían."""
x = np.asarray(x, float)
orden = np.argsort(x, kind="mergesort")
s = x[orden]
r = np.empty(len(x))
i = 0
while i < len(x):
j = i
while j + 1 < len(x) and s[j + 1] == s[i]:
j += 1
r[orden[i:j + 1]] = (i + j) / 2 + 1
i = j + 1
return r
def contraste_signos(x, mediana0=0.0):
d = np.asarray(x, float) - mediana0
d = d[d != 0] # los ceros no informan
n, s = len(d), int((d > 0).sum())
k = min(s, n - s)
return s, n, min(1.0, 2 * sum(comb(n, i) for i in range(k + 1)) / 2 ** n)
def nula_wilcoxon(n):
"""c[w] = nº de subconjuntos de {1..n} de suma w: coeficientes de prod(1 + q^k)."""
c = np.zeros(n * (n + 1) // 2 + 1)
c[0] = 1
for k in range(1, n + 1):
nuevo = c.copy()
nuevo[k:] += c[:len(c) - k]
c = nuevo
return c
def wilcoxon_signo(d, exacto=None):
d = np.asarray(d, float)
d = d[d != 0]
n = len(d)
r = rangos_medios(np.abs(d))
Wp = r[d > 0].sum()
t = np.unique(np.abs(d), return_counts=True)[1]
if exacto is None:
exacto = n <= 25 and (t == 1).all()
if exacto:
c = nula_wilcoxon(n)
w = int(round(Wp))
p = min(1.0, 2 * min(c[:w + 1].sum(), c[w:].sum()) / c.sum())
else:
var = n * (n + 1) * (2 * n + 1) / 24 - (t ** 3 - t).sum() / 48
z = max(0.0, abs(Wp - n * (n + 1) / 4) - 0.5) / np.sqrt(var)
p = 2 * stats.norm.sf(z)
return Wp, p
x = [3, 1, 2, 2, 5]
print("rangos medios:", rangos_medios(x), "| rankdata:", stats.rankdata(x))
rng = np.random.default_rng(7)
antes = rng.lognormal(5.0, 0.3, 12)
despues = antes * rng.lognormal(-0.08, 0.12, 12) # mejora típica del 8 %
d = despues - antes
print("\ndiferencias (ms):", np.round(d, 1))
s, n, p = contraste_signos(d)
print(f"signos: S = {s} de {n}, p exacto = {p:.4f} (scipy binomtest: {stats.binomtest(s, n, 0.5).pvalue:.4f})")
W, p = wilcoxon_signo(d)
res = stats.wilcoxon(d, method="exact")
print(f"Wilcoxon: W+ = {W:.0f}, p exacto = {p:.4f} (scipy: W- = {res.statistic:.0f}, p = {res.pvalue:.4f})")
print(f"E[W+] = {n*(n+1)/4}, Var = {n*(n+1)*(2*n+1)/24:.2f}")
# con empates y ceros descartados: normal con corrección
d2 = np.array([1, -1, 2, 2, -3, 3, 3, 4, 5, -5, 6, 7, 7, 8, 9.0])
W2, p2 = wilcoxon_signo(d2)
print(f"\ncon empates: W+ = {W2}, p normal = {p2:.4f} (scipy: {stats.wilcoxon(d2, method='approx', correction=True).pvalue:.4f})")Results agree with scipy to the last digit. With the same twelve differences, sign test gives and Wilcoxon . Eleven differences are negative, and the only positive ( ms) has smallest magnitude: sign test counts it as one sign, while Wilcoxon weights magnitude, gives it rank 1, and obtains , almost as extreme as possible. The second cell implements Mann–Whitney (exact distribution by memoized recursion and tie correction) and Kruskal–Wallis, checking three facts: null law under heavy tails, mean and variance of , and that hand-built ROC AUC is .
import numpy as np
from functools import lru_cache
from scipy import stats
@lru_cache(maxsize=None)
def cuenta_u(m, n):
"""c[u] = nº de configuraciones de m x y n y (sin empates) con U = u. Recursión sobre la mayor observación."""
if m == 0 or n == 0:
return (1,)
a, b = cuenta_u(m - 1, n), cuenta_u(m, n - 1) # la mayor es una x (gana n pares) o una y (no gana ninguno)
c = [0] * (m * n + 1)
for u, v in enumerate(a):
c[u + n] += v
for u, v in enumerate(b):
c[u] += v
return tuple(c)
def mann_whitney(x, y, exacto=None):
x, y = np.asarray(x, float), np.asarray(y, float)
m, n = len(x), len(y)
todo = np.concatenate([x, y])
W = rangos_medios(todo)[:m].sum()
U = W - m * (m + 1) / 2
N = m + n
t = np.unique(todo, return_counts=True)[1]
if exacto is None:
exacto = (t == 1).all() and m * n <= 400
if exacto:
c = np.array(cuenta_u(m, n), float)
u = int(round(U))
p = min(1.0, 2 * min(c[:u + 1].sum(), c[u:].sum()) / c.sum())
else:
var = m * n / 12 * (N + 1 - (t ** 3 - t).sum() / (N * (N - 1)))
p = 2 * stats.norm.sf(max(0.0, abs(U - m * n / 2) - 0.5) / np.sqrt(var))
return U, W, U / (m * n), p
def kruskal_wallis(*grupos):
todo = np.concatenate(grupos)
N = len(todo)
r = rangos_medios(todo)
medias = np.array([g.mean() for g in np.split(r, np.cumsum([len(g) for g in grupos])[:-1])])
tam = np.array([len(g) for g in grupos])
H = 12 / (N * (N + 1)) * (tam * (medias - (N + 1) / 2) ** 2).sum()
t = np.unique(todo, return_counts=True)[1]
H /= 1 - (t ** 3 - t).sum() / (N ** 3 - N) # corrección por empates
return H, stats.chi2.sf(H, len(grupos) - 1)
rng = np.random.default_rng(11)
x = np.round(rng.lognormal(4.9, 0.4, 9), 1)
y = np.round(rng.lognormal(4.5, 0.4, 11), 1)
U, W, auc, p = mann_whitney(x, y)
e = stats.mannwhitneyu(x, y, method="exact")
print(f"m = 9, n = 11: U = {U:.0f}, W = {W:.0f}, U/(mn) = {auc:.3f}, p exacto = {p:.4f} | scipy: U = {e.statistic:.0f}, p = {e.pvalue:.4f}")
# el AUC de la curva ROC construida a mano (x = positivos) es U/(mn)
umbrales = np.sort(np.concatenate([x, y]))[::-1]
tpr = np.r_[0, [(x >= c).mean() for c in umbrales]]
fpr = np.r_[0, [(y >= c).mean() for c in umbrales]]
print(f"área bajo la ROC (trapecios) = {np.sum(np.diff(fpr) * (tpr[1:] + tpr[:-1]) / 2):.4f} y U/(mn) = {auc:.4f}")
xt = np.array([1, 2, 2, 3, 5, 5, 8, 9.0])
yt = np.array([2, 3, 3, 4, 9, 10, 11.0])
print(f"con empates: p normal = {mann_whitney(xt, yt)[3]:.4f} | scipy asintótico con continuidad: {stats.mannwhitneyu(xt, yt, method='asymptotic', use_continuity=True).pvalue:.4f}")
# la ley nula no depende de F: colas de Cauchy (sin media ni varianza), m = n = 8
R, m, n = 6000, 8, 8
us = np.empty(R)
rechazos = 0
for k in range(R):
U, _, _, p = mann_whitney(rng.standard_cauchy(m), rng.standard_cauchy(n))
us[k] = U
rechazos += p <= 0.05
c = np.array(cuenta_u(m, n), float)
tam_exacto = sum(c[u] for u in range(m * n + 1) if min(1.0, 2 * min(c[:u + 1].sum(), c[u:].sum()) / c.sum()) <= 0.05) / c.sum()
print(f"\nU bajo H0 con Cauchy: media {us.mean():.2f} (teoría {m*n/2}), varianza {us.var():.2f} (teoría {m*n*(m+n+1)/12:.2f})")
print(f"tamaño del test a nivel 0.05: simulado {rechazos / R:.4f}, exacto {tam_exacto:.4f}")
g1, g2, g3 = rng.lognormal(0, 1, 15), rng.lognormal(0.6, 1, 12), rng.lognormal(0.2, 1, 10)
H, pk = kruskal_wallis(g1, g2, g3)
sc = stats.kruskal(g1, g2, g3)
print(f"\nKruskal-Wallis: H = {H:.4f}, p = {pk:.4f} | scipy: H = {sc.statistic:.4f}, p = {sc.pvalue:.4f}")
H2, _ = kruskal_wallis(g1, g2)
z = (mann_whitney(g1, g2, exacto=False)[0] - 15 * 12 / 2) / np.sqrt(15 * 12 * 28 / 12)
print(f"con k = 2, H = {H2:.4f} y el z² de Mann-Whitney sin corrección de continuidad vale {z**2:.4f}")A null-law detail: under Cauchy, which lacks even a mean, has exactly the theorem’s mean and variance (simulation gives and versus and ) and maintains level; exact size is , reproduced in simulation. That is distribution-freeness. (With the test is almost exactly 5 %: discreteness usually leaves actual size below nominal.)
Asymptotic relative efficiency: the cost of not assuming normality
Under normality is optimal (uniformly most powerful unbiased). What do ranks lose? Compare sample sizes for equal power, giving a clean limiting answer.
For asymptotically normal statistics there is a simple formula. If has mean and standard deviation under , its efficacy is and : with local alternative each test’s standardized signal is , which alone determines power. A shift test’s efficacy is its mean rise per unit shift divided by measurement noise.
The bound minimizes over fixed-variance densities (calculus of variations): the minimum occurs at parabola for . ARE can be arbitrarily large under heavy tails. Why: measures shift against noise , inflated without bound by a few extremes, while ranks use , driven mostly by central mass.
| Distribution | Wilcoxon vs | Sign vs |
|---|---|---|
| Uniform | ||
| Normal | ||
| Logistic | ||
| with 5 df | ||
| Laplace (double exponential) | ||
| with 3 df | ||
| 90 % + 10 % |
The table quantifies gains and losses: with normals, 4.7 % more data; with , nearly half the data. The figure simulates finite-sample versions: where each curve crosses 80 % power and the ratio of squared shifts.
One theoretical refinement: Wilcoxon is not the only rank test. Normal-score tests (van der Waerden) replace each rank by its corresponding normal quantile; Chernoff and Savage (1958) showed their ARE against is for every distribution, with equality only under normality. In this precise sense ranks “never lose” to the mean. Wilcoxon remains standard for simplicity, tables and interpretation (AUC), with efficiency never below 86.4 % (at worst 16 % more data).
Goodness of fit: the empirical distribution function
Everything so far compares samples. Another question is whether a sample is compatible with a specified distribution (or family such as normal). The tool is the empirical distribution function , a staircase with jumps .
Glivenko–Cantelli: the whole ECDF converges
For fixed , is the mean of indicators with expectation , converging by the strong law. Remarkably convergence is uniform in , allowing the ECDF to substitute for the entire distribution.
Proof
Proof for continuous (general case adapts using left limits; see probability’s Glivenko–Cantelli theorem). Fix and let for , with and , so . For , monotonicity of and gives
Therefore . The strong law at the points (finitely many) sends the maximum to almost surely, so almost surely. Since is arbitrary the limit is .
∎A second fact makes the ECDF a testing tool: the law of does not depend on if is continuous. By the probability integral transform, are uniform on and , where is the ECDF of ; then . This statistic is distribution-free like ranks.
DKW inequality and confidence band
Convergence has order and an explicit bound valid for all .
Dvoretzky, Kiefer and Wolfowitz (1956) proved the inequality with unspecified exponential prefactor; Massart (1990) showed constant works and cannot be improved because it is the first term of Kolmogorov’s limiting distribution (below). Equating the bound to gives a band for the whole distribution function:
With and , : with a thousand observations the unknown distribution function is within percentage points of the empirical one everywhere at once. Width falls as , so halving it costs four times the data, the power-lesson law.
The key word is simultaneous. A 95 % interval for at each separately (pointwise band ) covers each point with probability , but probability of covering all points simultaneously is much lower: neighboring ECDF deviations are correlated and many points can fail. The figure measures this difference.
The figure suggests another point: the DKW bound is not loose. The limit law of is Kolmogorov’s, . The first term is DKW; the second at is order . The 95 % DKW band is practically exact. The cell checks this and pointwise behavior by simulation.
import numpy as np
from scipy import stats
rng = np.random.default_rng(3)
alpha, z = 0.05, stats.norm.ppf(0.975)
def cubre(u, eps):
"""Para uniformes ordenadas (por filas): ¿contiene la banda DKW a la identidad, y la banda puntual?"""
n = u.shape[1]
j = np.arange(1, n + 1)
D = np.maximum((j / n - u).max(1), (u - (j - 1) / n).max(1)) # distancia de Kolmogorov
h = z * np.sqrt(u * (1 - u) / n) # semianchura puntual en cada salto
puntual = ((np.abs(j / n - u) <= h) & (np.abs((j - 1) / n - u) <= h)).all(1)
return D <= eps, puntual
print(" n eps_n cobertura DKW cobertura puntual")
for n in (20, 50, 200, 1000):
u = np.sort(rng.random((4000, n)), axis=1)
dkw, pun = cubre(u, np.sqrt(np.log(2 / alpha) / (2 * n)))
print(f"{n:5d} {np.sqrt(np.log(2 / alpha) / (2 * n)):.4f} {dkw.mean():.4f} {pun.mean():.4f}")
print(f"\nsqrt(n) * eps_n = {np.sqrt(np.log(2 / alpha) / 2):.5f} (valor crítico de Kolmogorov al 5 %: {stats.kstwobign.isf(alpha):.5f})")
print(f"segundo término de la serie de Kolmogorov en ese punto: {2 * np.exp(-8 * np.log(2 / alpha) / 2):.1e}")Kolmogorov–Smirnov
Invert the band into a test of with fully specified . Reject when leaves the band, i.e. maximum ECDF-to- distance exceeds . This is Kolmogorov–Smirnov, using exact distribution of rather than the bound.
ECDF goodness-of-fit tests share the structure of measuring distance between and with a weighted norm and calibrating against its null (free of continuous by probability integral transform). The three most common have distinct purposes.
The first two compute at ordered data. For two samples, Kolmogorov–Smirnov compares ECDFs , calibrated with Kolmogorov using (or exactly with ranks via permutation). The supremum occurs at a jump, so evaluate both ECDFs on all observations: sorting costs . This is the coding exercise.
Estimated parameters: Lilliefors correction
is rarely fully known. We test “normal” or “lognormal” with mean and variance estimated from the same data. Standard Kolmogorov–Smirnov critical values then fail in a specific way: fitting parameters makes the fitted distribution closer to ECDF than a prespecified , systematically reducing and almost eliminating rejections.
The same applies to Anderson–Darling, whose critical values with fitted parameters differ from the simple case (for normality with fitted mean and variance, corrected rejects at 5 % above ). Shapiro–Wilk does this naturally through location–scale invariance. The next cell measures level and power of four normality tests with against five alternatives.
import numpy as np
from scipy import stats
def kd(x):
"""D de Kolmogorov-Smirnov contra la normal con media y desviación estimadas (por filas) y A*² de Anderson-Darling."""
n = x.shape[1]
s = np.sort(x, axis=1)
F = stats.norm.cdf((s - s.mean(1, keepdims=True)) / s.std(1, ddof=1, keepdims=True))
i = np.arange(1, n + 1)
D = np.maximum((i / n - F).max(1), (F - (i - 1) / n).max(1))
Fc = np.clip(F, 1e-12, 1 - 1e-12)
A2 = -n - ((2 * i - 1) * (np.log(Fc) + np.log(1 - Fc[:, ::-1]))).sum(1) / n
return D, A2 * (1 + 0.75 / n + 2.25 / n ** 2)
n, R = 50, 1000
rng = np.random.default_rng(3)
D0, A0 = kd(rng.normal(size=(8000, n)))
cD, cA = np.quantile(D0, 0.95), np.quantile(A0, 0.95) # Lilliefors y A*² por simulación
cW = np.quantile([stats.shapiro(f).statistic for f in rng.normal(size=(2000, n))], 0.05)
cKS = stats.kstwo.isf(0.05, n) # tabla de Kolmogorov (parámetros conocidos)
print(f"valores críticos al 5 % con n = {n}: KS estándar {cKS:.4f}, Lilliefors {cD:.4f}, A*² {cA:.3f}, W {cW:.4f}")
alt = {
"normal (nivel real)": lambda: rng.normal(size=(R, n)),
"t con 3 g.l.": lambda: rng.standard_t(3, (R, n)),
"uniforme": lambda: rng.random((R, n)),
"exponencial": lambda: rng.exponential(size=(R, n)),
"logística": lambda: rng.logistic(size=(R, n)),
"mezcla 50/50, separación 3": lambda: rng.normal(size=(R, n)) + 3 * (rng.random((R, n)) < .5),
}
print(f"\n{'alternativa':28s} KS estándar Lilliefors Anderson-D Shapiro-W")
for nombre, g in alt.items():
x = g()
D, A = kd(x)
W = np.array([stats.shapiro(f).statistic for f in x])
print(f"{nombre:28s} {np.mean(D > cKS):10.3f} {np.mean(D > cD):11.3f} {np.mean(A > cA):11.3f} {np.mean(W < cW):10.3f}")Standard KS has actual size and almost no power; Lilliefors calibration recovers level and some power, but Anderson–Darling and Shapiro–Wilk clearly beat it on common alternatives (heavy tails, uniform, skew), with Shapiro–Wilk best almost everywhere (: versus for tails, versus for uniform). A mixture of populations separated by three standard deviations, clearly bimodal, is detected at most 41 % of the time at (Anderson–Darling wins there): bimodality is clearer in a histogram or QQ plot.
With large , everything is rejected
A fundamental problem no test solves: goodness of fit asks “is it exactly ?”, and for any real-world model the answer is no. Sufficient data detect that. A model can predict excellently yet be rejected at .
The second practical case uses numbers. Simulate service latencies with 3 % of requests on a slow path (shifted lognormal), fit three families by maximum likelihood (gamma and Weibull shape equations solved by vectorized Newton for thousands of repetitions), and test each with Kolmogorov–Smirnov and Anderson–Darling calibrated by parametric bootstrap with refitting, using Monte Carlo value .
import numpy as np
from scipy import stats
from scipy.special import digamma, polygamma
def muestra_latencias(n, rng, q=0.03):
"""Tiempos de respuesta (ms): una lognormal principal y una fracción q que sigue un camino más lento."""
lenta = rng.random(n) < q
return np.where(lenta, rng.lognormal(4.7, 0.3, n), rng.lognormal(4.0, 0.3, n))
# Estimadores de máxima verosimilitud vectorizados: una fila = una muestra
def ajusta_lognormal(x):
l = np.log(x)
return l.mean(1), l.std(1) # mu, sigma
def ajusta_gamma(x):
s = np.log(x.mean(1)) - np.log(x).mean(1)
k = (3 - s + np.sqrt((s - 3) ** 2 + 24 * s)) / (12 * s) # punto de partida
for _ in range(8): # Newton sobre ln k - digamma(k) = s
k = k - (np.log(k) - digamma(k) - s) / (1 / k - polygamma(1, k))
return k, x.mean(1) / k # forma, escala
def ajusta_weibull(x):
lx = np.log(x)
k = np.pi / (np.sqrt(6) * lx.std(1))
for _ in range(12): # Newton sobre la ecuación del EMV de la forma
xk = x ** k[:, None]
a = (xk * lx).sum(1) / xk.sum(1)
g = a - 1 / k - lx.mean(1)
dg = (xk * lx ** 2).sum(1) / xk.sum(1) - a ** 2 + 1 / k ** 2
k = k - g / dg
return k, ((x ** k[:, None]).mean(1)) ** (1 / k)
FAM = {
"lognormal": (ajusta_lognormal, lambda x, p: stats.norm.cdf((np.log(x) - p[0][:, None]) / p[1][:, None]),
lambda u, p: np.exp(p[0] + p[1] * stats.norm.ppf(u))),
"gamma": (ajusta_gamma, lambda x, p: stats.gamma.cdf(x, p[0][:, None], scale=p[1][:, None]),
lambda u, p: stats.gamma.ppf(u, p[0], scale=p[1])),
"Weibull": (ajusta_weibull, lambda x, p: stats.weibull_min.cdf(x, p[0][:, None], scale=p[1][:, None]),
lambda u, p: stats.weibull_min.ppf(u, p[0], scale=p[1])),
}
def estadisticos(F):
"""Kolmogorov-Smirnov D y Anderson-Darling A² de las filas de F = cdf ajustada en los datos ordenados."""
n = F.shape[1]
i = np.arange(1, n + 1)
D = np.maximum((i / n - F).max(1), (F - (i - 1) / n).max(1))
Fc = np.clip(F, 1e-12, 1 - 1e-12)
A2 = -n - ((2 * i - 1) * (np.log(Fc) + np.log(1 - Fc[:, ::-1]))).sum(1) / n
return D, A2
def contraste(nombre, x, B, rng):
"""D, A² y sus valores p: ingenuo (tabla de Kolmogorov) y por bootstrap paramétrico con reajuste en cada réplica."""
ajusta, cdf, ppf = FAM[nombre]
xs = np.sort(x)[None, :]
p = ajusta(xs)
D, A2 = (v[0] for v in estadisticos(cdf(xs, p)))
p_ingenuo = stats.kstest(x, lambda t: cdf(t[None, :], p)[0]).pvalue
sim = ppf(rng.random((B, len(x))), p)
sim.sort(axis=1)
Ds, A2s = estadisticos(cdf(sim, ajusta(sim)))
return D, A2, p_ingenuo, (1 + (Ds >= D).sum()) / (B + 1), (1 + (A2s >= A2).sum()) / (B + 1)
rng = np.random.default_rng(5)
x = muestra_latencias(150, rng)
print(f"n = {len(x)}: media {x.mean():.1f} ms, mediana {np.median(x):.1f} ms, p99 {np.quantile(x, .99):.0f} ms")
kk, _, ss = stats.gamma.fit(x, floc=0)
print(f"gamma: forma propia {ajusta_gamma(np.sort(x)[None, :])[0][0]:.4f}, scipy {kk:.4f}")
print("\nfamilia D p KS estándar p KS (Lilliefors) A² p AD")
for nombre in FAM:
D, A2, pi, pk, pa = contraste(nombre, x, 1000, rng)
print(f"{nombre:10s} {D:.4f} {pi:8.4f} {pk:8.4f} {A2:6.2f} {pa:8.4f}")At neither lognormal nor gamma is rejected (only a few requests are slow), but Weibull is; the standard Kolmogorov-table supplied by scipy.stats.kstest is much higher than correct. The same experiment with twenty times larger also rejects lognormal and gamma despite an unchanged generating mechanism.
rng = np.random.default_rng(5)
x = muestra_latencias(3000, rng)
print(f"n = {len(x)}")
print("\nfamilia D p KS (Lilliefors) A² p AD (el menor p posible con 100 réplicas es 1/101 = 0.0099)")
for nombre in FAM:
D, A2, pi, pk, pa = contraste(nombre, x, 100, rng)
print(f"{nombre:10s} {D:.4f} {pk:8.4f} {A2:7.2f} {pa:8.4f}")All three families are rejected, but distance tells another story: lognormal is percentage points from ECDF at its worst point (), gamma , Weibull nearly . Stop asking “does it pass?” and ask “how far off, and where?” A quantile–quantile plot helps.
QQ plots: inspect the distribution, not just test it
Tests give a probability; plots show where and how fit fails. Quantile–quantile plots compare sample with theoretical quantiles.
This makes it useful: the axis is calibrated by shape, discarding mean and spread as nuisance parameters so only shape remains. Points follow a line because estimates quantile with approximate variance : large in tails (small density ), small at center, so extreme points naturally move around. Draw an expected-variation band (as in the figure) rather than judging endpoints by eye.
Four normal-reference signatures worth remembering:
| Appearance | Meaning |
|---|---|
| Straight center, ends outward: right above and left below (S) | heavier tails than normal (more extremes, as in with few degrees of freedom) |
| Line with ends inward (inverted S) | lighter tails (bounded, like uniform) |
| Arch: concave upward | positive skew (long right tail); concave downward means negative |
| Step: steep center between flatter segments | bimodality or mixture of populations; regular steps suggest discrete or rounded data |
QQ plots also suggest action. Heavy tails favor robust methods or ranks (where Wilcoxon wins by ARE). Positive skew (times, prices, sizes) favors logarithms, confirmed by the log QQ. A mixture suggests separating populations. QQ-axis correlation is essentially Shapiro–Wilk: the test compresses the plot to one number, at the cost of only saying yes or no.
Using libraries
scipy.stats supplies everything here. The next cell repeats calculations with new data, comparing our earlier functions with library implementations, and adds Shapiro–Wilk, the only test not implemented by hand, and the Anderson–Darling critical-value table supplied by scipy.
import numpy as np
from scipy import stats
rng = np.random.default_rng(21)
a = rng.lognormal(4.6, 0.3, 40)
b = rng.lognormal(4.8, 0.5, 35)
d = a[:30] * rng.lognormal(0.05, 0.1, 30) - a[:30]
print("Wilcoxon (rangos con signo): propio", round(wilcoxon_signo(d, exacto=False)[1], 5), "| scipy", round(stats.wilcoxon(d, method="approx", correction=True).pvalue, 5))
print("Mann-Whitney (normal): propio", round(mann_whitney(a, b, exacto=False)[3], 5), "| scipy", round(stats.mannwhitneyu(a, b, method="asymptotic", use_continuity=True).pvalue, 5))
print("Kruskal-Wallis, 3 grupos: propio", round(kruskal_wallis(a[:20], a[20:], b)[1], 5), "| scipy", round(stats.kruskal(a[:20], a[20:], b).pvalue, 5))
# Kolmogorov-Smirnov de una y de dos muestras
ks1 = stats.kstest((np.log(a) - np.log(a).mean()) / np.log(a).std(ddof=1), "norm")
ks2 = stats.ks_2samp(a, b)
print(f"\nKS de una muestra (parámetros estimados, p NO válido): D = {ks1.statistic:.4f}, p = {ks1.pvalue:.4f}")
print(f"KS de dos muestras: D = {ks2.statistic:.4f}, p = {ks2.pvalue:.4f}")
# normalidad de log(a): Shapiro-Wilk y Anderson-Darling (este devuelve estadístico y valores críticos)
sw = stats.shapiro(np.log(a))
ad = stats.anderson(np.log(a), "norm")
print(f"\nShapiro-Wilk de log(a): W = {sw.statistic:.4f}, p = {sw.pvalue:.4f}")
print(f"Anderson-Darling de log(a): A² = {ad.statistic:.4f}, críticos {np.round(ad.critical_values, 3)} para los niveles {ad.significance_level} %")
# y de a sin transformar: asimetría que el QQ ya mostraba
print(f"Shapiro-Wilk de a (sin log): W = {stats.shapiro(a).statistic:.4f}, p = {stats.shapiro(a).pvalue:.4f}")Two observations. stats.anderson returns not a value but a statistic with critical values at (with fitted parameters, already Lilliefors-corrected). stats.kstest with fitted parameters returns an invalid , as described above. For goodness of fit with estimated parameters, simulate the null as for latency.
Common mistakes
Exercises
Step 1 of 4. What can be said about the law of each ?
ks_dos_muestras(x, y) returns two-sample Kolmogorov–Smirnov statistic in : the supremum occurs at a jump, so evaluate both right-continuous ECDFs on all pooled values using np.searchsorted(..., side='right'). It must handle ties. banda_dkw(n, alpha) returns half-width . Tests compare with scipy.stats.ks_2samp.import numpy as np
def ks_dos_muestras(x, y):
"""D = sup_t |F_m(t) - G_n(t)| con coste O((m + n) log(m + n))."""
x, y = np.sort(x), np.sort(y)
# tu código: evalúa las dos ECDF en todos los datos y toma el máximo de la diferencia absoluta
return 0.0
def banda_dkw(n, alpha=0.05):
"""Semianchura epsilon de la banda DKW de nivel 1 - alpha."""
return 0.0More than one answer may be correct.
scipy.stats.kstest on data standardized with their own mean and standard deviation, obtaining and . What follows?Summary
- Ranks. Exchangeable untied data have rank vector uniform over permutations: rank statistics are distribution-free, exact in small samples and invariant to monotone transforms.
- Signs and Wilcoxon. The sign test concerns median and is without further assumptions. Signed ranks sum under symmetry, mean , variance . Treat zeros and ties explicitly.
- Mann–Whitney. counts pairwise comparisons and unbiasedly estimates , AUC. It tests stochastic superiority, not medians. Under : mean , variance .
- Kruskal–Wallis. is ANOVA on ranks, asymptotically ; for it is Mann–Whitney . Pairwise comparisons use Dunn and multiplicity correction.
- ARE. : for normals, at least always, for Laplace and for . Sign versus : under normality.
- Goodness of fit. Glivenko–Cantelli: distance is distribution-free, and DKW band is simultaneous and nearly exact (unlike pointwise). Kolmogorov–Smirnov monitors center, Anderson–Darling tails, and Shapiro–Wilk is most powerful for normality. Fit parameters require simulated calibration (Lilliefors); at large everything is rejected, and QQ shows how and where.