Choose the Box-Cox lambda by maximum likelihood over a grid
Why it matters Box-Cox is a classic fix for skewed positive targets such as prices and waiting times, and its likelihood-based lambda search is a common interview follow-up.
Box-Cox needs a lambda, and the usual choice is the one that makes the transformed data look most Gaussian by likelihood.
Write boxcox_best_lambda(x, lambdas). x is a 1D sequence of strictly positive values; raise ValueError if any value is <= 0. For each lam in lambdas, transform y = (x^lam - 1) / lam (or log x when |lam| < 1e-12) and score it with the profile log-likelihood llf = (lam - 1) * sum(log x) - n / 2 * log(var(y)), where var uses ddof 0. Return (best_lam, best_llf, y_best) for the highest llf (the first one wins ties), with best_lam and best_llf as floats.
def boxcox_best_lambda(x, lambdas)Example
x [1, 2, 4, 8, 16], lambdas [-1, 0, 0.5, 1] gives best_lam 0.0, best_llf -6.8318 (rounded) and y_best = log x = [0, 0.6931, 1.3863, 2.0794, 2.7726].
Understand the idea
Box-Cox transforms positive data with y = (x^lam - 1) / lam, and lam = 0 means log x. To choose lam we ask which version of y looks most like a normal distribution, measured by likelihood.
There is a catch. Changing lam also stretches or shrinks the number line, so comparing raw variances is unfair: a tiny lam squashes everything and gives a tiny variance. The Jacobian term (lam - 1) * sum(log x) corrects for that stretching.
Worked example: x = 1, 2, 4, 8, 16. With lam = 0, y = log x = 0, 0.69, 1.39, 2.08, 2.77, perfectly evenly spaced, so it should win. Its variance is about 0.961, giving llf = -1 * 6.93 - 2.5 * log(0.961), about -6.83, which beats lam = 0.5 and lam = 1.
Rule: llf(lam) = (lam - 1) * sum(log x) - n / 2 * log(var(y)). Pick the lam with the largest llf, then reuse it on test data.
Statistics libraries fit Box-Cox exactly this way, just with a continuous optimiser instead of a grid.