Uncertainty analysis, propagation and communication
Quantify uncertainty around a number. Propagate it through functions of several quantities with linear rules and Monte Carlo, distinguish confidence, prediction and tolerance intervals, combine estimates with inverse-variance weighting and model heterogeneity, and communicate the resulting uncertainty.
After this lesson you can
- Propagate uncertainty using a linear approximation with covariances and using Monte Carlo, and diagnose when linearization fails.
- Compute tolerance intervals and identify when they answer the question better than confidence or prediction intervals.
- Combine independent estimates with inverse-variance weighting and estimate between-source heterogeneity with DerSimonian–Laird and I².
- Choose and label error bars as standard deviations, standard errors or intervals, and interpret overlap correctly.
- Report estimates, intervals, assumptions and sources of unquantified uncertainty.
Before you start
Motivation: a single number is not a result
A security manager must budget the expected annual cost of incidents for a service. The model is as simple as it looks: , with incidents per year, the average cost of each, and the fraction of risk the current control does not eliminate. None of the three factors is known: comes from counting past incidents, from a small sample of costs, and from expert judgment. This is the pattern throughout: a quantity of interest that is a function of several uncertain quantities. The same applies to latency of a composite service (a sum of stages with different distributions) or model performance measured on several evaluation sets.
The next cell’s figures are illustrative, not from a real system. First, what a hurried report would do: multiply point estimates. Then, what this lesson teaches: propagate uncertainty in each ingredient to the answer.
import numpy as np
rng = np.random.default_rng(26)
M = 1_000_000
# Ingredientes (cifras didácticas): incidentes por año, coste medio por incidente (k€) y fracción de riesgo que no elimina el control
lam_hat, u_lam = 2.0, np.sqrt(6) / 3 # 6 incidentes en 3 años: tasa 2 por año, incertidumbre de Poisson sqrt(k)/T
c_hat, u_c = 85.0, 18.0 # k€, a partir de 12 incidentes pasados
r_hat, u_r = 0.40, 0.10 # juicio de expertos: 1 - eficacia del control
L_hat = lam_hat * c_hat * r_hat
rel = np.sqrt((u_lam / lam_hat) ** 2 + (u_c / c_hat) ** 2 + (u_r / r_hat) ** 2)
u_L = L_hat * rel
print(f"cifra única: L = {L_hat:.1f} k€ al año")
print(f"ley lineal: u = {u_L:.1f} k€ ({100 * rel:.0f} %), intervalo al 95 %: [{L_hat - 1.96 * u_L:.1f}, {L_hat + 1.96 * u_L:.1f}]")
# Monte Carlo con distribuciones que respetan el dominio de cada magnitud (positiva, positiva, en [0, 1])
lam = rng.gamma(6, 1 / 3, M) # media 2, desviación típica sqrt(6)/3
s2 = np.log(1 + (u_c / c_hat) ** 2)
c = rng.lognormal(np.log(c_hat) - s2 / 2, np.sqrt(s2), M) # media 85, desviación típica 18
kb = r_hat * (1 - r_hat) / u_r ** 2 - 1
r = rng.beta(r_hat * kb, (1 - r_hat) * kb, M) # media 0.40, desviación típica 0.10
L = lam * c * r
lo, med, hi = np.percentile(L, [2.5, 50, 97.5])
print(f"Monte Carlo: media {L.mean():.1f}, desviación típica {L.std():.1f}, mediana {med:.1f}")
print(f" intervalo al 95 %: [{lo:.1f}, {hi:.1f}]")
print(f"P(L > 100 k€) = {np.mean(L > 100):.3f}; P(L > extremo superior lineal) = {np.mean(L > L_hat + 1.96 * u_L):.3f}")The single figure, k€, is correct as a central value and misleading as a summary. The linear law gets the spread right (about k€) but draws a symmetric interval reaching k€: a negative cost the model does not allow. Monte Carlo, using distributions respecting the domain, gives an asymmetric interval, : true risk is shifted upward and the probability of exceeding k€ is almost one in six, information neither the single figure nor the linear law contains. This lesson builds both tools (linear law and Monte Carlo), teaches when to trust each, and closes with three parts of the craft: choosing the interval that answers the question (confidence, prediction or tolerance), combining estimates from different sources, and communicating results without misleading.
We use without further explanation standard error, confidence and prediction intervals, the delta method, nonparametric bootstrap, simulation studies and effect size, as well as the covariance matrix, gradient and linearization.
Three kinds of uncertainty and two ways to evaluate it
Not all uncertainty in a result is of the same kind; mixing kinds is a major source of misleading reports.
- Sampling. Comes from observing a finite sample from a varying process. It decreases as grows, typically like , and is studied by the module’s classical inference.
- Measurement. Comes from the instrument: resolution, calibration, drift. Repeating measurement does not reduce it if the defect is the same every time (a clock with constant offset carries it into every reading).
- Model. Comes from potentially false functional form or assumptions: independence, distribution, relationships between quantities. No sample from the model itself quantifies it; explore it by model comparison and sensitivity analysis, and disclose it if not quantified.
The GUM (Guide to the expression of uncertainty in measurement, JCGM 100:2008), the international metrology standard, adds a practical distinction about how each component is evaluated, distinct from “random versus systematic”.
The table lists common type-B conversions. They come from calculating each distribution’s variance: a uniform distribution on has variance , and a symmetric triangular distribution with the same half-width has (less dispersed because it concentrates mass at the center).
| Available information | Assigned distribution | |
|---|---|---|
| Value within , nothing else known | uniform | |
| Value within , central values more likely | triangular | |
| Certificate: with coverage factor | normal | |
| Digital resolution (last digit) | uniform with | |
| Poisson events in time | estimated rate |
Independent components combine in quadrature, (later we see the rule with sensitivities and correlations), and the result is expressed using expanded uncertainty , where coverage factor must be the quantile of an with Welch–Satterthwaite effective degrees of freedom:
where type-B components with solid information count as . The value is merely customary for large . The next cell builds a latency measurement’s budget with three components.
import numpy as np
from scipy import stats
# 10 lecturas con un cronómetro: media 25.40 ms y desviación típica 0.45 ms (tipo A)
n, xbar, s = 10, 25.40, 0.45
comp = {
"repetibilidad (tipo A)": (s / np.sqrt(n), n - 1), # u = s / sqrt(n), nu = 9
"resolución 0.1 ms (tipo B, unif.)": (0.1 / (2 * np.sqrt(3)), np.inf), # a = 0.05
"calibración ±0.30 ms, k = 2 (B)": (0.30 / 2, np.inf),
}
uc2 = sum(u ** 2 for u, _ in comp.values())
uc = np.sqrt(uc2)
denom = sum(u ** 4 / nu for u, nu in comp.values())
nu_ef = uc ** 4 / denom
k = stats.t.ppf(0.975, nu_ef)
for nombre, (u, nu) in comp.items():
print(f"{nombre:36s} u = {u:.4f} ms {100 * u ** 2 / uc2:5.1f} % de u_c^2")
print(f"u_c = {uc:.4f} ms, grados de libertad efectivos = {nu_ef:.1f}, k = {k:.3f}, U = {k * uc:.3f} ms")
print(f"resultado: {xbar:.2f} ± {k * uc:.2f} ms (k = {k:.2f}, nivel aproximado 95 %)")Two observations: repeatability and calibration dominate while clock resolution hardly matters, which the budget shows and intuition does not; and since the type-A component, the only one with few degrees of freedom (), contributes almost half the variance, effective degrees of freedom fall to about and the coverage factor is , not exactly . With only three readings, the same calculation would give a much larger factor.
Linear propagation law
Given with inputs of known uncertainty, we want the uncertainty of . Start by visualizing it.
The linear law replaces by its tangent plane at the nominal value. In the left figure this turns level curves of into parallel lines: the linear interval is exact when curves are straight and fails to the extent they curve inside the input ellipse. With , level curves are straight lines fanning out from the origin: the smaller , the faster changes, so the symmetric linear interval falls short above and extends too far below.
Proof
The first two statements are properties of a linear form: and . For the third, Taylor’s theorem with Lagrange remainder gives, for each realization, with on the segment joining and , hence . Standard deviation is the norm of the centered variable, and centering does not increase the norm, so by Minkowski’s triangle inequality
If , the right side is , of order , while is of order .
∎This is the delta-method argument, except that here there is no : the small parameter is relative input dispersion. It shows where the law fails: the bound grows with curvature and the inputs’ fourth moment. Two theorem conditions fail in examples that matter. The Hessian of is unbounded near , and that of grows with . If is normal, has neither finite mean nor variance, because has a nonintegrable singularity at : a Monte Carlo standard deviation is then meaningless and changes between runs (check the figure: with at , the “Monte Carlo ” jumps between configurations, unlike percentiles). A coverage interval is well defined, so Monte Carlo reports it.
Special cases worth remembering
With coefficients and correlations , expanding gives
- Sum or difference, : . With , the sum has more uncertainty than quadrature and the difference less. Two latencies measured with the same clock share its offset: the difference cancels it, the sum doubles it.
- Products and ratios, : since , with ,
Relative uncertainties add in quadrature and the exponent is squared: a denominator with dominates numerators with and (you will calculate it in an exercise).
- Second order. For normal inputs, and . For with and , relative mean bias is about (simulation gives ) and simulated standard deviation is of nominal value, not the linear law’s (the second-order formula reaches ): linearization is no longer a reliable spread approximation. With simulated standard deviation is erratic and can exceed the linear value tens of times (one run of two million draws gave relative deviation versus ), because the ratio of normals no longer has finite variance.
Monte Carlo propagation
If the linear law analyzes the derivative, Monte Carlo is the experiment: simulate input uncertainty and observe the output. The GUM devotes Supplement 1 (JCGM 101:2008) to it.
This is a simulation study without an unknown parameter: the input distribution is known and the output distribution is wanted. Three practical issues:
- How many draws. Numerical error of sample percentile is , with the output density at that percentile. Density is small in tails and error large: thus the guide requires large relative to , for example (two hundred thousand for ; it suggests as a starting value), or an adaptive procedure increasing until endpoints stabilize to the number of digits to report.
- Seed and reproducibility. Fix and disclose it. Runs with different seeds should agree in published digits.
- Validating the linear law. The recommended check compares coverage endpoints from the linear law and Monte Carlo, accepting linearization only when they agree within numerical tolerance. The figure does this with the aquamarine versus violet bars.
A propagator from scratch
We build the propagator in three pieces: gradient by centered finite differences, the linear law (with each input’s coefficient to see where uncertainty comes from), and correlated-input sampling via Cholesky factorization.
import numpy as np
import sympy as sp
def gradiente(f, x, rel=1e-6):
"""Gradiente de f: R^p -> R por diferencias centradas, con paso relativo a cada coordenada."""
x = np.asarray(x, float)
g = np.zeros_like(x)
for i in range(x.size):
d = rel * max(abs(x[i]), 1e-3)
xp, xm = x.copy(), x.copy()
xp[i] += d
xm[i] -= d
g[i] = (f(xp) - f(xm)) / (2 * d)
return g
def propaga_lineal(f, mu, Sigma):
"""u(Y) = sqrt(g' Sigma g); devuelve f(mu), u, el gradiente y el aporte de cada entrada a u^2 (con los cruces repartidos)."""
mu, Sigma = np.asarray(mu, float), np.asarray(Sigma, float)
g = gradiente(f, mu)
aportes = g * (Sigma @ g) # suma de aportes = g' Sigma g
return f(mu), np.sqrt(g @ Sigma @ g), g, aportes
# Q = A·B/C con incertidumbres relativas del 3 %, 4 % y 12 % e independientes
mu = np.array([10.0, 20.0, 5.0])
Sigma = np.diag((np.array([0.03, 0.04, 0.12]) * mu) ** 2)
Q = lambda x: x[0] * x[1] / x[2]
q0, u, g, ap = propaga_lineal(Q, mu, Sigma)
print(f"Q = {q0:.2f}, u(Q) = {u:.3f} (relativa {100 * u / q0:.2f} %)")
print("aporte de A, B, C a u^2:", np.round(100 * ap / ap.sum(), 1), "%")
# contraste con el gradiente exacto de sympy
a, b, c = sp.symbols("a b c")
gs = sp.lambdify((a, b, c), [sp.diff(a * b / c, v) for v in (a, b, c)])
print("gradiente numérico :", np.round(g, 6))
print("gradiente de sympy :", np.round(gs(*mu), 6))The denominator’s contributes of total variance ( of in relative-formula units): if the budget allows improving only one measurement, the choice is clear. Numerical and symbolic gradients agree in every displayed digit.
import numpy as np
def muestrea_normal(mu, Sigma, M, rng):
"""M vectores de N(mu, Sigma) mediante la factorización de Cholesky Sigma = L L'."""
L = np.linalg.cholesky(np.asarray(Sigma, float))
return np.asarray(mu, float) + rng.standard_normal((M, len(mu))) @ L.T
def resumen(y, p=0.95):
"""Media, desviación típica, intervalo simétrico en probabilidad e intervalo más corto de cobertura p."""
y = np.sort(np.asarray(y))
M = y.size
simetrico = np.percentile(y, [100 * (1 - p) / 2, 100 * (1 + p) / 2])
m = int(np.ceil(p * M))
anchos = y[m - 1:] - y[: M - m + 1] # todas las ventanas de m valores consecutivos
j = int(np.argmin(anchos))
return y.mean(), y.std(), simetrico, (y[j], y[j + m - 1])
rng = np.random.default_rng(5)
M = 400_000
# Prueba de cordura: para una función lineal con entradas normales la ley lineal es exacta.
# D = T1 - T2, u1 = 3, u2 = 4, con correlación rho entre las dos latencias.
for rho in (-0.6, 0.0, 0.6):
Sigma = np.array([[9.0, rho * 12], [rho * 12, 16.0]])
X = muestrea_normal([50.0, 40.0], Sigma, M, rng)
d = X[:, 0] - X[:, 1]
print(f"rho = {rho:+.1f}: u lineal = {np.sqrt(9 + 16 - 2 * rho * 12):.3f}, u Monte Carlo = {d.std():.3f}")
# Un caso no lineal: cociente Q = A/B con B al 25 % (normal)
X = muestrea_normal([10.0, 5.0], np.diag([1.0, 1.25 ** 2]), M, rng)
q = X[:, 0] / X[:, 1]
media, sd, sim, corto = resumen(q)
print(f"A/B: nominal 2.00, media {media:.2f}")
print(f" intervalo simétrico en probabilidad [{sim[0]:.2f}, {sim[1]:.2f}] (anchura {sim[1] - sim[0]:.2f})")
print(f" intervalo más corto [{corto[0]:.2f}, {corto[1]:.2f}] (anchura {corto[1] - corto[0]:.2f})")
print(f" lineal: 2.00 ± {1.96 * 2 * np.hypot(0.1, 0.25):.2f}")With uncertainty in the difference rises to and with falls to : the same cancellation as clocks with shared offset. For a linear function, the linear law is exact with normal inputs, and Monte Carlo reproduces it to numerical error, a sanity check for the code. For the ratio, the shortest interval (width ) is narrower than the probability-symmetric interval () because the distribution is asymmetric: with a long right tail, trim the tail and keep the dense region. Neither resembles linear interval , symmetric around a nominal value that is no longer the distribution center (simulated mean ).
We still need to see how many draws are needed. Numerical error of an endpoint is ; the cell measures it by repeating the experiment and compares it with that formula, estimating density at percentile using a large Monte Carlo run.
import numpy as np
rng = np.random.default_rng(11)
f = lambda a, b: a / b
mu, sd = np.array([10.0, 5.0]), np.array([1.0, 1.0])
def extremo(M):
a = rng.normal(mu[0], sd[0], M)
b = rng.normal(mu[1], sd[1], M)
return np.percentile(f(a, b), 97.5)
# densidad de la salida en el percentil 97.5, a partir de un Monte Carlo grande
ref = f(rng.normal(10, 1, 2_000_000), rng.normal(5, 1, 2_000_000))
q = np.percentile(ref, 97.5)
h = 0.02
dens = np.mean(np.abs(ref - q) < h) / (2 * h)
print(f"{'M':>9s} {'desv. típica del extremo (30 repeticiones)':>46s} {'teoría':>9s}")
for M in (1_000, 10_000, 100_000):
ex = [extremo(M) for _ in range(30)]
teo = np.sqrt(0.975 * 0.025 / M) / dens
print(f"{M:9d} {np.std(ex, ddof=1):46.4f} {teo:9.4f}")Error decreases like , as predicted: with the upper endpoint’s standard deviation is almost and the interval’s first decimal is already noise; with it drops to and with to (the formula gives ; with 30 repetitions the deviation itself has relative error , plus error in estimated density). Publishing two significant digits needs only ; the guide’s default million gives another digit of margin.
With the machinery ready, return to the motivating problem and study correlation between incident rate and mean cost (for example, both increase with service exposure). Marginals stay the same (gamma, lognormal, beta), and dependence is introduced with a Gaussian copula: draw a multivariate normal with desired correlation, pass each coordinate through to obtain uniforms, and apply each marginal’s quantile function.
import numpy as np
from scipy import stats
rng = np.random.default_rng(26)
M = 200_000
marg = [
stats.gamma(6, scale=1 / 3), # tasa de incidentes: media 2
stats.lognorm(s=np.sqrt(np.log(1 + (18 / 85) ** 2)), scale=85 / np.sqrt(1 + (18 / 85) ** 2)), # coste medio: media 85
stats.beta(9.2, 13.8), # fracción no eliminada: media 0.4
]
def simula(rho_lc):
R = np.array([[1, rho_lc, 0], [rho_lc, 1, 0], [0, 0, 1.0]])
z = rng.standard_normal((M, 3)) @ np.linalg.cholesky(R).T
u = stats.norm.cdf(z)
x = np.column_stack([m.ppf(u[:, i]) for i, m in enumerate(marg)])
return x[:, 0] * x[:, 1] * x[:, 2]
print(f"{'rho(tasa, coste)':>17s} {'media':>7s} {'desv. típ.':>11s} {'intervalo al 95 %':>22s} {'P(L > 100)':>11s}")
for rho in (-0.6, 0.0, 0.6):
L = simula(rho)
lo, hi = np.percentile(L, [2.5, 97.5])
print(f"{rho:17.1f} {L.mean():7.1f} {L.std():11.1f} {'[%.1f, %.1f]' % (lo, hi):>22s} {np.mean(L > 100):11.3f}")The mean changes with correlation (from to k€: the product of positively correlated variables has a higher mean), standard deviation grows nearly , from to , and probability of exceeding k€ rises from to . Ignoring plausible correlation is not neutral: it assumes , which the report should state.
Confidence, prediction and tolerance: three different questions
Given a sample from an assumed normal process, three intervals are constantly confused. They share center and form , but answer different questions.
| Question | Interval | Half-width (normal) | With |
|---|---|---|---|
| Where is mean ? | Confidence | shrinks to a point | |
| Where will the next observation fall? | Prediction | tends to | |
| Which interval contains at least proportion of the population? | Tolerance | tends to |
Prediction half-width follows because is independent of : the new observation contributes its own variance in addition to the mean’s, and the ratio with is . Hence : never disappears however large becomes, because variability of one observation is irreducible.
The prediction interval averages over samples ( is mean content); tolerance requires high content in the particular sample, with high confidence. Thus tolerance is wider, especially for small . For specifications such as “ of requests take less than ms”, it is the right tool because a guaranteed threshold is requested, not one correct on average.
The normal tolerance factor
For a one-sided bound there is an exact formula. Let and , with independent of . Upper bound leaves at least fraction of the population below it if and only if , equivalent to
The left side is by definition a noncentral with degrees of freedom and noncentrality parameter (the sign of is irrelevant because ). Requiring this with probability gives , the quantile of that noncentral divided by . For the two-sided interval there is no elementary exact closed form; Howe’s highly accurate approximation is
with the probability- chi-square quantile. The cell below checks it by simulation.
Tolerance without distributional assumptions
Without assuming normality, interval formed by sample minimum and maximum is a tolerance interval with confidence that does not depend on .
Proof
By the probability integral transform, , and since is increasing, , the range of uniforms. The joint density of minimum and maximum is on (choose the minimum and maximum, with the remaining falling between them). With , the minimum can occupy any position in , so range density is
and integrating gives distribution function . Confidence is .
∎This is the distribution. Read it carefully: with and confidence is only , meaning the range of observations does not contain of the population more than half the time. To have confidence of covering requires observations, and to cover with the same confidence, . For one-sided bounds, the maximum suffices with , that is, : for and for percentile at confidence . The cell below calculates and simulates this.
import numpy as np
from scipy import stats
def k_howe(n, beta, gamma):
"""Factor bilateral de tolerancia normal (aproximación de Howe)."""
return stats.norm.ppf((1 + beta) / 2) * np.sqrt((n - 1) * (1 + 1 / n) / stats.chi2.ppf(1 - gamma, n - 1))
def k_unilateral(n, beta, gamma):
"""Factor exacto de la cota unilateral: cuantil gamma de la t no central con delta = z_beta sqrt(n), dividido por sqrt(n)."""
return stats.nct.ppf(gamma, n - 1, stats.norm.ppf(beta) * np.sqrt(n)) / np.sqrt(n)
def conf_np(n, beta):
return 1 - n * beta ** (n - 1) + (n - 1) * beta ** n
rng = np.random.default_rng(3)
beta = gamma = 0.95
print(f"{'n':>4s} {'IC':>6s} {'IP':>6s} {'IT Howe':>8s} {'IT unilateral':>14s} (semianchuras en unidades de s)")
for n in (5, 10, 30, 100):
t = stats.t.ppf(0.975, n - 1)
print(f"{n:4d} {t / np.sqrt(n):6.3f} {t * np.sqrt(1 + 1 / n):6.3f} {k_howe(n, beta, gamma):8.3f} {k_unilateral(n, beta, gamma):14.3f}")
# Cobertura por simulación sobre 100 000 muestras normales
print("\nfracción de muestras cuyo IT bilateral contiene al menos el 95 % de la población:")
for n in (5, 10, 30):
x = rng.standard_normal((100_000, n))
m, s = x.mean(1), x.std(1, ddof=1)
k = k_howe(n, beta, gamma)
contenido = stats.norm.cdf(m + k * s) - stats.norm.cdf(m - k * s)
print(f" n = {n:3d}: {np.mean(contenido >= beta):.3f}")
# [mín, máx] sin supuestos
print("\nconfianza de [mín, máx] para beta = 0.95:", {n: round(conf_np(n, 0.95), 3) for n in (10, 30, 59, 93)})
n_min = lambda b, g: next(n for n in range(2, 5000) if conf_np(n, b) >= g)
print("n mínimo bilateral:", {(b, g): n_min(b, g) for b, g in ((0.90, 0.90), (0.95, 0.95), (0.99, 0.95))})
print("n mínimo unilateral (solo el máximo):", {(b, g): int(np.ceil(np.log(1 - g) / np.log(b))) for b, g in ((0.95, 0.95), (0.99, 0.95))})
u = rng.random((100_000, 93))
print("simulación n = 93, contenido >= 0.95:", np.mean(u.max(1) - u.min(1) >= 0.95).round(3))The first table’s numbers tell the figure’s story: with the confidence interval has half-width , prediction , and two-sided tolerance (exact one-sided bound ). As grows, the first shrinks to , and the other two converge to the same limit, when , but tolerance approaches from above: at it still measures , the price of not knowing .
Combining evidence: inverse-variance weighting
The same effect is measured repeatedly in different studies, evaluation sets or facilities, and each measurement comes with standard error . How should they be combined? A simple average treats precise and noisy measurements equally. The module’s criterion (minimum variance among unbiased linear estimators) gives the answer.
Proof
By the Cauchy–Schwarz inequality,
so . Equality holds exactly when vectors and are proportional, that is, , and constraint fixes the constant.
∎This is the Gauss–Markov theorem for observations with common mean and diagonal covariance; if estimates were correlated with covariance , the optimum would be with variance . The result depends on a strong assumption: all estimate the same . If each study estimates its own effect, the variance of is minimal for the wrong target, and the interval from is too narrow.
Heterogeneity: when studies estimate different things
The first question is whether data are compatible with one . Once is calculated, Cochran’s statistic measures weighted discrepancy,
which under homogeneity and normality follows (one degree of freedom is lost estimating ). To measure how much heterogeneity there is, use
the fraction of variation in exceeding what chance predicts ( without heterogeneity). It is a ratio, not a size: describes not how far apart studies are but what fraction of observed variation is not sampling noise.
Proof
Expand . With and , the first term has expectation . For the second, and the squared mean is , so its expectation divided by is . Subtracting cancels and gives the result. Equating to its expectation and solving for (truncating at ) gives .
∎See what does to the weights: . If is large relative to , all weights become equal, because between-study uncertainty is common to all and individual precision no longer discriminates. A single enormous study no longer dominates. Try it.
With initial values, with degrees of freedom (), and . Fixed and random effects give nearly the same central value ( and ), but random-effects standard error is versus : its interval is wider, reflecting that the six estimates differ more than their noise explains. Adding the large study (effect , standard error ) sends the fixed effect to with interval only , pulled by a study carrying of weight, while random effects remain at with (the new study falls to of weight): this honestly reflects uncertainty about which of the seven is “true”. The initial six studies’ prediction interval, , already warned us: mean effect is clearly positive (interval ), but a seventh evaluation set could yield zero or negative improvement. In practice, when studies disagree, fixed effect gives a narrow, falsely confident interval.
Meta-analysis from scratch
The cell calculates all of the above for the six studies in the figure, draws the forest plot and repeats after adding the discrepant study.
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
def meta(y, se):
"""Efecto fijo y de efectos aleatorios (DerSimonian-Laird), Q, I², tau² e intervalo de predicción."""
y, v = np.asarray(y, float), np.asarray(se, float) ** 2
k = len(y)
w = 1 / v
fe = np.sum(w * y) / w.sum()
Q = np.sum(w * (y - fe) ** 2)
tau2 = max(0.0, (Q - (k - 1)) / (w.sum() - np.sum(w ** 2) / w.sum()))
ws = 1 / (v + tau2)
re = np.sum(ws * y) / ws.sum()
se_re = ws.sum() ** -0.5
pred = None
if k >= 3:
r = stats.t.ppf(0.975, k - 2) * np.sqrt(tau2 + se_re ** 2)
pred = (re - r, re + r)
return dict(fe=fe, se_fe=w.sum() ** -0.5, re=re, se_re=se_re, Q=Q, p_Q=stats.chi2.sf(Q, k - 1),
I2=max(0.0, (Q - (k - 1)) / Q), tau2=tau2, w_fe=w / w.sum(), w_re=ws / ws.sum(), pred=pred)
y = np.array([1.1, 0.3, 1.8, 0.7, 1.4, 0.0])
se = np.array([0.45, 0.40, 0.55, 0.30, 0.50, 0.60])
r = meta(y, se)
print(f"efecto fijo {r['fe']:.3f} ± {1.96 * r['se_fe']:.3f}")
print(f"efectos aleatorios {r['re']:.3f} ± {1.96 * r['se_re']:.3f}")
print(f"Q = {r['Q']:.2f} (p = {r['p_Q']:.3f}), I² = {100 * r['I2']:.0f} %, tau² = {r['tau2']:.3f}")
print(f"intervalo de predicción de un estudio nuevo: [{r['pred'][0]:.2f}, {r['pred'][1]:.2f}]")
r2 = meta(np.append(y, 2.6), np.append(se, 0.12))
print(f"\ncon el estudio grande y discrepante (2.6, 0.12):")
print(f"efecto fijo {r2['fe']:.3f} ± {1.96 * r2['se_fe']:.3f}")
print(f"efectos aleatorios {r2['re']:.3f} ± {1.96 * r2['se_re']:.3f} (peso relativo del nuevo estudio: {100 * r2['w_fe'][-1]:.0f} % en EF, {100 * r2['w_re'][-1]:.0f} % en EA)")
print(f"I² = {100 * r2['I2']:.0f} %, tau² = {r2['tau2']:.3f}")
fig, ax = plt.subplots(figsize=(7.2, 3.8))
n = len(y)
for i in range(n):
ax.plot([y[i] - 1.96 * se[i], y[i] + 1.96 * se[i]], [n - i] * 2, color="C0", lw=1.8)
ax.plot(y[i], n - i, "s", color="C0", ms=4 + 18 * r["w_fe"][i])
for yy, (m, s, col, nom) in zip((0, -1), ((r["fe"], r["se_fe"], "C1", "efecto fijo"), (r["re"], r["se_re"], "C4", "efectos aleatorios"))):
ax.fill([m - 1.96 * s, m, m + 1.96 * s, m], [yy, yy + 0.3, yy, yy - 0.3], color=col, label=nom)
ax.plot(r["pred"], [-1.8, -1.8], color="C4", ls="--", lw=2, label="predicción")
ax.axvline(0, color="gray", lw=1)
ax.set_yticks(list(range(n, 0, -1)) + [0, -1, -1.8], [f"estudio {i + 1}" for i in range(n)] + ["efecto fijo", "ef. aleatorios", "predicción"])
ax.set_xlabel("efecto (puntos)")
ax.legend(loc="lower right", fontsize=8)
plt.show()With the discrepant study, study carries of fixed-effect weight and only under random effects, while rises from to . Why does rise so much? Because the new study is very precise (), and with small measurement errors almost all observed variation is heterogeneity. Thus does not measure distance between effects, but how much observed variation is not noise; measures the former.
With few studies (small ), DerSimonian–Laird is downward biased and normal intervals are too short. Common alternatives are the Hartung–Knapp–Sidik–Jonkman correction, using and a standard error rescaled by observed heterogeneity, and estimators such as REML or Paule–Mandel. The statsmodels function in the libraries section offers Paule–Mandel (method_re="iterated") and Hartung–Knapp; REML requires fitting the random-effects model by restricted maximum likelihood using other tools. The test also has little power for small : large does not prove homogeneity.
Communicating uncertainty
Analysis ends when someone else reads the result and makes a decision with it. Much uncertainty is lost, or invented, at that final stage.
Three bars that mean different things
The same bar around a mean can represent three things, and the reader cannot guess which.
- Standard deviation : describes data spread. It does not shrink with .
- Standard error : precision of the mean. It is smaller by factor , so many figures prefer it, but coverage is low: is a confidence interval of level for large and only for .
- confidence interval: , with for large and for .
The most common reading is “if bars overlap, there is no difference”. This is false. For two independent groups with standard errors and , the difference test is significant when (with for and large ), whereas intervals stop overlapping when . Since , separation implies significance, but not conversely. With equal standard errors , the test requires and intervals separate only at : between and the difference is significant while intervals overlap, up to of each interval’s half-width. Standard-error bars behave oppositely: they stop overlapping at , before significance; a gap does not imply .
Simulation measures the cost of using overlap as a test: with no real difference, how often would each rule declare a “difference”?
import numpy as np
from scipy import stats
rng = np.random.default_rng(14)
R, n, s = 200_000, 15, 1.0
a = rng.normal(0, s, (R, n))
b = rng.normal(0, s, (R, n)) # misma población: toda «diferencia» es un falso positivo
ma, mb = a.mean(1), b.mean(1)
sa, sb = a.std(1, ddof=1), b.std(1, ddof=1)
ea, eb = sa / np.sqrt(n), sb / np.sqrt(n)
d = np.abs(ma - mb)
t = stats.t.ppf(0.975, n - 1)
welch = d / np.hypot(ea, eb)
df = np.hypot(ea, eb) ** 4 / (ea ** 4 / (n - 1) + eb ** 4 / (n - 1))
p = 2 * stats.t.sf(welch, df)
print(f"test de Welch con p < 0.05: {np.mean(p < 0.05):.4f}")
print(f"IC 95 % que NO se solapan (regla visual): {np.mean(d > t * (ea + eb)):.4f}")
print(f"barras de error estándar que NO se solapan: {np.mean(d > ea + eb):.4f}")
print(f"barras de desviación típica que NO se solapan: {np.mean(d > sa + sb):.4f}")The asymmetry is striking. Checking whether intervals overlap almost never declares differences ( false positives): it protects against type-I error so strongly that it loses power and misses real differences. Checking whether standard-error bars separate instead has false positives. Standard-deviation bars never separate by chance, because they describe data rather than precision. The practical rule from Cumming and Krzywinski and Altman: with intervals from two independent groups of similar size, overlap of up to half a half-width remains compatible with ; use the test (or better, the difference interval), not the eye, for comparison.
Significant figures and notation
Giving more digits than uncertainty justifies communicates something false: suggests precision contradicted by its second term. GUM (§7.2.6) and Particle Data Group convention is to round uncertainty first, to one or two significant figures, then the estimate to the same decimal place. The PDG rule chooses one or two figures based on the first three digits of : through , two; through , one; through , round to and retain two. The cell implements edge cases and compact notation , with uncertainty in the last digits in parentheses.
import numpy as np
from decimal import Decimal, ROUND_HALF_EVEN
def redondea(x, u):
"""Devuelve (x, u) redondeados con la regla del PDG: u con 1 o 2 cifras significativas, x en el mismo lugar decimal."""
if u <= 0:
raise ValueError("la incertidumbre debe ser positiva")
e = int(np.floor(np.log10(u))) # u = m · 10^e con 1 <= m < 10
tres = int(round(u / 10 ** (e - 2))) # tres primeras cifras (100..999) o 1000 tras redondear
if tres >= 950: # 950..999 sube a 1.0 · 10^(e+1), con dos cifras
e += 1
cifras = 2
elif tres >= 355:
cifras = 1
else:
cifras = 2
lugar = e - (cifras - 1) # exponente del último decimal que se conserva
q = Decimal(1).scaleb(lugar)
ur = Decimal(repr(u)).quantize(q, rounding=ROUND_HALF_EVEN)
xr = Decimal(repr(x)).quantize(q, rounding=ROUND_HALF_EVEN)
return xr, ur, lugar
def formato(x, u):
xr, ur, lugar = redondea(x, u)
mant = int(ur.scaleb(-lugar)) # incertidumbre como entero en el último lugar
if lugar < 0:
return f"{xr:f}({mant})"
return f"{xr:f} ± {ur:f}"
casos = [(12.3456, 0.0678), (12.3456, 0.0123), (12.3456, 0.0996), (1234.5678, 56.78), (0.0012345, 0.0000456), (25.40, 0.2088)]
for x, u in casos:
xr, ur, _ = redondea(x, u)
print(f"{x!r:>10} ± {u!r:<10} -> {xr:f} ± {ur:f} compacto: {formato(x, u)}")Consider : its first three digits, , fall between and , uncertainty rounds up to and two digits are retained, so the result is , or . With one digit one would publish , and rounding the estimate to tenths could shift it by up to , half the uncertainty itself. Also compare , which takes one digit (), with , which takes two (): with only one, , almost of uncertainty would be lost. Two cautions: do not round intermediate results, only the published one; and give numbers used in later calculations one extra digit.
How to plot
- Show the data if few. With per group, individual points say more than any bar; a bar chart with error bars (“dynamite”) hides distribution, sample size and outliers.
- Label the bar in the figure. “Mean ± standard error, users per group”, or “ CI (percentile bootstrap, resamples)”. Without a label the figure cannot be interpreted.
- Show the difference with its interval, not two separate intervals. It is the reader’s question and the one the test answers.
- Interval plots. One row per estimate and interval, ordered with the reference (zero, a threshold) visible: the preceding forest plot is the model. Better than a table of values.
- Honest scale. An estimate-plot axis need not start at zero, but a bar-chart axis should; draw the same quantity on the same scale across compared panels.
Checklist for an honest statistical report
- Estimate and interval together. Every number includes uncertainty, with level () and type (confidence, prediction, tolerance, standard error).
- The question determines the interval. Is it about a parameter, the next observation or a compliance threshold? See the interval table.
- Analysis unit and independence. What is an observation? Are there repeated measures, seeds on the same test set, users with multiple sessions? If dependent, naive standard error is too small.
- Assumptions and checks. Distribution, linearization, homogeneity. If linearized, was it compared with Monte Carlo? If studies were combined, is there heterogeneity (, , ), and was the appropriate model used?
- Correlations. Are propagated inputs independent? If assumed, say so.
- Included and excluded sources. Explicitly list what the figure includes (sampling, instrument) and excludes (model, data drift, selection bias). Unquantified uncertainty does not disappear when omitted.
- Sensitivity. Does the conclusion change under less certain assumptions? A table of intervals under each alternative is more honest than one interval.
- Effect size, not only . A small value with trivial effect and a large with an interval including important effects are very different results (effect size).
- Multiplicity. If many comparisons were examined, was this corrected or disclosed (multiple comparisons)?
- Digits and reproducibility. Rounding consistent with uncertainty, seed, code version and data version.
With libraries: statsmodels, scipy and quasi-Monte Carlo
statsmodels.stats.meta_analysis.combine_effects performs meta-analysis with several estimators and Hartung–Knapp correction. scipy.stats.qmc provides Sobol sequences, covering input space more uniformly than pseudorandom numbers and reducing propagation’s numerical error for smooth models. The cell compares both with the implementations above.
import numpy as np
from scipy import stats
from scipy.stats import qmc
from statsmodels.stats.meta_analysis import combine_effects
y = np.array([1.1, 0.3, 1.8, 0.7, 1.4, 0.0])
se = np.array([0.45, 0.40, 0.55, 0.30, 0.50, 0.60])
res = combine_effects(y, se ** 2, method_re="chi2") # "chi2" es el estimador de DerSimonian-Laird
tabla = res.summary_frame()
print(tabla.loc[["fixed effect", "random effect", "random effect wls"], ["eff", "sd_eff", "ci_low", "ci_upp"]].round(3))
print(f"tau² = {res.tau2:.3f}, Q = {res.q:.2f}, I² = {100 * res.i2:.0f} %")
print("la fila «wls» es la corrección de Hartung-Knapp: error estándar", round(float(tabla.loc["random effect wls", "sd_eff"]), 3), "frente a", round(float(tabla.loc["random effect", "sd_eff"]), 3))
# Propagación del coste esperado con M = 2^13 sorteos: Monte Carlo ordinario frente a Sobol aleatorizado
marg = [stats.gamma(6, scale=1 / 3),
stats.lognorm(s=np.sqrt(np.log(1 + (18 / 85) ** 2)), scale=85 / np.sqrt(1 + (18 / 85) ** 2)),
stats.beta(9.2, 13.8)]
def coste(u):
return np.prod([m.ppf(np.clip(u[:, i], 1e-12, 1 - 1e-12)) for i, m in enumerate(marg)], axis=0)
rng = np.random.default_rng(8)
ests_mc, ests_qmc = [], []
for rep in range(25):
ests_mc.append(coste(rng.random((2 ** 13, 3))).mean())
ests_qmc.append(coste(qmc.Sobol(3, scramble=True, seed=rep).random(2 ** 13)).mean())
print(f"\nmedia del coste con 8192 sorteos, 25 repeticiones (valor exacto 68.0):")
print(f" Monte Carlo ordinario: desviación típica entre repeticiones {np.std(ests_mc, ddof=1):.3f}")
print(f" Sobol aleatorizado: desviación típica entre repeticiones {np.std(ests_qmc, ddof=1):.3f}")The statsmodels table reproduces the homemade implementation’s numbers (, , ) and adds the Hartung–Knapp row, with slightly greater standard error. Quasi-Monte Carlo reduces numerical error of the mean from to with the same number of evaluations, because the integrand is a product of monotone functions of one input each (low effective dimension) and Sobol projections onto each coordinate are perfectly stratified. For discontinuous models, strong interactions among many inputs, or extreme percentiles, the advantage diminishes, so GUM relies on ordinary Monte Carlo and its error analysis.
Common mistakes
Exercises
Step 1 of 5. Which optimization problem must be solved?
confianza_np(n, beta), the confidence with which interval of a sample of size from a continuous distribution contains at least proportion of the population, and n_minimo(beta, gamma), the smallest for which that confidence is at least . Hint: content is .import numpy as np
def confianza_np(n, beta):
"""Confianza de que [min, max] contenga al menos una proporcion beta de la poblacion."""
# tu código
return None
def n_minimo(beta, gamma):
"""Menor n con confianza_np(n, beta) >= gamma."""
# tu código
return NoneSummary
Uncertainty is propagated (linear law , exact to first order and poor near singularities; Monte Carlo when linearization fails, with draws and percentiles as coverage interval), chosen to match the question (confidence for a parameter, prediction for an observation, tolerance for a guaranteed population proportion, for ), combined (inverse-variance weighting is the optimal unbiased linear estimator if all estimate the same thing; otherwise random effects with ), and communicated with label, analysis unit, data and unquantified sources. As a difference grows, standard-error bars stop overlapping before the test is significant, and intervals afterward.
Next in the module: post-selection inference and inference with ML predictions studies what happens to these intervals when data were previously used to choose what to analyze or some labels are model predictions.