Techniquecore
Box-Cox transformation
Also called Box-Cox power transform.
Transforms a positive response by (y^lambda - 1) / lambda, or log y at lambda = 0, choosing lambda by profile likelihood to make errors closer to normal with constant variance.
The Box-Cox transformation replaces a positive response by , which is in the limit , and chooses the power by maximum likelihood. The model is that for some the transformed responses follow a linear model with independent normal errors of constant variance. Maximizing out the coefficients and the variance leaves a one-dimensional function, the profile log-likelihood , whose second term is the Jacobian of the change of scale. One QR factorization of the design matrix makes each value of cost , so a grid search, a golden-section refinement and a likelihood ratio interval for cost little more than one fit. George Box and David Cox published the method in 1964. It is a choice of scale for the analysis, not a cure: it cannot make every data set normal, and it needs .
In plain words
Many measurements, such as incomes, concentrations and times, are skewed, and their spread grows with their size. A straight-line model with even scatter fits them badly. Taking logs often helps; taking square roots or reciprocals sometimes helps more. The Box-Cox method tries the whole range of powers between them and asks the data which one makes the scatter around the fitted model look most like even, bell-shaped noise. To compare different powers fairly, it corrects for the fact that a power stretches or squeezes the scale. The answer comes with a range of powers that fit about equally well, so a simple power in that range, such as the log, can be used.
When it applies
- The response is strictly positive, and the analysis is a linear model in some scale: with an matrix of rank .
- The departures to fix are skewness and a variance that changes with the mean, and one power can fix both at once. Often it can: if the standard deviation is proportional to the mean to the power , then stabilizes the variance to first order (the log for , the square root for Poisson-like counts with ).
- The ratio of the largest to the smallest is not close to 1. If all lie in a narrow band, every power is nearly linear on it and the data cannot tell the powers apart.
- The transformed scale has a meaning for the user, or only tests and predictions are needed. Coefficients on the scale are hard to interpret.
The template
The input is , the design matrix (with an intercept unless there is a reason not to have one), a search range with grid points, a tolerance and a confidence level .
BOX-COX(y[1..n], X, λlo, λhi, m, tol, level)- 1
if some y_i ≤ 0 then error "Box-Cox needs y > 0" - 2
L_i ← log y_i; G ← mean of the L_i; factor X = QR once by Householder reflections - 3
define ℓ(λ) = −(n/2) log(RSS(λ)/n) + (λ − 1) Σ L_i ▷ RSS of the fit of y^(λ) on X, O(np) with Q - 4
evaluate ℓ at m equally spaced λ_j in [λlo, λhi]; let λ_k be the best - 5
λ̂ ← golden-section maximum of ℓ on [λ_(k−1), λ_(k+1)], to tolerance tol - 6
target ← ℓ(λ̂) − χ²_(1, level)/2 - 7
lower end: bisection between λ̂ and the first grid point below λ̂ with ℓ < target (none: open) - 8
upper end: bisection between λ̂ and the first grid point above λ̂ with ℓ < target (none: open) return λ̂, ℓ(λ̂) and the interval
Why this function of . If has density , the density of is that density times . So the log-likelihood of is
For fixed the maximum over is the least squares fit of on , and over it is . Substituting gives . Without the Jacobian term, the residual sums of squares at different are in different units and cannot be compared: alone mixes the quality of the fit with the change of units, and its minimum has no meaning. An equivalent form divides by , where is the geometric mean; then is of the residual sum of squares of the scaled responses over .
Why one factorization suffices. does not depend on . With by Householder reflections, is the squared norm of the last entries of , which costs to apply. The factorization costs once.
Numerical form. Evaluating directly loses all digits for small (catastrophic cancellation), and overflows for large . The implementation uses centered logs and the identity
The second term is the same for every , so it is dropped when contains the intercept. At the expression is , and the limit is continuous.
What is exact and what is not. The function is computed exactly up to rounding. The grid in L4 finds the best of points, and golden-section search (see golden-section search) then converges to a local maximum in the bracket around it. If has two separated peaks of nearly equal height, the grid may pick the lower one; nothing in the method proves a global maximum, and a plot of is the check. The interval of L6 to L8 is the likelihood ratio interval: by Wilks' theorem, under , so its coverage is only asymptotic. The bisection method finds the first crossing of the target level on each side; if dips below and rises again, the set is not an interval, and the method returns its inner part.
Cost. for the factorization, then for each of the evaluations: time and space.
Example. The eight values of the Q-Q plot example, with an intercept only (), give
| 76.03 | 21.83 | 9.977 | 7.849 | 9.795 | 34.49 | |
| 1.071 | 2.507 | 1.771 |
alone is smallest near ; the Jacobian term moves the maximum of . The search on with 81 grid points gives and . The 95% interval, where , is . It contains 0, with likelihood ratio statistic , so the log scale is supported. It excludes 1: the statistic for no transformation is , with p-value 0.0097 against . The Q-Q plot of the logs is nearly straight, with correlation 0.996.
Measured coverage. With on equally spaced in (true ), 1000 replications with seed 21 and the search range gave a coverage of 0.926 for the nominal 95% interval. With true , (seed 22), it was 0.939, and with true and (seed 23) it was 0.946. These are measurements for one design; they show the interval is a little short in small samples, as an asymptotic interval often is.
Classic examples
- Survival times in a factorial experiment. Box and Cox (1964) analyzed the survival times of animals under three poisons and four treatments. The likelihood pointed near , so they analyzed the reciprocal, the rate of dying. On that scale the variances were close to equal and the evidence for an interaction between poison and treatment became weak, so a simpler model and the usual F-tests of the analysis of variance could be used.
- Cycles to failure. Their second example, the number of cycles to failure of worsted yarn in a design, pointed to the log. On the log scale a model with main effects only described the data well.
- Fixing a fan of residuals. When the residuals spread out with the fitted values, a Box-Cox power is one remedy for heteroscedasticity, next to weighting and robust standard errors.
- Checking normality before a t-test or ANOVA. Transform, then check the residuals with a Q-Q plot, as in the example.
Variations
- Shifted family. allows ; Box and Cox gave it in the same paper. The likelihood in can be unbounded as , so is usually fixed.
- Yeo-Johnson. A power family for all real : for and for , with logs in the limits. The same profile likelihood method applies, with Jacobian .
- Rounded powers. Choose the simplest value in the interval, from , and analyze on that scale. This is what Box and Cox did.
- Transforming the predictors. Box and Tidwell fit powers of the predictors instead of the response, for nonlinearity without a change of the error scale.
- Modeling the mean and variance directly. A generalized linear model keeps on its own scale and states a link and a variance function, so the mean of , not of a transform of , is modeled.
Pitfalls
- Zeros and negative values. The method is undefined for . Adding a constant before the transform changes and the conclusions, and the choice of constant is arbitrary. Use the shifted family with care, or Yeo-Johnson, or a model for counts.
- Inference after choosing . Tests and intervals for that treat as known ignore its estimation. Bickel and Doksum (1981) showed that the variance of can then grow a lot; Box and Cox replied that has no fixed meaning when the scale itself is estimated. A fixed round chosen from the interval avoids most of the issue.
- Back-transforming. The inverse of the fitted mean on the log scale estimates the median of , not its mean. For the mean under normal errors on the log scale, multiply by .
- Outliers decide . One extreme can pull strongly. Check the influence of single points, for example with Cook's distance on the chosen scale.
- One power for three goals. Linearity of the mean, constant variance and normality may need different powers. The likelihood finds a compromise; it may fix none of them well.
- Comparing raw RSS. Choosing by the smallest without the Jacobian, or by the residual standard deviation on each scale, is wrong. In the example it picks a value near 0.5 instead of 0.08.
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/box-cox-transformation/. The authors are listed in prov/KHKPKJ.jsonl.
"""Box-Cox transformation with lambda chosen by profile likelihood.
The model is y_i^(lambda) = x_i^T b + e_i with e_i iid N(0, sigma^2), where
y^(lambda) = (y^lambda - 1) / lambda for lambda != 0 and log y for lambda = 0.
With b and sigma^2 maximized out, the log-likelihood of lambda is
l(lambda) = -(n / 2) log(RSS(lambda) / n) + (lambda - 1) sum log y_i,
up to the constant -(n / 2)(log(2 pi) + 1). X is factored once by Householder
QR; each l(lambda) then costs O(n p). The maximizer comes from a grid search
followed by golden-section refinement, and the likelihood ratio interval
{lambda : 2 (l(lambda_hat) - l(lambda)) <= chi^2_(1, level)} from bisection.
For accuracy the transform is evaluated on centered logs: with L_i = log y_i
and G the mean of the L_i,
y_i^(lambda) / gdot^(lambda - 1) = gdot * (expm1(lambda (L_i - G)) - expm1(-lambda G)) / lambda,
where gdot = exp(G) is the geometric mean. The second term is a constant
vector; it is dropped when the column space of X contains the constants.
"""
import math
from typing import Sequence
from stdist import chi2_ppf
RANK_TOL = 1e-10
_INV_PHI = (math.sqrt(5.0) - 1.0) / 2.0 # 0.618...
def box_cox(y: Sequence[float], lam: float) -> list[float]:
"""The transform y^(lambda) of each entry; every y_i must be positive."""
if any(not v > 0.0 for v in y):
raise ValueError("Box-Cox needs y > 0")
if lam == 0.0:
return [math.log(v) for v in y]
return [math.expm1(lam * math.log(v)) / lam for v in y]
class _Householder:
"""The Householder QR factor of X, kept to compute residual sums of squares."""
def __init__(self, X: Sequence[Sequence[float]]):
n = len(X)
p = len(X[0]) if n else 0
if n == 0 or p == 0 or any(len(row) != p for row in X):
raise ValueError("X must be n x p with p >= 1")
if n <= p:
raise ValueError("need n > p")
A = [[float(v) for v in row] for row in X]
scale = max(math.sqrt(math.fsum(A[i][j] ** 2 for i in range(n))) for j in range(p))
self.n, self.p = n, p
self.vs: list[tuple[list[float], float]] = []
for j in range(p):
norm = math.sqrt(math.fsum(A[i][j] ** 2 for i in range(j, n)))
if norm <= RANK_TOL * scale:
raise ValueError("X does not have full column rank")
alpha = -norm if A[j][j] >= 0.0 else norm
v = [0.0] * n
v[j] = A[j][j] - alpha
for i in range(j + 1, n):
v[i] = A[i][j]
vv = math.fsum(v[i] * v[i] for i in range(j, n))
for k in range(j, p):
s = 2.0 * math.fsum(v[i] * A[i][k] for i in range(j, n)) / vv
for i in range(j, n):
A[i][k] -= s * v[i]
self.vs.append((v, vv))
def rss(self, z: Sequence[float]) -> float:
"""The residual sum of squares of the least squares fit of z on X."""
c = list(z)
n = self.n
for j, (v, vv) in enumerate(self.vs):
s = 2.0 * math.fsum(v[i] * c[i] for i in range(j, n)) / vv
for i in range(j, n):
c[i] -= s * v[i]
return math.fsum(c[i] * c[i] for i in range(self.p, n))
class BoxCoxProfile:
"""l(lambda) for fixed y and X, at O(n p) per evaluation after one QR."""
def __init__(self, y: Sequence[float], X: Sequence[Sequence[float]] | None = None):
n = len(y)
if any(not v > 0.0 for v in y): # @line L1
raise ValueError("Box-Cox needs y > 0")
if X is None:
X = [[1.0] for _ in range(n)]
if len(X) != n:
raise ValueError("X and y must have the same number of rows")
self.n = n
self.logs = [math.log(v) for v in y] # @line L2
self.sum_log = math.fsum(self.logs)
self.G = self.sum_log / n
self.centered = [L - self.G for L in self.logs]
self.qr = _Householder(X)
# The constant vector is dropped when X spans it.
self.spans_one = self.qr.rss([1.0] * n) <= (RANK_TOL ** 2) * n
self.calls = 0
def loglik(self, lam: float) -> float:
"""-(n/2) log(RSS(lambda)/n) + (lambda - 1) sum log y_i.""" # @line L3
self.calls += 1
n = self.n
if lam == 0.0:
u = list(self.centered)
k = self.G
else:
u = [math.expm1(lam * d) / lam for d in self.centered]
k = -math.expm1(-lam * self.G) / lam
if not self.spans_one:
u = [ui + k for ui in u]
rss_u = self.qr.rss(u)
if rss_u <= 0.0:
return math.inf
# RSS(lambda) / gdot^(2 (lambda - 1)) = gdot^2 RSS(u), and gdot = exp(G).
return -0.5 * n * (math.log(rss_u / n) + 2.0 * self.G)
def _golden_max(f, a: float, b: float, tol: float) -> tuple[float, float]:
"""Golden-section search for a maximum of f on [a, b]; returns (x, f(x))."""
c = b - _INV_PHI * (b - a)
d = a + _INV_PHI * (b - a)
fc, fd = f(c), f(d)
while b - a > tol:
if fc >= fd:
b, d, fd = d, c, fc
c = b - _INV_PHI * (b - a)
fc = f(c)
else:
a, c, fc = c, d, fd
d = a + _INV_PHI * (b - a)
fd = f(d)
return (c, fc) if fc >= fd else (d, fd)
def _bisect_level(f, inside: float, outside: float, target: float, tol: float) -> float:
"""The point between inside (f >= target) and outside (f < target) where f crosses target."""
while abs(outside - inside) > tol:
mid = 0.5 * (inside + outside)
if f(mid) >= target:
inside = mid
else:
outside = mid
return 0.5 * (inside + outside)
def box_cox_fit(
y: Sequence[float],
X: Sequence[Sequence[float]] | None = None,
lo: float = -2.0,
hi: float = 2.0,
grid: int = 81,
tol: float = 1e-7,
level: float = 0.95,
):
"""Maximum likelihood lambda on [lo, hi] and its likelihood ratio interval.
X is the n x p design matrix (default: intercept only). Returns
(lam_hat, l_max, ci_low, ci_high); ci_low is None when the interval
reaches past lo, and ci_high is None when it reaches past hi.
"""
if not lo < hi or grid < 3:
raise ValueError("need lo < hi and grid >= 3")
prof = BoxCoxProfile(y, X)
f = prof.loglik
lams = [lo + (hi - lo) * j / (grid - 1) for j in range(grid)]
vals = [f(t) for t in lams] # @line L4
k = max(range(grid), key=lambda j: vals[j])
a = lams[max(k - 1, 0)]
b = lams[min(k + 1, grid - 1)]
lam_hat, l_max = _golden_max(f, a, b, tol) # @line L5
if vals[k] > l_max:
lam_hat, l_max = lams[k], vals[k]
target = l_max - 0.5 * chi2_ppf(level, 1) # @line L6
# Lower end: the first grid point below lam_hat with l < target.
ci_low = None
inside = lam_hat
for t, v in zip(reversed(lams), reversed(vals)): # @line L7
if t >= lam_hat:
continue
if v < target:
ci_low = _bisect_level(f, inside, t, target, tol)
break
inside = t
ci_high = None
inside = lam_hat
for t, v in zip(lams, vals): # @line L8
if t <= lam_hat:
continue
if v < target:
ci_high = _bisect_level(f, inside, t, target, tol)
break
inside = t
return lam_hat, l_max, ci_low, ci_high
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_box_cox_transformation.py 175 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/box-cox-transformation/. The authors are listed in prov/KHKPKJ.jsonl.
import math
import random
import pytest
from box_cox_transformation import BoxCoxProfile, box_cox, box_cox_fit
Y8 = [0.1, 0.2, 0.4, 0.5, 0.9, 1.3, 2.0, 3.6]
def _solve(A, b):
"""Gauss-Jordan elimination with partial pivoting (the brute force for small p)."""
m = len(A)
M = [list(map(float, row)) + [float(v)] for row, v in zip(A, b)]
for c in range(m):
piv = max(range(c, m), key=lambda r: abs(M[r][c]))
M[c], M[piv] = M[piv], M[c]
for r in range(m):
if r != c:
f = M[r][c] / M[c][c]
M[r] = [a - f * bb for a, bb in zip(M[r], M[c])]
return [M[i][m] / M[i][i] for i in range(m)]
def _rss_normal_equations(X, z):
p = len(X[0])
XtX = [[math.fsum(row[i] * row[j] for row in X) for j in range(p)] for i in range(p)]
Xtz = [math.fsum(row[i] * v for row, v in zip(X, z)) for i in range(p)]
b = _solve(XtX, Xtz)
return math.fsum((v - math.fsum(bi * xi for bi, xi in zip(b, row))) ** 2 for row, v in zip(X, z))
def _brute_loglik(y, X, lam):
"""l(lambda) from the plain transform and the normal equations."""
z = [math.log(v) if lam == 0 else (v ** lam - 1.0) / lam for v in y]
n = len(y)
return -0.5 * n * math.log(_rss_normal_equations(X, z) / n) + (lam - 1.0) * math.fsum(map(math.log, y))
def _random_problem(rng, n, p):
X = [[1.0] + [rng.uniform(0.0, 5.0) for _ in range(p - 1)] for _ in range(n)]
lam0 = rng.choice([-0.5, 0.0, 0.5, 1.0])
y = []
for row in X:
z = 0.2 * (2.0 + 0.4 * sum(row[1:]) + rng.gauss(0.0, 0.3)) # z in about (0.2, 1.3)
y.append(math.exp(z) if lam0 == 0.0 else (1.0 + lam0 * z) ** (1.0 / lam0))
return X, y
def test_worked_example() -> None:
lam, lmax, a, b = box_cox_fit(Y8)
assert abs(lam - 0.07784) < 1e-4
assert abs(lmax - 2.53422) < 1e-4
assert abs(a - (-0.58707)) < 1e-4 and abs(b - 0.76145) < 1e-4
P = BoxCoxProfile(Y8)
assert 2.0 * (lmax - P.loglik(1.0)) > 3.8415 # no transform is rejected
assert 2.0 * (lmax - P.loglik(0.0)) < 3.8415 # the log is not
def test_profile_matches_plain_formula() -> None:
rng = random.Random(1)
for _ in range(60):
n, p = rng.randint(6, 25), rng.randint(1, 4)
X, y = _random_problem(rng, n, p)
P = BoxCoxProfile(y, X)
# No lambda near 0 here: the plain (y^lambda - 1) / lambda of the brute force cancels there.
for lam in [-2.0, -1.0, -0.3, 0.0, 0.5, 1.0, 1.7, 2.0]:
assert abs(P.loglik(lam) - _brute_loglik(y, X, lam)) < 1e-7 * (1.0 + abs(P.loglik(lam)))
def test_against_dense_grid() -> None:
rng = random.Random(2)
for _ in range(25):
n, p = rng.randint(8, 20), rng.randint(1, 3)
X, y = _random_problem(rng, n, p)
lam, lmax, _, _ = box_cox_fit(y, X)
grid = [-2.0 + 4.0 * j / 4000 for j in range(4001)]
P = BoxCoxProfile(y, X)
vals = [P.loglik(t) for t in grid]
j = max(range(len(grid)), key=lambda i: vals[i])
assert lmax >= vals[j] - 1e-9
assert abs(lam - grid[j]) <= 1e-3 + 1e-9 or abs(lmax - vals[j]) < 1e-6
def test_profile_equals_maximized_full_likelihood() -> None:
rng = random.Random(3)
X, y = _random_problem(rng, 15, 3)
n = len(y)
P = BoxCoxProfile(y, X)
for lam in [-1.0, 0.0, 0.4, 1.3]:
z = box_cox(y, lam)
p = len(X[0])
XtX = [[math.fsum(r[i] * r[j] for r in X) for j in range(p)] for i in range(p)]
b = _solve(XtX, [math.fsum(r[i] * v for r, v in zip(X, z)) for i in range(p)])
res = [v - math.fsum(bi * xi for bi, xi in zip(b, r)) for r, v in zip(X, z)]
s2 = math.fsum(e * e for e in res) / n
full = math.fsum(-0.5 * math.log(2.0 * math.pi * s2) - e * e / (2.0 * s2) for e in res)
full += (lam - 1.0) * math.fsum(map(math.log, y))
# Perturbing b or sigma^2 can only lower the full likelihood.
worse = math.fsum(-0.5 * math.log(2.0 * math.pi * s2 * 1.1) - (e + 0.01) ** 2 / (2.0 * s2 * 1.1) for e in res)
worse += (lam - 1.0) * math.fsum(map(math.log, y))
assert worse < full
assert abs(full - (P.loglik(lam) - 0.5 * n * (math.log(2.0 * math.pi) + 1.0))) < 1e-9 * n
def test_scale_invariance_with_intercept() -> None:
rng = random.Random(4)
X, y = _random_problem(rng, 18, 2)
a = box_cox_fit(y, X, lo=-8.0, hi=8.0)
assert a[2] is not None and a[3] is not None
for c in [1e-3, 7.0, 1e4]:
b = box_cox_fit([c * v for v in y], X, lo=-8.0, hi=8.0)
assert abs(a[0] - b[0]) < 1e-5
assert abs(a[2] - b[2]) < 1e-5 and abs(a[3] - b[3]) < 1e-5
# l changes by the constant -n log c.
assert abs((b[1] - a[1]) + len(y) * math.log(c)) < 1e-6 * len(y)
def test_lambda_zero_is_continuous_and_lambda_one_is_a_shift() -> None:
P = BoxCoxProfile(Y8)
assert abs(P.loglik(1e-10) - P.loglik(0.0)) < 1e-8
assert abs(P.loglik(-1e-10) - P.loglik(0.0)) < 1e-8
m = sum(Y8) / len(Y8)
rss = math.fsum((v - m) ** 2 for v in Y8)
assert abs(P.loglik(1.0) - (-4.0 * math.log(rss / 8.0))) < 1e-12
assert box_cox([math.e], 0.0) == [1.0]
assert abs(box_cox([4.0], 0.5)[0] - 2.0) < 1e-15
def test_without_intercept_keeps_the_constant() -> None:
rng = random.Random(5)
n = 12
X = [[rng.uniform(1.0, 3.0)] for _ in range(n)]
y = [math.exp(0.5 * r[0] + rng.gauss(0.0, 0.1)) for r in X]
P = BoxCoxProfile(y, X)
assert not P.spans_one
for lam in [-0.7, 0.0, 0.6, 1.0]:
assert abs(P.loglik(lam) - _brute_loglik(y, X, lam)) < 1e-8 * (1.0 + abs(P.loglik(lam)))
def test_rejects_bad_input() -> None:
with pytest.raises(ValueError):
box_cox_fit([1.0, 0.0, 2.0, 3.0])
with pytest.raises(ValueError):
box_cox_fit([1.0, -2.0, 2.0, 3.0])
with pytest.raises(ValueError):
box_cox([1.0, -1.0], 0.5)
with pytest.raises(ValueError):
box_cox_fit([1.0, 2.0, 3.0, 4.0], [[1.0, 2.0], [1.0, 2.0], [1.0, 2.0], [1.0, 2.0]])
with pytest.raises(ValueError):
box_cox_fit([1.0, 2.0], [[1.0, 1.0], [1.0, 2.0]])
def test_open_interval_is_reported() -> None:
# Two-point-like data give a flat profile: the interval runs past [lo, hi].
lam, lmax, a, b = box_cox_fit([1.0, 1.1, 1.05, 1.08], lo=-0.5, hi=0.5)
assert a is None and b is None
assert -0.5 <= lam <= 0.5
def test_coverage_monte_carlo() -> None:
rng = random.Random(21)
n, r = 20, 200
x = [1.0 + 9.0 * i / (n - 1) for i in range(n)]
X = [[1.0, v] for v in x]
cover = 0
for _ in range(r):
y = [math.exp(1.0 + 0.3 * v + rng.gauss(0.0, 0.25)) for v in x]
_, _, a, b = box_cox_fit(y, X, lo=-3.0, hi=3.0)
if (a is None or a <= 0.0) and (b is None or 0.0 <= b):
cover += 1
assert 0.88 <= cover / r <= 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
- Derive the profile log-likelihood from the normal density of , including the Jacobian.
- Show that as , and that is increasing in for every .
- Show that when contains the intercept, replacing by with does not change or the interval, and that it changes by the constant .
- Use the delta method to show that if , then (or when ) has approximately constant variance.
- Write the profile log-likelihood for the Yeo-Johnson family and find its Jacobian term.
References
- G. E. P. Box and D. R. Cox, An analysis of transformations, Journal of the Royal Statistical Society, Series B 26(2), 1964, pp. 211 to 243, The whole paper (the power family, the likelihood with the Jacobian, the maximized log-likelihood in lambda and its approximate confidence region, the biological and textile examples)
- In-Kwon Yeo and Richard A. Johnson, A new family of power transformations to improve normality or symmetry, Biometrika 87(4), 2000, pp. 954 to 959, The whole paper (a power family defined for all real y)
- Peter J. Bickel and Kjell A. Doksum, An analysis of transformations revisited, Journal of the American Statistical Association 76, 1981, pp. 296 to 311, The whole paper (the extra variance of the regression coefficients when lambda is estimated)
- George A. F. Seber and Alan J. Lee, Linear Regression Analysis, second edition, Wiley, 2003, Chapter 10 (departures from the assumptions, transforming the response, the Box-Cox method)
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 | W3 standard |
|
Tag KHKPKJ Edit this page History Report an error Markdown