Inference

Fitting distributions

Given data and a family of distributions, which member fits? Maximum likelihood picks the parameters that make the data most probable; the method of moments matches the mean and variance. Where the answer has a closed form it is an exact fraction.

Closed forms

import { fit, show } from "@ratmath/stats";

const d = [3, 1, 4, 1, 5, 9, 2, 6];
fit(d, "normal").params;        // { mu: 31/8, variance: 423/64, sigma: 2.570870… }
fit(d, "exponential").params;   // { rate: 8/31 }
fit(d, "poisson").params;       // { lambda: 31/8 }
fit(d, "uniform").params;       // { a: 1, b: 9 }: the smallest and largest values
fit(d, "uniform", { method: "moments" }).params;   // { a: −0.577878…, b: 8.327878… }
fit([2, 3, 1], "binomial", { trials: 4 }).params;  // { trials: 4, p: 1/2 }

For most textbook families the likelihood equations solve in closed form: the normal mean is xˉ\bar x and its variance 1n∑(xi−xˉ)2\frac1n\sum(x_i - \bar x)^2 (dividing by nn, not n−1n - 1), the exponential rate is 1/xˉ1/\bar x, the Poisson mean is xˉ\bar x. With rational data these are exact. The method of moments sets the population mean and variance equal to the sample's; for the uniform distribution that gives xˉ±3v\bar x \pm \sqrt{3v}, which need not even contain the data, while maximum likelihood gives the range of the data.

Gamma: an equation to solve

The gamma family's moment estimates are exact, k=xˉ2/vk = \bar x^2/v and rate xˉ/v\bar x/v. Its maximum-likelihood shape solves

log⁡k−ψ(k)=log⁡xˉ−1n∑log⁡xi, \log k - \psi(k) = \log \bar x - \frac1n \sum \log x_i,

with ψ\psi the digamma function. The left side decreases from ∞\infty to 0, so there is exactly one root, and it is enclosed by bisection on certified values of ψ\psi and log⁡\log (both from @ratmath/analytic). The answer is an interval of width about 2−642^{-64}.

fit(d, "gamma").params;                       // { shape: 2.093251…, rate: 0.540194… }, certified
fit(d, "gamma", { method: "moments" }).params; // { shape: 961/423, rate: 248/423 }, exact
fit([1, 2, 4], "lognormal").params.mu;        // log 2, certified: the mean of the logs

When the parameters are enclosures the result has no distribution, since the distributions take exact parameters; when they are exact, distribution is the fitted member, ready for its density, quantiles or samples.

Try itEdit the code and run it with @ratmath/stats and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs