Confidence intervals
Construct and interpret confidence and prediction intervals, compare proportion intervals and profile likelihood, and measure coverage and tail behavior under realistic sampling.
After this lesson you can
- Interpret confidence coverage and construct exact intervals using pivotal quantities.
- Compare Wald, Wilson, Agresti–Coull and Clopper–Pearson intervals for a proportion.
- Construct profile-likelihood intervals and understand reparameterization invariance.
- Distinguish confidence intervals, prediction intervals and joint regions.
- Assess coverage and tail errors by exact calculations and simulation.
Before you start
Motivation: a metric without an interval cannot decide
You evaluate two detectors on independent test sets of 200 labeled cases each. Detector A gets 168 right (84 %) and B gets 176 (88 %). Is B better? Point estimates alone cannot tell you, because you do not know how much each number would move if evaluation were repeated on another 200 cases. What is missing is a measure of that uncertainty, conventionally a confidence interval.
The next cell does two things. It calculates Wilson intervals (defined shortly) for A and B, and answers an uncomfortable question: if the two detectors were identical, with true accuracy 0.86, how often would a gap of at least 4 percentage points appear purely by chance between evaluations?
import numpy as np
from scipy import stats
n, z = 200, 1.959964
for nombre, aciertos in [("A", 168), ("B", 176)]:
p = aciertos / n
centro = (p + z**2 / (2 * n)) / (1 + z**2 / n)
mitad = z / (1 + z**2 / n) * np.sqrt(p * (1 - p) / n + z**2 / (4 * n**2))
print(f"detector {nombre}: exactitud {p:.3f}, intervalo de Wilson al 95 %: [{centro - mitad:.3f}, {centro + mitad:.3f}]")
# Si ambos detectores tuvieran exactitud 0.86, probabilidad exacta de ver una diferencia de >= 8 aciertos (4 puntos)
x = np.arange(n + 1)
pmf = stats.binom.pmf(x, n, 0.86)
dif = np.abs(x[:, None] - x[None, :])
print("P(|brecha| >= 4 puntos) con detectores idénticos:", round(float(np.sum(pmf[:, None] * pmf[None, :] * (dif >= 8))), 3))More than once in four you would see such a gap without any real difference, and the two 95 % intervals overlap substantially. This lesson constructs those intervals rigorously and measures, in a simulation study, whether they deliver what they promise. It answers five questions:
- What exactly does “95 %” mean? It is a property of the procedure, not the particular resulting interval.
- How is an exact interval built? With pivotal quantities: the and intervals of normal theory.
- What if there is no pivot? Wald intervals from the MLE, their failures, and the profile-likelihood alternative.
- Which interval for a proportion? Four candidates (Wald, Wilson, Agresti–Coull, Clopper–Pearson) with very different behavior.
- Interval for a parameter or the next observation? The distinction between confidence and prediction, which in machine learning separates model uncertainty from noise.
What “95 %” means: the frequentist definition
Work with a sample from a statistical model , seeking a set of reasonable values for parameter . Neyman’s (1937) idea is to avoid assigning probability to , an unknown constant, and instead require a guarantee about the procedure.
This is the confidence interval. Three details of the definition matter more than they seem.
- The interval is random. In probability is over samples the model could generate with fixed . Once data are observed, is a pair of numbers, and either lies in it or does not: nothing remains over which to assign probability.
- The guarantee is for every . A procedure covering 99 % at some parameter values and 80 % at others is not at the 95 % level. The infimum matters, and as we will see for binomial proportions it can be disastrous even if average coverage is good.
- Nominal is not actual. You choose level ; coverage is what the procedure actually does. Exact intervals satisfy (or ) at every finite sample size; approximate ones satisfy it only in the limit, and distance from that limit must be measured.
The first interactive makes the definition visible. Each row is a new sample, and its interval is plotted against the true mean.
Three lessons from the interactive. “95 %” is a long-run frequency: a batch of one hundred yields about five red intervals, not exactly five, and none “knows” it missed. The guarantee depends on assumptions: under normality the interval is exact for every (coverage is always 95 % within simulation error); with exponential data and it covers around 90 %, and with lognormal () and , around 84 %. Misses are not evenly distributed: with long right tails, the sample mean tends to fall below , and the estimated standard deviation is small just when is, so almost all misses are intervals entirely below .
Correct and incorrect interpretations
Suppose you obtained as a 95 % interval for a proportion. Common readings include:
| Statement | Correct? |
|---|---|
| “The procedure I used produces intervals containing in 95 % of repetitions of the experiment.” | Yes: that is the definition. |
| “There is a 95 % probability that is in .” | No, in the frequentist framework: is not random and the interval is fixed. (With a prior distribution for a statement like this exists, but it is a Bayesian credible interval, a different object: lesson 21.) |
| “95 % of observations fall in .” | No: that would be a tolerance or prediction interval, and much wider. |
| “If I repeat the study, the new estimate will fall in with probability 95 %.” | No. For a normal mean, the probability that a replicate mean falls in the first interval is %. |
The last figure follows because the difference of two independent means has twice the variance. This is a widespread error, corrected by remembering that the interval quantifies uncertainty about the parameter, not future estimates.
Pivotal quantities
How do we build an interval with exact coverage? The classical tool is a function of data and parameter whose distribution depends on nothing unknown.
A pivotal quantity differs from a statistic because it depends on the parameter, but differs from an arbitrary variable because its law is known. The recipe is mechanical. Choose with under (e.g. its and quantiles) and solve for . Since the inequality’s probability does not depend on , neither does that of the resulting interval: coverage is exactly for every .
Normal mean. With , by normal sampling theory , and . If is known, is a pivot. Otherwise, the ratio of a standard normal to the square root of an independent divided by its degrees of freedom is Student’s :
The unknown variance has been absorbed into the pivot’s distribution: that is what it does. The has heavier tails than the normal; with , versus , and the correction vanishes as grows.
Normal variance. The pivot gives
It is not symmetric around : the upper end is farther away because is skewed.
Exponential rate. With , , so is a pivot. The interval is with . We will use it as an exact reference. In general, for any continuous family, by the probability integral transform: a pivot always exists, although solving for may not be possible in closed form.
Duality with tests
One idea underlies every interval in this lesson. An interval is the set of parameter values that would not be rejected as the null hypothesis. Tests are studied in lesson 10; here only the notion of an acceptance region is needed.
Proof
For every , by definition of , so . The converse is the same equivalence read backward.
∎This duality turns any test whose level is known into an interval. Wilson inverts the score test, Clopper–Pearson inverts exact binomial tests, and likelihood intervals invert likelihood-ratio tests. Interval quality inherits test quality: its coverage is test level at each point, width reflects power (a more powerful test rejects more false values and leaves a shorter interval), and shape follows the acceptance region.
The pivot is fragile
An interval exact under normality says nothing about what happens outside that assumption. The and pivots behave very differently.
The interval is asymptotically robust: by the central limit theorem and Slutsky’s lemma, for any population with finite variance. But convergence is slow under skewness. The Edgeworth expansion of the studentized statistic gives, for a population with skewness coefficient ,
and the opposite tail deviates in the opposite direction: first-order errors cancel in total coverage (error of order ), but not in each tail (error of order ). The interactive shows this.
The variance interval is much worse, for a transparent reason. With the kurtosis (3 for normal), , while the law assumes , equivalent to . By the CLT, in distribution, and the interval, which for large behaves like , has asymptotic coverage
With this is 95 %. With exponential data () it is %, and does not improve as grows (it is the limit): this is not a small-sample issue, but a pivot depending on an assumption (kurtosis) the data do not satisfy.
import numpy as np
from scipy import stats
rng = np.random.default_rng(1)
z = stats.norm.ppf(0.975)
def coberturas(muestreo, mu, var, n, R=20000):
x = muestreo((R, n))
m, s2 = x.mean(axis=1), x.var(axis=1, ddof=1)
mitad = stats.t.ppf(0.975, n - 1) * np.sqrt(s2 / n)
lo = (n - 1) * s2 / stats.chi2.ppf(0.975, n - 1)
hi = (n - 1) * s2 / stats.chi2.ppf(0.025, n - 1)
return (np.mean(np.abs(m - mu) <= mitad), # intervalo t
np.mean((lo <= var) & (var <= hi)), # intervalo chi2 para la varianza
np.mean(m + mitad < mu)) # t: intervalo entero por debajo de mu
print("población n cobertura t cobertura chi2 t falla por debajo")
for nombre, f, mu, var in [("normal", lambda s: rng.normal(size=s), 0.0, 1.0),
("exponencial", lambda s: rng.exponential(size=s), 1.0, 1.0)]:
for n in [20, 100, 400]:
ct, cv, abajo = coberturas(f, mu, var, n)
print(f"{nombre:12s} {n:4d} {ct:.3f} {cv:.3f} {abajo:.3f}")
# primer orden de Edgeworth para la cola inferior del estadístico t (exponencial: asimetría 2)
for n in [20, 100, 400]:
ed = 0.025 + 2 / (6 * np.sqrt(n)) * (2 * z**2 + 1) * stats.norm.pdf(z)
print(f"n = {n}: cola inferior según Edgeworth {ed:.3f}")
print("cobertura asintótica del intervalo chi2 con curtosis 9:", round(2 * stats.norm.cdf(z * np.sqrt(2 / 8)) - 1, 3))For exponential data, coverage rises toward 0.95 as increases with misses concentrated in one tail, and the Edgeworth prediction gets the order of magnitude right; coverage falls toward 0.67 and does not improve. Practical lesson: normality-based intervals for variances are not used with real data; for variances and standard deviations prefer intervals not depending on kurtosis, such as bootstrap intervals in lessons 16 and 17.
Wald intervals
There is almost never an exact pivot. But asymptotic normality of the MLE provides an approximate pivot: , where is an estimated standard error, e.g. or , with the observed information.
Proof
converges in distribution by Slutsky to . The interval covers if and only if the ratio is in , and since the limiting law is continuous, probability converges to .
∎This defines the Wald interval: estimator plus or minus standard errors. For a function use the delta method: . It is convenient (one fit and a subtraction), and what almost all software prints. But the theorem hides three traps:
- “For each fixed ” is not “uniformly”. Sample size needed to approach 95 % can grow without bound as approaches the boundary. For a proportion, the infimum over of Wald coverage is near 0 for any .
- It depends on parameterization. A Wald interval for and one for transformed back with are different intervals for the same parameter, both asymptotically correct but very different at finite . If the MLE distribution is highly skewed on one scale, the normal approximation is bad on that scale and good on another.
- It uses at , not at the value being tested. When variance depends on the parameter, random can systematically fail: with estimated standard error is 0 and the interval is a point.
The last point motivates inverting a test instead of solving with estimated standard error: evaluate variance at hypothetical , not at . This is what Wilson (score) and likelihood do.
A proportion: four intervals
The most frequent model-evaluation case is with the number correct, and . It is also instructive because it has exact solutions for comparison and an anomaly affecting all approximate intervals: is discrete, causing coverage to oscillate.
These are binomial proportion intervals. Each has a distinct interpretation worth understanding.
Wald is the naive interval: standardize with estimated standard error. Wilson inverts the score test (lesson 11): in testing , variance is evaluated at , not , so the interval always lies in and never degenerates: with it is . Its center, , is a weighted average of (weight ) and (weight ): shrinkage toward that grows as shrinks. Agresti–Coull uses the same center with Wald’s formula and is therefore always slightly wider than Wilson. You will derive Wilson in the first proof exercise.
Clopper–Pearson inverts two exact binomial tail tests. To understand it, use the binomial–beta relationship: , the distribution function in of a . Since increases, the lower endpoint is the where , and the upper where .
Proof
Let , nonincreasing in and increasing in . By construction, is the unique with , so is equivalent to . Since is nonincreasing in , the set has form , with its least element, and probability . Thus . The same argument with gives , and the union bound gives .
∎The exact guarantee has a cost: the inequality is almost always strict (because is discrete, exact cannot be attained), so the interval is conservative: it covers more than its promised 95 %.
Sawtooth coverage
How much do they really cover? For each method gives an interval , and coverage at is exactly
without simulation: a finite sum. Plotted as a function of it is not smooth. When crosses an endpoint or , enters or leaves the set of covering outcomes, and jumps by the binomial mass of , of order . This produces sawtooth oscillations of amplitude that do not disappear quickly. Brown, Cai and DasGupta (2001) study them in depth.
Four observations, all checkable by moving the interactive.
Wald fails where it matters. With average coverage is 90 %, below 93 % for four in ten values of in . Near 0 it is worse: for with small , is nearly Poisson, , and with the interval is point , which does not contain . Thus coverage is bounded by , tending to and barely changing with : the ceiling is the same for any large . For and it is at most 40 %. Increasing only moves the collapse toward smaller .
Wilson oscillates around 95 % (average 95 %, with occasional dips below 90 % at very small ). Agresti–Coull is slightly more conservative than Wilson and rarely drops below 93 %. Clopper–Pearson guarantees 95 % in the worst case, but averages 97 % coverage at : the excess is wasted information, unnecessarily wide intervals.
Brown, Cai and DasGupta recommend Wilson (or Jeffreys’ interval, the Bayesian interval from lesson 21 with prior ) for small and Agresti–Coull for larger , and advise against Wald even at large . Clopper–Pearson is the option when minimum coverage is required (e.g. a validation report), knowing it overcovers.
Lab: coverage from scratch
We implement five procedures (the four plus likelihood ratio, covered shortly), measure exact coverage, and reproduce the Brown–Cai–DasGupta figure. Everything is vectorized: coverage at is a weighted sum of masks.
import numpy as np
from scipy import stats, optimize, special
import matplotlib.pyplot as plt
Z = stats.norm.ppf(0.975)
def ic_wald(x, n, z=Z):
p = x / n
h = z * np.sqrt(p * (1 - p) / n)
return np.clip(p - h, 0, 1), np.clip(p + h, 0, 1)
def ic_wilson(x, n, z=Z):
p = x / n
centro = (p + z**2 / (2 * n)) / (1 + z**2 / n)
h = z / (1 + z**2 / n) * np.sqrt(p * (1 - p) / n + z**2 / (4 * n**2))
return np.clip(centro - h, 0, 1), np.clip(centro + h, 0, 1)
def ic_agresti_coull(x, n, z=Z):
nt = n + z**2
pt = (x + z**2 / 2) / nt
h = z * np.sqrt(pt * (1 - pt) / nt)
return np.clip(pt - h, 0, 1), np.clip(pt + h, 0, 1)
def ic_clopper_pearson(x, n, alfa=0.05):
lo = np.where(x == 0, 0.0, stats.beta.ppf(alfa / 2, np.maximum(x, 1), n - x + 1))
hi = np.where(x == n, 1.0, stats.beta.ppf(1 - alfa / 2, x + 1, np.maximum(n - x, 1)))
return lo, hi
def ic_verosimilitud(x, n, nivel=0.95):
"""Razón de verosimilitudes: {p : 2[l(p_hat) - l(p)] <= chi2_1(nivel)}, con raíces por brentq."""
corte = stats.chi2.ppf(nivel, 1) / 2
lo, hi = np.zeros(len(x)), np.ones(len(x))
for i, xi in enumerate(x):
ll = lambda p: special.xlogy(xi, p) + special.xlog1py(n - xi, -p) # 0 log 0 = 0
ph = xi / n
f = lambda p: ll(p) - ll(ph) + corte
if xi > 0:
lo[i] = optimize.brentq(f, 1e-12, ph)
if xi < n:
hi[i] = optimize.brentq(f, ph, 1 - 1e-12)
return lo, hi
def cobertura(metodo, n, ps):
"""C(p) = sum_x Bin(x; n, p) * 1[p en IC(x)], exacta."""
x = np.arange(n + 1)
lo, hi = metodo(x, n)
pmf = stats.binom.pmf(x[None, :], n, ps[:, None])
cubre = (lo[None, :] <= ps[:, None]) & (ps[:, None] <= hi[None, :])
return np.sum(pmf * cubre, axis=1)
METODOS = {"Wald": ic_wald, "Wilson": ic_wilson, "Agresti-Coull": ic_agresti_coull,
"Clopper-Pearson": ic_clopper_pearson, "Verosimilitud": ic_verosimilitud}
n = 50
ps = np.linspace(0.001, 0.5, 2000)
curvas = {nombre: cobertura(f, n, ps) for nombre, f in METODOS.items()}
print(f"n = {n}, p en [0.001, 0.5]")
print("método mínima media p con cobertura < 93 %")
for nombre, c in curvas.items():
print(f"{nombre:16s} {c.min():.3f} {c.mean():.3f} {np.mean(c < 0.93):6.1%}")
fig, ax = plt.subplots(figsize=(8, 3.6))
for nombre in ["Wald", "Wilson", "Clopper-Pearson"]:
ax.plot(ps, curvas[nombre], lw=1.2, label=nombre)
ax.axhline(0.95, color="gray", ls="--")
ax.set_ylim(0.6, 1.0); ax.set_xlabel("p"); ax.set_ylabel("cobertura"); ax.legend(loc="lower right")
plt.show()The table is the figure in numbers. Wald has a minimum near 0.05 (at , where a success is rarely observed) and falls below 93 % over 40 % of the range; Wilson has a minimum near 0.84 and almost always covers well; Agresti–Coull does not fall below 0.93 and Clopper–Pearson not below 0.95, with average 97 %. The likelihood interval, built next, has minimum (0.84) and average (0.95) similar to Wilson, as expected from two approximations to the same test, although it falls below 93 % for more values (8 % versus 1.4 %).
Profile likelihood
Wald requires to be approximately normal on its parameterization scale. Log-likelihood gives an alternative without that requirement. Near the maximum a second-order Taylor expansion gives
a parabola, and the Wald interval is exactly where that parabola lies above . But the true log-likelihood is not a parabola. The idea is to cut the true curve at that height, not its approximation. With multiple parameters, decide what to do with those not of interest (nuisance parameters): maximize over them for each value of the parameter of interest, yielding a function of one parameter.
This is the profile likelihood interval. Its justification is Wilks’ theorem (lesson 11): under MLE conditions, in distribution. When the parabola is exact, this statistic is the squared Wald pivot and the two intervals coincide; otherwise the likelihood interval follows the curve’s real shape. For 95 % the line is at (because ).
It has a property Wald does not.
This follows because (likelihood at a point does not depend on its name) and the MLE is equivariant: . The last exercise gives the full proof. A Wald interval, by contrast, is not invariant: it depends on the scale used for the normal approximation.
The interactive shows this for exponential rate . With observations and , relative log-likelihood is , which does not depend on data except via . Its curve has a long right tail in (hence is skewed) and is much more symmetric in .
With and 95 %, as multiples of : the exact interval ( pivot) is ; likelihood ; Wald on ; and Wald on . Exact coverages are 95.0 %, 94.8 %, 95.5 %, and 94.1 %. Looking only at total coverage would make Wald on seem best, incorrectly: its lower endpoint is far too low and upper endpoint too short, so it misses 3.9 % on one side and 0.6 % on the other. Wald on misses in reverse (1.1 % and 4.8 %), the exact interval splits misses evenly (2.5 % and 2.5 %), and likelihood is close (2.0 % and 3.2 %). Differences are larger at . Total coverage is not enough: examine both tails.
The likelihood interval is not exact (94.8 % at ): its coverage error is of order , and Bartlett correction reduces it to . But it follows the true shape more closely and is invariant, making it reliable when the scale on which normality works well is unknown.
import numpy as np
from scipy import stats, optimize
n = 10
corte = stats.chi2.ppf(0.95, 1) / 2
# log-verosimilitud relativa de la tasa exponencial en la escala t = lambda / lambda_hat
rel_ll = lambda t: n * (np.log(t) - t + 1)
def extremos(f, centro, limites):
"""Raíces de f(u) = -corte a cada lado del máximo."""
g = lambda u: f(u) + corte
return optimize.brentq(g, limites[0], centro), optimize.brentq(g, centro, limites[1])
lo, hi = extremos(rel_ll, 1.0, (1e-6, 50.0)) # en la escala de lambda
lo2, hi2 = extremos(lambda u: rel_ll(np.exp(u)), 0.0, (-20.0, 20.0)) # en la escala de log lambda
print(f"verosimilitud en lambda: [{lo:.6f}, {hi:.6f}]")
print(f"verosimilitud en log lambda: [{np.exp(lo2):.6f}, {np.exp(hi2):.6f}] (tras exponenciar)")
z = stats.norm.ppf(0.975)
print(f"Wald en lambda: [{1 - z / np.sqrt(n):.3f}, {1 + z / np.sqrt(n):.3f}]")
print(f"Wald en log lambda: [{np.exp(-z / np.sqrt(n)):.3f}, {np.exp(z / np.sqrt(n)):.3f}]")
ex = stats.chi2.ppf([0.025, 0.975], 2 * n) / (2 * n)
print(f"exacto (chi2_2n): [{ex[0]:.3f}, {ex[1]:.3f}]")
# cobertura exacta: lambda / lambda_hat ~ Gamma(n, escala 1/n)
G = stats.gamma(n, scale=1 / n)
for nombre, (a, b) in {"verosimilitud": (lo, hi), "Wald en lambda": (1 - z / np.sqrt(n), 1 + z / np.sqrt(n)),
"Wald en log lambda": (np.exp(-z / np.sqrt(n)), np.exp(z / np.sqrt(n)))}.items():
print(f"{nombre:19s} cobertura {G.cdf(b) - G.cdf(a):.3f} fallos: por encima {1 - G.cdf(b):.3f}, por debajo {G.cdf(a):.3f}")The first two lines agree to the sixth digit: this is the theorem, not numerical coincidence. The others show what the interactive predicts.
Prediction intervals
Until now the target was a parameter. In machine learning another question often matters: where will the next observation fall? This is a different question with a different interval.
This is the prediction interval. There are two sources of uncertainty and a confidence interval captures only one: is unknown (uncertainty shrinks with ), and has its own noise, , which no sample size reduces.
Normal case. is normal with mean 0 and variance , independent of ; the pivot gives
Compared with confidence interval , the difference is “1 +” under the root. As the confidence interval shrinks like and the prediction interval tends to , with fixed width .
Without assuming a distribution. One construction uses only exchangeability.
Proof
Let be the rank of among the observations. Since they are iid with a continuous distribution (no ties with probability 1), all orderings are equally likely and is uniform on . Thus is equivalent to , and to . The event is , with values, probability .
∎Coverage is distribution-free (continuity suffices). The interval covers exactly . For 95 % take (the largest not exceeding the target), requiring : with , is equivalent to . With less data even cannot reach 95 %. With , for example, the sample range covers only %.
This is the germ of conformal prediction in m30: replace “rank of the new observation among the ” with “rank of an error score” to obtain the same distribution-free guarantee for any model.
Three readings. Uncertainty that does not shrink. At , the confidence interval is wide and prediction intervals (for normal), about 45 times wider. Confidence intervals say how much you know about the model; prediction intervals, how much about data. In machine learning this is the distinction between epistemic uncertainty (reducible with data) and aleatoric uncertainty (intrinsic noise). Total coverage hides the split. For exponential data with , normal prediction covers 94.7 %, seemingly reasonable, but its lower endpoint is negative (for a positive quantity) and almost all misses are above. The order interval assumes no distribution: exact 96.0 % at () under any continuous law. This is coverage averaged over samples; conditional on a particular sample, coverage of is random with law and mean .
import numpy as np
from scipy import stats
rng = np.random.default_rng(5)
n, R = 100, 40000
j = int(np.floor((n + 1) * 0.05 / 2))
print(f"n = {n}: j = {j}, cobertura teórica del intervalo de orden (n+1-2j)/(n+1) = {(n + 1 - 2 * j) / (n + 1):.4f}\n")
for nombre, f in [("normal", lambda s: rng.normal(size=s)),
("exponencial", lambda s: rng.exponential(size=s)),
("lognormal", lambda s: np.exp(rng.normal(size=s)))]:
x, nuevo = f((R, n)), f(R)
xs = np.sort(x, axis=1)
orden_lo, orden_hi = xs[:, j - 1], xs[:, n - j]
m, s = x.mean(axis=1), x.std(axis=1, ddof=1)
h = stats.t.ppf(0.975, n - 1) * s * np.sqrt(1 + 1 / n)
print(f"{nombre:12s} orden: cubre {np.mean((orden_lo <= nuevo) & (nuevo <= orden_hi)):.3f} "
f"(por debajo {np.mean(nuevo < orden_lo):.3f}, por encima {np.mean(nuevo > orden_hi):.3f}) "
f"normal: cubre {np.mean(np.abs(nuevo - m) <= h):.3f} "
f"(por debajo {np.mean(nuevo < m - h):.3f}, por encima {np.mean(nuevo > m + h):.3f})")
# la anchura: intervalo de confianza para la media frente a predicción (normal, sigma = 1)
for n2 in [10, 100, 1000, 10000]:
t = stats.t.ppf(0.975, n2 - 1)
print(f"n = {n2:5d}: anchura del IC {2 * t / np.sqrt(n2):.3f}, de la predicción {2 * t * np.sqrt(1 + 1 / n2):.3f}")One-sided intervals, joint regions and overlap
One-sided intervals. Sometimes only one bound matters: a maximum failure rate, a minimum accuracy. An upper bound of level is a statistic with ; the equal-tailed two-sided interval is the intersection of two one-sided level- intervals, so it uses , not . Using a two-sided 95 % interval and looking only at one endpoint wastes precision: that endpoint is a 97.5 % bound, farther away than necessary if a 95 % bound was wanted. The rule of three is one-sided for the same reason.
Joint regions. Two marginal 95 % intervals do not form a joint 95 % region. If the two coverage events are independent, the rectangle covers %. Beware: independent estimators alone are not enough. For a normal sample, and are independent, but the interval for also uses , so its coverage event depends on that of the interval for . Conditioning on , exact rectangular coverage is
which at is 90.6 % and tends to 90.25 % only as . For independent coverage events, : with 10 parameters, 60 %. Under dependence there is no formula, only Bonferroni’s bound: using level for each interval guarantees at least joint (union bound), with the usual conservatism. The dimension-aware solution is an ellipsoidal region (or profile likelihood with cutoff ): , with correct asymptotic coverage that respects parameter correlation.
import numpy as np
from scipy import stats, integrate
rng = np.random.default_rng(7)
n, R = 15, 100000
x = rng.normal(size=(R, n)) # mu = 0, sigma^2 = 1
m, s2 = x.mean(axis=1), x.var(axis=1, ddof=1)
def cubre(nivel):
a = (1 - nivel) / 2
cm = np.abs(m) <= stats.t.ppf(1 - a, n - 1) * np.sqrt(s2 / n)
cv = ((n - 1) * s2 / stats.chi2.ppf(1 - a, n - 1) <= 1) & (1 <= (n - 1) * s2 / stats.chi2.ppf(a, n - 1))
return cm.mean(), cv.mean(), (cm & cv).mean()
for etiqueta, nivel in [("cada uno al 95 %", 0.95), ("Bonferroni: cada uno al 97.5 %", 0.975)]:
cm, cv, cj = cubre(nivel)
print(f"{etiqueta:30s} media {cm:.3f} varianza {cv:.3f} conjunto {cj:.3f}")
# cobertura conjunta exacta: se condiciona en V = (n-1) S^2 / sigma^2 ~ chi2_{n-1}
def conjunta_exacta(nivel):
a, k = (1 - nivel) / 2, n - 1
tq = stats.t.ppf(1 - a, k)
f = lambda v: (2 * stats.norm.cdf(tq * np.sqrt(v / k)) - 1) * stats.chi2.pdf(v, k)
return integrate.quad(f, stats.chi2.ppf(a, k), stats.chi2.ppf(1 - a, k))[0]
print(f"exacta: {conjunta_exacta(0.95):.4f} y {conjunta_exacta(0.975):.4f}; "
f"si los sucesos fueran independientes: {0.95**2:.4f} y {0.975**2:.4f}")Interval overlap. Overlapping 95 % intervals do not imply a nonsignificant difference. With two independent estimates of equal standard error , intervals overlap if , but the difference test rejects at 5 % when . For differences between and the intervals overlap and the difference is significant. The converse does not occur: non-overlap implies a significant difference. With equal standard errors, a simple rule that works is to use 83.4 % intervals (), whose non-overlap is equivalent to the 5 % test; with different standard errors it is no longer exact, and the correct approach is to construct the difference interval directly. An exercise checks this with concrete numbers.
Using libraries
statsmodels.stats.proportion.proportion_confint implements proportion intervals ("normal", "wilson", "agresti_coull", "beta" for Clopper–Pearson, "jeffreys" and others), and scipy.stats.t.interval the interval. First we check agreement with our implementation, then use them in a real application: scanner detection rate evaluated on a small set of labeled cases. The numbers are illustrative.
import numpy as np
from scipy import stats
from statsmodels.stats.proportion import proportion_confint
# nuestras implementaciones (recortadas a [0, 1]) frente a statsmodels, para varios (x, n)
Z = stats.norm.ppf(0.975)
def wilson(x, n):
p = x / n
c = (p + Z**2 / (2 * n)) / (1 + Z**2 / n)
h = Z / (1 + Z**2 / n) * np.sqrt(p * (1 - p) / n + Z**2 / (4 * n**2))
return c - h, c + h
def ac(x, n):
nt = n + Z**2
pt = (x + Z**2 / 2) / nt
h = Z * np.sqrt(pt * (1 - pt) / nt)
return max(pt - h, 0), min(pt + h, 1)
def cp(x, n):
return (0.0 if x == 0 else stats.beta.ppf(0.025, x, n - x + 1)), (1.0 if x == n else stats.beta.ppf(0.975, x + 1, n - x))
maxdif = {"wilson": 0.0, "agresti_coull": 0.0, "beta": 0.0}
for n in [10, 50, 200]:
for x in range(0, n + 1, max(1, n // 10)):
for met, f in [("wilson", wilson), ("agresti_coull", ac), ("beta", cp)]:
a = np.clip(f(x, n), 0, 1)
b = np.clip(proportion_confint(x, n, alpha=0.05, method=met), 0, 1)
maxdif[met] = max(maxdif[met], float(np.max(np.abs(np.array(a) - np.array(b)))))
print("máxima diferencia con statsmodels:", {k: f"{v:.1e}" for k, v in maxdif.items()})
# intervalo t frente a scipy
rng = np.random.default_rng(3)
y = rng.normal(5.0, 2.0, size=25)
m, se = y.mean(), y.std(ddof=1) / np.sqrt(len(y))
a = (m - stats.t.ppf(0.975, 24) * se, m + stats.t.ppf(0.975, 24) * se)
b = stats.t.interval(0.95, 24, loc=m, scale=se)
print("t a mano:", np.round(a, 4), " scipy.stats.t.interval:", np.round(b, 4))Now the application. A vulnerability scanner is evaluated on 120 labeled illustrative cases and detects 111. Which interval should be reported, and how many cases are needed to say something useful?
import numpy as np
from scipy import stats
from statsmodels.stats.proportion import proportion_confint
casos, detectados = 120, 111
print(f"tasa de detección observada: {detectados / casos:.3f}")
for met in ["normal", "wilson", "agresti_coull", "beta", "jeffreys"]:
lo, hi = proportion_confint(detectados, casos, alpha=0.05, method=met)
print(f" {met:14s} [{lo:.3f}, {hi:.3f}] anchura {hi - lo:.3f}")
# 1) ¿cuántos casos para un margen de ±2 puntos? n = z^2 p (1-p) / m^2 (peor caso p = 0.5, y con p = 0.9)
z = stats.norm.ppf(0.975)
for p in [0.5, 0.9]:
print(f"margen ±2 puntos con p = {p}: n = {int(np.ceil(z**2 * p * (1 - p) / 0.02**2))}")
# 2) cero fallos: ¿cuántas pruebas hacen falta para acotar la tasa de fallo en el 1 % con el 95 %?
n_unilateral = int(np.ceil(np.log(0.05) / np.log(0.99))) # (1 - 0.01)^n <= 0.05
n_bilateral = int(np.ceil(np.log(0.025) / np.log(0.99))) # extremo superior de Clopper-Pearson bilateral
print(f"cero fallos: cota unilateral del 1 % con n = {n_unilateral}; cota superior del intervalo bilateral con n = {n_bilateral}")
print(f"regla del tres con n = 300: 3/300 = {3 / 300:.4f}; exacta: {1 - 0.05 ** (1 / 300):.4f}")
lo, hi = proportion_confint(0, 300, alpha=0.05, method="beta")
print(f"Clopper-Pearson bilateral con 0 fallos en 300: [{lo:.4f}, {hi:.4f}]")Two conclusions. With 120 cases the Wilson interval is nearly 10 percentage points wide: not enough to distinguish 92 % from 88 %. For a margin of points, around 2400 cases are needed in the worst case (), and still around 865 if the rate is near 90 %. The rule of three has an uncomfortable corollary: “zero failures in 300 trials” does not prove a failure rate below 1 %; it bounds it below 1 % with 95 % confidence only if a one-sided bound is accepted (299 trials suffice). To get the upper endpoint of the two-sided Clopper–Pearson interval below 1 %, 368 are needed.
Common mistakes
Exercises
Step 1 of 4. What is the score test's acceptance region?
clopper_pearson(x, n, alpha=0.05) to return (lo, hi), the exact level-1 - alpha interval, using scipy.stats.beta quantiles. It must accept scalar x or an array of successes, returning 0 as the lower endpoint if x == 0 and 1 as the upper endpoint if x == n. Tests check known values, endpoints and, above all, that exact coverage never falls below `1 - alpha` over a grid of values.import numpy as np
from scipy import stats
def clopper_pearson(x, n, alpha=0.05):
"""Devuelve (lo, hi) para x éxitos en n pruebas (x escalar o array)."""
x = np.asarray(x, dtype=float)
# tu código: cuantiles alpha/2 y 1 - alpha/2 de beta(x, n - x + 1) y beta(x + 1, n - x)
# (cuidado con x = 0 y con x = n, donde un parámetro de la beta sería 0)
return x / n, x / nStep 1 of 3. How are and related?
Summary
- Definition. for every . The interval is random; the parameter is fixed. Nominal is not actual: procedure coverage must be measured, in each tail.
- Pivots. A data-and-parameter function with known distribution gives exact intervals: for the mean, for variance. The pivot withstands non-normality at a rate depending on skewness; depends on kurtosis and its error does not disappear with .
- Wald. has correct but nonuniform asymptotic coverage and depends on parameterization. Inverting a test instead of solving with estimated standard error (Wilson, likelihood) almost always fixes this.
- Proportion. Wald collapses near 0 and 1 for all (with , coverage is bounded by ). Wilson and Agresti–Coull oscillate around the level. Clopper–Pearson never falls below level and overcovers. Zero failures in trials: 95 % bound .
- Profile likelihood. Cutting log-likelihood at yields an asymmetric interval invariant under monotone reparameterization, with better coverage than Wald when the normal approximation is poor.
- Prediction. Confidence intervals shrink like ; prediction intervals for the next observation tend to fixed width . Without assuming the law, covers exactly (requiring for 95 %): the seed of conformal prediction.
- Multiple parameters. Two marginal 95 % intervals do not form a 95 % region. Interval overlap does not decide significance: construct the difference interval.