Techniqueresearch
Empirical likelihood
Also called Owen's empirical likelihood.
Owen's nonparametric likelihood that puts weights on the data points subject to moment constraints. Its ratio has a chi-squared limit, so it gives tests and intervals without a model.
Empirical likelihood builds a likelihood ratio without a parametric model. It gives each observation a weight , with the weights on the data points only, and asks how far the weights must move from for a hypothesis to hold exactly. The profile ratio
behaves like a parametric likelihood ratio: if has components and finite, nonsingular covariance at the true , then in distribution (Owen 1988, 1990), the same limit as Wilks' theorem. So it gives tests and confidence regions whose shape the data choose, with no variance estimate and no model for the law of .
In plain words
Think of the data as the only values the random quantity can take, each with its own probability. With no constraint, the most likely choice is equal probabilities. Now ask a question such as "is the mean 5?". Find the probabilities closest to equal that make the mean of the data exactly 5. The more you must bend the probabilities, the less the data support the answer.
A known reference law tells you how much bending is too much. Collect all answers that need only a little bending, and you have a confidence interval. It needs no formula for the spread and no assumption about the shape of the data. The interval stays inside the range of the data and leans toward the side where the data are spread out more.
When it applies
- The data are iid from an unknown law , and the quantity of interest is defined by estimating equations with : a mean (), a quantile (), regression coefficients, the conditions of an M-estimator or of the generalized method of moments.
- For the chi-squared limit, is finite and nonsingular. For a quantile the indicator function satisfies this for any that is continuous at .
- The hypothesis value must be reachable: must lie inside the convex hull of . Otherwise .
- For dependent data the plain form fails; blocks of observations take the place of single observations.
The template
EL-TEST(x_1, ..., x_n, θ)- 1
choose ESTIMATING-FUNCTION m(x, θ) ∈ R^q ▷ hole: x - μ for a mean - 2
d_i ← m(x_i, θ) for i ← 1 to n - 3
if 0 is not inside the convex hull of d_1, ..., d_n then return ∞ - 4
λ ← root of Σ_i d_i / (1 + λ'd_i) = 0 with every 1 + λ'd_i > 0 ▷ hole: Newton on the dual - 5
w_i ← 1 / (n (1 + λ'd_i)) for i ← 1 to n - 6
r ← 2 Σ_i log(1 + λ'd_i) ▷ r = -2 log R(θ) - 7
return r, and reject when r > CRITICAL-VALUE ▷ hole: chi-squared q, Bartlett or bootstrap
The holes are the estimating function (line L1), the solver for (line L4) and the calibration (line L7). A confidence region is the set of with at most the critical value; for a scalar mean, is 0 at and increases on each side, so each end of the interval is found by bisection.
The weights (line L5). Maximize subject to and . The objective is strictly concave and the constraints are linear, so a point that satisfies the conditions of the Lagrange multiplier rule is the unique maximum. With multipliers and , the stationarity condition is . Multiplying by and summing gives , so , and the constraint becomes the equation of line L4. Then , which is line L6. This is proved.
Solving for (line L4). The function is convex on the set where every , and its gradient is minus the left side of line L4, so is the minimizer of . Owen's computation replaces for by the quadratic with the same value, slope and curvature at . The new function is convex and defined everywhere, so damped Newton steps can start at . A true solution has all , because each weight is below 1, so the change does not move it. When the solver ends with some , or with weights that do not sum to 1, the point is outside the hull and line L3 applies.
Why the limit is chi-squared (sketch, ). Let with variance . One shows that and , so uniformly. Expanding line L4 to first order gives , and expanding in line L6 gives
by the central limit theorem, the law of large numbers and Slutsky's theorem. The full proof, for vectors, is in Owen (1990). The leading term is the score statistic with the variance estimated under the hypothesis, which is why the method needs no separate variance estimate.
Classic examples
A mean. For the eight values , and (divisor ). At the multiplier is , , and the weights fall from on the smallest value to on the largest. At , , , and the largest value gets the weight . With the quantile , the 95% empirical likelihood interval is . The t interval is : symmetric about and reaching close to the smallest value. The empirical likelihood interval is shorter on the left, where the data are dense, and has the long side toward the long tail.
Quantiles. With , the constraint fixes the total weight on the points at most . The weights are then on those points and on the rest, so is the binomial likelihood ratio statistic for successes in trials. The interval for the median is close to the sign test interval, and it is valid whenever is continuous at the quantile.
Estimating equations. With conditions for parameters, maximize over (Qin and Lawless 1994). The maximum empirical likelihood estimate has the same first-order law as efficient GMM, , without a weight matrix. The ratio is and is , which tests the surplus conditions as the test does.
Side information. If the population mean of an auxiliary variable is known, as in a survey, adding it as a constraint changes the weights, and the weighted mean of the variable of interest gains precision. The weights then act like calibration weights.
Mean and variance together. With and , the test of a joint value of uses , and the region for both is not an ellipse but follows the data.
Variations
- Bartlett correction. For smooth functions of means, the mean of is , and dividing by lowers the coverage error from order to order (DiCiccio, Hall and Romano, 1991). The parametric likelihood ratio has the same property.
- Bootstrap calibration. Take the critical value from the bootstrap law of instead of the chi-squared table. In practice this corrects most of the undercoverage seen in small skewed samples.
- Adjusted empirical likelihood. Add one artificial point so that is always inside the hull, which removes the empty-set problem of line L3 with little change for large .
- Other divergences. Empirical likelihood minimizes , a Kullback-Leibler divergence from the uniform weights. Exponential tilting uses the reverse divergence and Euclidean likelihood a chi-squared distance, which allows negative weights and has a closed form. All of them form generalized empirical likelihood, with the same first-order limits.
- Profile and nuisance parameters. For a parameter of interest with nuisance parameters, maximize over the nuisance part. The limit keeps the chi-squared form with as many degrees of freedom as the parameter of interest.
- Blocks for time series. Replace single observations by averages over blocks of consecutive observations, with a scale factor, to keep the limit under dependence.
Pitfalls
- Undercoverage in small, skewed samples. The limit is proved; the accuracy at a given is only measured. For 95% intervals for the mean, from 4000 samples each, with the calibration:
| Law | ||||
|---|---|---|---|---|
| normal, EL | 0.900 | 0.932 | 0.943 | 0.945 |
| normal, t | 0.952 | 0.949 | 0.948 | 0.949 |
| exponential, EL | 0.862 | 0.906 | 0.928 | 0.936 |
| exponential, t | 0.889 | 0.913 | 0.924 | 0.933 |
| lognormal, EL | 0.812 | 0.869 | 0.900 | 0.919 |
| lognormal, t | 0.841 | 0.867 | 0.897 | 0.913 |
In these runs the plain empirical likelihood interval was no better than the t interval at , and only about equal at and 80. Its gain is the shape of the interval, not the coverage. Use a Bartlett or bootstrap calibration, or an F quantile in place of the chi-squared one, for small .
- The convex hull. Any for which is outside the hull of the gets . For the mean, the interval can never reach beyond , even when the true mean does, as with a heavy right tail and few data. With many constraints compared with , the hull can miss the true value with high probability.
- No moments, no limit. The chi-squared limit needs . For a mean of Cauchy data the method gives intervals, but their coverage has no guarantee.
- Numerical trouble near the hull. As nears the edge of the feasible set, grows without bound and a plain Newton step can leave the domain . Use the pseudo-logarithm or a bisection that keeps every weight positive.
- Profiling is a hard problem. need not be concave in when is nonlinear in , and the region can be non-convex or in parts.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/empirical-likelihood/. The authors are listed in prov/DSWA0W.jsonl.
import math
from collections.abc import Callable, Sequence
from typing import Any, NamedTuple
from stdist import chi2_ppf
def _solve(a: list, b: list) -> list:
"""Solve a x = b by Gaussian elimination with partial pivoting. Cost O(q^3)."""
k = len(a)
m = [list(row) + [b[i]] for i, row in enumerate(a)]
for c in range(k):
p = max(range(c, k), key=lambda r: abs(m[r][c]))
if m[p][c] == 0:
raise ZeroDivisionError("singular matrix")
m[c], m[p] = m[p], m[c]
for r in range(c + 1, k):
f = m[r][c] / m[c][c]
for j in range(c, k + 1):
m[r][j] -= f * m[c][j]
x = [0.0] * k
for r in range(k - 1, -1, -1):
x[r] = (m[r][k] - sum(m[r][j] * x[j] for j in range(r + 1, k))) / m[r][r]
return x
def _log_star(z: float, n: int) -> tuple[float, float, float]:
"""Owen's pseudo-logarithm and its first two derivatives.
Equal to log z for z >= 1/n, a quadratic below 1/n with matching value,
slope and curvature, so it is defined for every real z.
"""
if z >= 1.0 / n:
return math.log(z), 1.0 / z, -1.0 / (z * z)
t = n * z
return -math.log(n) - 1.5 + 2.0 * t - 0.5 * t * t, 2.0 * n - n * n * z, -float(n * n)
class ELResult(NamedTuple):
stat: float # -2 log R(theta); math.inf when 0 is outside the convex hull
lam: list # Lagrange multiplier
weights: list # w_i = 1 / (n (1 + lam' d_i)); empty when stat is inf
iterations: int
def el_ratio(d: Sequence[Sequence[float]], tol: float = 1e-24, max_iter: int = 100) -> ELResult:
"""Empirical likelihood ratio statistic for the hypothesis E[d] = 0.
d holds the n vectors d_i = m(x_i, theta) in R^q. The multiplier lam
minimizes the convex dual -sum log*(1 + lam' d_i), found by damped Newton
steps. If the solution puts some 1 + lam' d_i below 1/n, the point 0 is not
inside the convex hull of the d_i and the result is inf.
Cost per Newton step: O(n q^2 + q^3).
"""
n = len(d) # @line L2
q = len(d[0])
lam = [0.0] * q
def dual(lv: list) -> float:
return -sum(_log_star(1.0 + sum(a * b for a, b in zip(lv, di)), n)[0] for di in d)
f = dual(lam)
it = 0
for it in range(1, max_iter + 1): # @line L4
grad = [0.0] * q
hess = [[0.0] * q for _ in range(q)]
for di in d:
z = 1.0 + sum(a * b for a, b in zip(lam, di))
_, d1, d2 = _log_star(z, n)
for r in range(q):
grad[r] -= d1 * di[r]
for s in range(q):
hess[r][s] -= d2 * di[r] * di[s]
try:
step = _solve(hess, [-g for g in grad])
except ZeroDivisionError:
break
dec = -sum(g * s for g, s in zip(grad, step))
if dec <= tol:
break
s = 1.0
new = [a + s * b for a, b in zip(lam, step)]
fn = dual(new)
while fn > f and s > 1e-12:
s /= 2
new = [a + s * b for a, b in zip(lam, step)]
fn = dual(new)
if fn > f:
break
stalled = fn == f
lam, f = new, fn
if stalled:
break
zs = [1.0 + sum(a * b for a, b in zip(lam, di)) for di in d]
w = [1.0 / (n * z) if z > 0 else math.inf for z in zs] # @line L5
# A true solution has every z_i > 1/n and weights that sum to 1. If 0 is
# outside the hull, some z_i < 1/n, or the dual has no minimum and the
# iterates run off with every z_i large, so the weights sum far below 1.
if min(zs) < 1.0 / n * (1 - 1e-9) or abs(sum(w) - 1.0) > 1e-6: # @line L3
return ELResult(math.inf, lam, [], it)
stat = 2.0 * sum(math.log(z) for z in zs) # @line L6
return ELResult(stat, lam, w, it)
def el_test(
m: Callable[[Any, Sequence[float]], Sequence[float]],
data: Sequence,
theta: Sequence[float],
alpha: float = 0.05,
) -> tuple[float, float, bool]:
"""Test E[m(X, theta)] = 0 with the chi-squared(q) calibration.
Returns (-2 log R, critical value, reject). Cost: one call of el_ratio.
"""
d = [list(m(x, theta)) for x in data] # @line L1
res = el_ratio(d)
crit = chi2_ppf(1.0 - alpha, len(d[0]))
return res.stat, crit, res.stat > crit # @line L7
def el_mean_stat(x: Sequence[float], mu: float) -> float:
"""-2 log R(mu) for a scalar mean. inf when mu is not strictly inside (min x, max x)."""
lo, hi = min(x), max(x)
if lo == hi:
return 0.0 if mu == lo else math.inf
if not lo < mu < hi:
return math.inf
return el_ratio([[v - mu] for v in x]).stat
def el_mean_interval(x: Sequence[float], alpha: float = 0.05, iters: int = 80) -> tuple[float, float]:
"""Empirical likelihood interval {mu : -2 log R(mu) <= chi2_1(1 - alpha)} for a mean.
-2 log R is 0 at the sample mean and increases on each side, so each end
is found by bisection. Precondition: at least two distinct values.
Cost: O(iters) calls of el_ratio.
"""
c = chi2_ppf(1.0 - alpha, 1)
xbar = sum(x) / len(x)
ends = []
for edge in (min(x), max(x)):
inside, outside = xbar, edge
for _ in range(iters):
mid = 0.5 * (inside + outside)
if el_mean_stat(x, mid) <= c:
inside = mid
else:
outside = mid
ends.append(inside)
return ends[0], ends[1]
stdist.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.
The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""
import math
from statistics import NormalDist
_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000
def norm_cdf(x: float) -> float:
"""P(Z <= x) for a standard normal Z."""
return 0.5 * math.erfc(-x / math.sqrt(2.0))
def norm_sf(x: float) -> float:
"""P(Z > x), computed with erfc, so it is accurate for large x."""
return 0.5 * math.erfc(x / math.sqrt(2.0))
def norm_ppf(p: float) -> float:
"""The lower p-quantile z_p of the standard normal, 0 < p < 1."""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
return _STD.inv_cdf(p)
def _gamma_tails(a: float, x: float) -> tuple[float, float]:
"""(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
if a <= 0.0 or x < 0.0:
raise ValueError("need a > 0 and x >= 0")
if x == 0.0:
return 0.0, 1.0
if math.isinf(x):
return 1.0, 0.0
front = math.exp(-x + a * math.log(x) - math.lgamma(a))
if x < a + 1.0:
# Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
ap, term = a, 1.0 / a
total = term
for _ in range(_MAXIT):
ap += 1.0
term *= x / ap
total += term
if abs(term) < abs(total) * _EPS:
break
p = front * total
return p, 1.0 - p
# Continued fraction for Q, modified Lentz.
b = x + 1.0 - a
c = 1.0 / _TINY
d = 1.0 / b
h = d
for i in range(1, _MAXIT):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < _TINY:
d = _TINY
c = b + an / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
q = front * h
return 1.0 - q, q
def gamma_p(a: float, x: float) -> float:
"""Regularized lower incomplete gamma P(a, x)."""
return _gamma_tails(a, x)[0]
def gamma_q(a: float, x: float) -> float:
"""Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
return _gamma_tails(a, x)[1]
def _beta_cf(a: float, b: float, x: float) -> float:
"""The continued fraction of I_x(a, b), modified Lentz."""
qab, qap, qam = a + b, a + 1.0, a - 1.0
c = 1.0
d = 1.0 - qab * x / qap
if abs(d) < _TINY:
d = _TINY
d = 1.0 / d
h = d
for m in range(1, _MAXIT):
m2 = 2 * m
aa = m * (b - m) * x / ((qam + m2) * (a + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
h *= d * c
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
return h
def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
"""(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.
y is 1 - x; pass it when it is known more accurately than 1 - x.
"""
if a <= 0.0 or b <= 0.0:
raise ValueError("need a > 0 and b > 0")
if y is None:
y = 1.0 - x
if x <= 0.0:
return 0.0, 1.0
if y <= 0.0:
return 1.0, 0.0
front = math.exp(
math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
+ a * math.log(x) + b * math.log(y)
)
if x < (a + 1.0) / (a + b + 2.0):
low = front * _beta_cf(a, b, x) / a
return low, 1.0 - low
# Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
up = front * _beta_cf(b, a, y) / b
return 1.0 - up, up
def beta_inc(a: float, b: float, x: float) -> float:
"""Regularized incomplete beta function I_x(a, b)."""
return _beta_tails(a, b, x)[0]
def chi2_cdf(x: float, k: float) -> float:
"""P(X <= x) for X chi-square with k > 0 degrees of freedom."""
return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)
def chi2_sf(x: float, k: float) -> float:
"""P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)
def t_sf(x: float, k: float) -> float:
"""P(T > x) for T Student t with k > 0 degrees of freedom."""
if math.isfinite(x):
s = k + x * x
half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0] # P(|T| > |x|) / 2
else:
half = 0.0
return half if x >= 0.0 else 1.0 - half
def t_cdf(x: float, k: float) -> float:
"""P(T <= x) for T Student t with k degrees of freedom."""
return t_sf(-x, k)
def f_cdf(x: float, k1: float, k2: float) -> float:
"""P(F <= x) for F with (k1, k2) degrees of freedom."""
if x <= 0.0:
return 0.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]
def f_sf(x: float, k1: float, k2: float) -> float:
"""P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
if x <= 0.0:
return 1.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]
def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
"""The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).
lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
"""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
if p <= 0.5:
g = lambda x: cdf(x) - p # increasing in x
else:
q = 1.0 - p
g = lambda x: q - sf(x) # increasing in x, and no cancellation in sf
while g(hi) < 0.0:
lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
for _ in range(400):
mid = 0.5 * (lo + hi)
if mid <= lo or mid >= hi:
break
if g(mid) < 0.0:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def chi2_ppf(p: float, k: float) -> float:
"""The lower p-quantile chi^2_(k, p)."""
return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))
def t_ppf(p: float, k: float) -> float:
"""The lower p-quantile t_(k, p)."""
if p == 0.5:
return 0.0
if p < 0.5:
return -t_ppf(1.0 - p, k)
return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)
def f_ppf(p: float, k1: float, k2: float) -> float:
"""The lower p-quantile F_(k1, k2, p)."""
return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
test_empirical_likelihood.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/empirical-likelihood/. The authors are listed in prov/DSWA0W.jsonl.
import math
import random
from empirical_likelihood import _solve, el_mean_interval, el_mean_stat, el_ratio, el_test
from stdist import chi2_ppf
def scalar_reference(x, mu):
"""-2 log R(mu) by bisection on lambda in the interval where all weights are positive."""
d = [v - mu for v in x]
lo, hi = -1.0 / max(d), -1.0 / min(d)
for _ in range(200):
mid = 0.5 * (lo + hi)
f = sum(di / (1 + mid * di) for di in d) # decreasing in lambda
if f > 0:
lo = mid
else:
hi = mid
lam = 0.5 * (lo + hi)
return 2 * sum(math.log1p(lam * di) for di in d)
def test_zero_at_the_sample_mean():
x = [1.0, 4.0, 2.0, 8.0, 5.0]
res = el_ratio([[v - 4.0] for v in x])
assert abs(res.stat) < 1e-14
assert all(abs(w - 0.2) < 1e-14 for w in res.weights)
def test_scalar_matches_lambda_bisection():
rng = random.Random(1)
for _ in range(50):
n = rng.randint(3, 30)
x = [rng.expovariate(1.0) for _ in range(n)]
lo, hi = min(x), max(x)
mu = lo + (hi - lo) * rng.uniform(0.02, 0.98)
assert abs(el_mean_stat(x, mu) - scalar_reference(x, mu)) < 1e-8 * max(1.0, scalar_reference(x, mu))
def test_two_points_exact():
x1, x2 = 1.0, 5.0
for mu in (1.5, 2.0, 3.0, 4.9):
w1 = (x2 - mu) / (x2 - x1)
expect = -2 * (math.log(2 * w1) + math.log(2 * (1 - w1)))
assert abs(el_mean_stat([x1, x2], mu) - expect) < 1e-10
def test_three_points_against_simplex_search():
x = [0.0, 1.0, 5.0]
for mu in (0.5, 1.0, 2.0, 4.0):
d = [v - mu for v in x]
def value(t):
w2 = (-t * d[0] - (1 - t) * d[2]) / (d[1] - d[2])
w3 = 1 - t - w2
if t <= 0 or w2 <= 0 or w3 <= 0:
return -math.inf
return math.log(3 * t) + math.log(3 * w2) + math.log(3 * w3)
best = max((value(i / 20000), i / 20000) for i in range(1, 20000))
h = 1 / 20000
best = max((value(best[1] - h + 2 * h * i / 20000), 0) for i in range(20001))
assert abs(el_mean_stat(x, mu) - (-2 * best[0])) < 1e-8
def test_outside_hull_is_infinite():
x = [1.0, 2.0, 3.0]
assert el_mean_stat(x, 3.0) == math.inf and el_mean_stat(x, 0.5) == math.inf
d = [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [2.0, 0.5]] # 0 is not in the hull
assert el_ratio(d).stat == math.inf
d2 = [[1.0, 0.0], [0.0, 1.0], [-1.0, -1.0], [2.0, 0.5]]
assert el_ratio(d2).stat < math.inf
def test_affine_invariance():
rng = random.Random(2)
x = [rng.gauss(0, 1) for _ in range(25)]
a, b = 3.0, -2.5
y = [a + b * v for v in x]
for mu in (-0.3, 0.0, 0.2):
assert abs(el_mean_stat(x, mu) - el_mean_stat(y, a + b * mu)) < 1e-9
d = [[rng.gauss(0.1, 1), rng.gauss(-0.2, 2)] for _ in range(30)]
m = [[2.0, 1.0], [-1.0, 3.0]]
dm = [[m[0][0] * u + m[0][1] * v, m[1][0] * u + m[1][1] * v] for u, v in d]
assert abs(el_ratio(d).stat - el_ratio(dm).stat) < 1e-9
def test_vector_weights_are_optimal():
rng = random.Random(3)
n = 12
d = [[rng.gauss(0.2, 1), rng.gauss(0.1, 1)] for _ in range(n)]
res = el_ratio(d)
w = res.weights
assert abs(sum(w) - 1) < 1e-12
for j in range(2):
assert abs(sum(wi * di[j] for wi, di in zip(w, d))) < 1e-12
base = sum(math.log(n * wi) for wi in w)
assert abs(-2 * base - res.stat) < 1e-10
# random feasible directions: project onto {v : sum v = 0, sum v d = 0}
c = [[1.0] * n, [di[0] for di in d], [di[1] for di in d]]
cct = [[sum(a * b for a, b in zip(r, s)) for s in c] for r in c]
for _ in range(200):
v = [rng.gauss(0, 1) for _ in range(n)]
coef = _solve(cct, [sum(a * b for a, b in zip(r, v)) for r in c])
v = [v[i] - sum(coef[k] * c[k][i] for k in range(3)) for i in range(n)]
eps = 0.5 * min(wi / abs(vi) for wi, vi in zip(w, v) if vi != 0)
assert sum(math.log(n * (wi + eps * vi)) for wi, vi in zip(w, v)) <= base + 1e-12
def test_interval_ends_and_scan():
rng = random.Random(4)
x = [rng.expovariate(0.5) for _ in range(20)]
lo, hi = el_mean_interval(x)
c = chi2_ppf(0.95, 1)
assert abs(el_mean_stat(x, lo) - c) < 1e-6 and abs(el_mean_stat(x, hi) - c) < 1e-6
grid = [min(x) + (max(x) - min(x)) * i / 4000 for i in range(1, 4000)]
inside = [mu for mu in grid if el_mean_stat(x, mu) <= c]
step = (max(x) - min(x)) / 4000
assert abs(inside[0] - lo) <= step and abs(inside[-1] - hi) <= step
def test_coverage_measured():
# Measured, not proved: coverage at the true mean for Exp(1) data, n = 40.
rng = random.Random(5)
r, n = 1000, 40
c = chi2_ppf(0.95, 1)
hits = sum(el_mean_stat([rng.expovariate(1.0) for _ in range(n)], 1.0) <= c for _ in range(r))
assert 0.90 < hits / r < 0.97
# mean and variance together for normal data, q = 2
c2 = chi2_ppf(0.95, 2)
hits = 0
for _ in range(300):
x = [rng.gauss(0, 1) for _ in range(60)]
stat, crit, rej = el_test(lambda v, t: (v - t[0], (v - t[0]) ** 2 - t[1]), x, (0.0, 1.0))
assert crit == c2
hits += not rej
assert 0.88 < hits / 300 < 0.99
test_stdist.py 60 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
import math
from stdist import (
beta_inc, chi2_cdf, chi2_ppf, chi2_sf, f_cdf, f_ppf, f_sf, gamma_p, gamma_q,
norm_cdf, norm_ppf, norm_sf, t_cdf, t_ppf, t_sf,
)
XS = [0.001, 0.01, 0.1, 0.3, 0.5, 1.0, 1.7, 2.5, 4.0, 7.0, 12.0, 30.0, 80.0]
def test_chi2_two_degrees_of_freedom() -> None:
for x in XS:
assert abs(chi2_cdf(x, 2) - (1.0 - math.exp(-x / 2.0))) < 1e-13
assert abs(chi2_sf(x, 2) - math.exp(-x / 2.0)) <= 1e-12 * math.exp(-x / 2.0)
def test_t_one_and_two_degrees_of_freedom() -> None:
for x in XS + [-v for v in XS] + [0.0]:
assert abs(t_cdf(x, 1) - (0.5 + math.atan(x) / math.pi)) < 1e-13
assert abs(t_cdf(x, 2) - (0.5 + x / (2.0 * math.sqrt(2.0 + x * x)))) < 1e-13
assert abs(t_cdf(x, 3) + t_sf(x, 3) - 1.0) < 1e-14
def test_f_is_square_of_t() -> None:
for k in [1, 2, 3, 5, 10, 30]:
for x in XS:
two_sided = 2.0 * t_sf(math.sqrt(x), k)
assert abs(f_sf(x, 1, k) - two_sided) < 1e-13
assert abs(f_cdf(x, 1, k) + f_sf(x, 1, k) - 1.0) < 1e-14
def test_gamma_and_beta_identities() -> None:
for a in [0.5, 1.0, 2.5, 10.0, 50.0]:
for x in XS:
assert abs(gamma_p(a, x) + gamma_q(a, x) - 1.0) < 1e-14
# P(1, x) = 1 - e^(-x); I_x(a, 1) = x^a; I_x(1, b) = 1 - (1 - x)^b.
for x in [0.05, 0.3, 0.5, 0.8, 0.99]:
assert abs(gamma_p(1.0, x) - (1.0 - math.exp(-x))) < 1e-14
for a in [0.5, 2.0, 7.0]:
assert abs(beta_inc(a, 1.0, x) - x**a) < 1e-13
assert abs(beta_inc(1.0, a, x) - (1.0 - (1.0 - x) ** a)) < 1e-13
def test_upper_tails_do_not_cancel() -> None:
assert abs(norm_sf(10.0) / 7.619853024160527e-24 - 1.0) < 1e-12
assert abs(chi2_sf(200.0, 2) / math.exp(-100.0) - 1.0) < 1e-12
assert norm_cdf(-30.0) > 0.0
def test_quantiles() -> None:
assert abs(norm_ppf(0.975) - 1.959963985) < 1e-8
assert abs(chi2_ppf(0.95, 1) - 3.841458821) < 1e-8
assert abs(t_ppf(0.975, 10) - 2.228138852) < 1e-8
for p in [1e-6, 0.01, 0.2, 0.5, 0.8, 0.99, 1.0 - 1e-6]:
for k in [1, 4, 25]:
assert abs(chi2_cdf(chi2_ppf(p, k), k) - p) < 1e-12
assert abs(t_cdf(t_ppf(p, k), k) - p) < 1e-12
assert abs(f_cdf(f_ppf(p, k, 7), k, 7) - p) < 1e-12
Exercises
- For and , find for the mean, and its value at the midpoint. Answer. The two constraints fix and , so . At the midpoint and the value is 0.
- Show that exactly at , and is for when the are not all equal. Answer. At , the equal weights satisfy the constraint, so and . For all with some positive, so forces positive weight only on the points with , which leaves some and .
- Show that the empirical likelihood interval for a mean is equivariant under with . Answer. The constraint has the same feasible weights, so at for the new data equals at for the old data.
- For a quantile, show that , where is the number of , . Answer. The constraint fixes the total weight on the points at . Given that total, is largest with equal weights within each group, and . Then .
- Use the expansion in the template section to show that for the mean, and with differ by when is the true mean, and explain why the interval is not symmetric about . Answer. The leading term of the expansion is exactly that ratio. The cubic term of is of order and carries the third moment of the data, so for a finite the ends move toward the long tail.
References
- Art B. Owen, Empirical likelihood ratio confidence intervals for a single functional, Biometrika 75(2), 1988, pp. 237 to 249 (the definition, intervals for a mean, M-estimates and smooth functionals, and the chi-squared limit)
- Art B. Owen, Empirical likelihood ratio confidence regions, Annals of Statistics 18(1), 1990, pp. 90 to 120 (the vector mean, the chi-squared limit with q degrees of freedom, and coverage error)
- Jing Qin and Jerry Lawless, Empirical likelihood and general estimating equations, Annals of Statistics 22(1), 1994, pp. 300 to 325 (estimating equations with more conditions than parameters, the maximum empirical likelihood estimator and its efficiency)
- Art B. Owen, Empirical Likelihood, Chapman and Hall/CRC, 2001, the chapters on the univariate and the vector mean, and the chapter on computation (the pseudo-logarithm and the dual problem)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag DSWA0W Edit this page History Report an error Markdown