Algorithm Search⌘K

Algorithmadvanced

Restricted maximum likelihood

Also called REML, residual maximum likelihood.

Estimates variance components by maximizing the likelihood of error contrasts that do not depend on the fixed effects. It removes the downward bias of ML variance estimates.

Time
Θ(t k n^3) worstΘ(k n^3) best
Space
Θ(k n^2) extra
Counts
flops t ((2 k + 7/3) n^3 + 2 (k^2 + p^2) n^2) worst
Where
k = the number of variance components; n = the number of observations; p = the number of fixed-effect columns; t = the number of likelihood evaluations
Properties
deterministicnot exactofflineiterative
Origin
H. D. Patterson, Robin Thompson, 1971

Restricted maximum likelihood (REML), also called residual maximum likelihood, estimates the covariance parameters θ\theta of a linear mixed model y∼N(Xb,V(θ))y \sim N(Xb, V(\theta)) by maximizing the likelihood of n−pn - p error contrasts K⊤yK^\top y with K⊤X=0K^\top X = 0. On this page bb is the vector of fixed-effect coefficients. The contrasts have mean 0 whatever bb is, so their likelihood depends on θ\theta only. Plain maximum likelihood estimates bb and θ\theta together and does not allow for the degrees of freedom that the estimate of bb uses, so its variance estimates are too small; REML makes that allowance, and for a single normal sample it gives the sample variance with divisor n−1n - 1. After θ^\hat\theta is found, bb is estimated by generalized least squares at V(θ^)V(\hat\theta). REML is the default method for variance components in mixed model software. The algorithm on this page maximizes the restricted likelihood by Fisher scoring, keeps every variance component at 0 or above, and reports which components end at 0.

In plain words

Pupils sit in classes, and you want to know two things: how much the classes differ, and how much pupils in one class differ. Plain maximum likelihood fits the averages first and then measures the spread around the fitted averages. The fitted averages follow the data a little too closely, so the measured spread comes out too small. REML first removes everything the averages can explain. It keeps only what is left over, which carries no information about the averages, and asks which spreads make those leftovers most likely. For one sample this gives the usual sample variance that divides by one less than the sample size. The search moves uphill one step at a time. If the best value for the spread between classes would be negative, the method holds it at zero and says so.

The problem

Input. A response y∈Rny \in \mathbb R^n; a fixed-effects design XX (n×pn \times p) of rank p<np < n; symmetric positive semidefinite matrices V1,…,VkV_1, \dots, V_k (n×nn \times n) with Vk=IV_k = I, so that V(θ)=θ1V1+⋯+θkVkV(\theta) = \theta_1V_1 + \dots + \theta_kV_k. For the one-way layout, V1=ZZ⊤V_1 = ZZ^\top and θ=(σu2,σe2)\theta = (\sigma_u^2, \sigma_e^2). The parameter space is θ1,…,θk−1≥0\theta_1, \dots, \theta_{k-1} \ge 0 and θk>0\theta_k > 0.

Output. A maximizer θ^\hat\theta of the restricted log-likelihood over the parameter space, the GLS estimate b^\hat b at θ^\hat\theta, the maximum value, the set of components with θ^j=0\hat\theta_j = 0 and the score there.

The criterion. With A=X⊤V−1XA = X^\top V^{-1}X and P=V−1−V−1XA−1X⊤V−1P = V^{-1} - V^{-1}XA^{-1}X^\top V^{-1},

ℓR(θ)=−12[(n−p)log⁡2π+log⁡∣V∣+log⁡∣A∣−log⁡∣X⊤X∣+y⊤Py].\ell_R(\theta) = -\tfrac12\bigl[(n - p)\log 2\pi + \log|V| + \log|A| - \log|X^\top X| + y^\top Py\bigr].

This is the log density of w=K⊤yw = K^\top y for any n×(n−p)n \times (n - p) matrix KK with K⊤X=0K^\top X = 0 and K⊤K=IK^\top K = I. The ML criterion is ℓ(θ)=−12[nlog⁡2π+log⁡∣V∣+y⊤Py]\ell(\theta) = -\frac12[n\log 2\pi + \log|V| + y^\top Py], with bb already replaced by b^\hat b; the difference is the term log⁡∣A∣−log⁡∣X⊤X∣\log|A| - \log|X^\top X| and n−pn - p in place of nn. The score and the expected information of ℓR\ell_R are

sj=−12tr⁡(PVj)+12y⊤PVjPy,Ijl=12tr⁡(PVjPVl).s_j = -\tfrac12\operatorname{tr}(PV_j) + \tfrac12 y^\top PV_jPy, \qquad I_{jl} = \tfrac12\operatorname{tr}(PV_jPV_l).

For ML, V−1V^{-1} replaces PP in both trace terms.

The algorithm

  1. REML-FISHER-SCORING(y[1..n], X[1..n, 1..p], V_1, ..., V_k, θ⁰, tol, max_iter)
  2. 1θ ← θ⁰, each entry raised to a small positive floor
  3. 2(ℓ, s, I) ← restricted log-likelihood, score and information at θ
  4. 3for it ← 1 to max_iter
  5. 4F ← {1, ..., k} ▷ the free components
  6. 5δ_F ← solution of I[F, F] δ_F = s_F; δ_j ← 0 for j ∉ F
  7. 6if some j ∈ F has θ_j = 0 and δ_j < 0 then remove those j from F and go to L5
  8. 7λ ← 1
  9. 8θ' ← max(θ + λδ, 0) entry by entry; θ'_k ← max(θ'_k, floor)
  10. 9(ℓ', s', I') ← the same quantities at θ'; if ℓ' ≥ ℓ then go to L11
  11. 10λ ← λ/2; if λ < 10⁻⁸ then θ' ← θ (no move) else go to L8
  12. 11record the change max_j |θ'_j - θ_j|; (θ, ℓ, s, I) ← (θ', ℓ', s', I')
  13. 12if the change ≤ tol (1 + max_j θ_j) then leave the loop
  14. 13return θ, b̂ = A⁻¹X^⊤V⁻¹y at θ, ℓ, the set {j : θ_j = 0} and s

Line L5 is a Fisher scoring step, the Newton step with the expected information in place of the Hessian. Lines L4 to L6 are an active set: a component already at 0 whose step points below 0 is held at 0, and the step for the other components is solved again without it. Line L8 projects the step onto the parameter space, and lines L9 and L10 halve the step until the restricted likelihood does not decrease. The floor in line L8 keeps the residual variance positive, so VV stays positive definite. Each evaluation in lines L2 and L9 forms VV, its Cholesky factor, AA, PP and the products PVjPV_j.

Boundary behavior. A variance component of 0 is a boundary point, and the algorithm can stop there. Line L8 puts a component that would go negative at exactly 0, and line L6 keeps it there while the step still points out of the parameter space. At a maximum on the boundary the score of that component is at most 0, which is the Karush-Kuhn-Tucker condition for the bound θj≥0\theta_j \ge 0; at a maximum inside, the score is 0. Line L13 returns the score and the set of components at 0, so that the caller can check this condition and knows that the usual standard errors and the usual χ2\chi^2 tests do not apply to those components.

Example

Three data sets in the one-way layout yij=b0+ui+eijy_{ij} = b_0 + u_i + e_{ij}, each with an intercept and θ=(σu2,σe2)\theta = (\sigma_u^2, \sigma_e^2). Balanced: y=(10,12,14; 15,16,17; 18,20,22)y = (10, 12, 14;\ 15, 16, 17;\ 18, 20, 22). Unbalanced: y=(10,12,14; 15,17; 18,20,22,24)y = (10, 12, 14;\ 15, 17;\ 18, 20, 22, 24). Near-null: y=(10,14,12; 11,13,15; 12,10,14)y = (10, 14, 12;\ 11, 13, 15;\ 12, 10, 14). The start is the sample variance divided by 2 for each component, and tol=10−10\mathrm{tol} = 10^{-10}.

data method σ^u2\hat\sigma_u^2 σ^e2\hat\sigma_e^2 b^0\hat b_0 ℓ^\hat\ell iterations
balanced REML 15 3 16 −18.5185-18.5185 2
balanced ML 29/3=9.666729/3 = 9.6667 3 16 −21.2649-21.2649 2
unbalanced REML 19.2418 4.9723 16.3693 −20.2490-20.2490 9
unbalanced ML 12.4571 4.9413 16.3867 −23.1356-23.1356 10
near-null REML 0 3.25 12.3333 −16.0661-16.0661 3
near-null ML 0 2.8889 12.3333 −17.5444-17.5444 3

In the balanced data the group means are 12, 16 and 20, so MSA=48\mathrm{MSA} = 48 and MSE=3\mathrm{MSE} = 3. REML gives σ^e2=MSE\hat\sigma_e^2 = \mathrm{MSE} and σ^u2=(MSA−MSE)/3=15\hat\sigma_u^2 = (\mathrm{MSA} - \mathrm{MSE})/3 = 15, the unbiased ANOVA estimates. ML gives σ^u2=(SSA/3−MSE)/3=29/3\hat\sigma_u^2 = (\mathrm{SSA}/3 - \mathrm{MSE})/3 = 29/3, smaller because it divides the sum of squares between groups by 3 groups instead of 2 degrees of freedom. In the unbalanced data there is no closed form, and REML again gives a larger σ^u2\hat\sigma_u^2 than ML.

In the near-null data the group means are 12, 13 and 12, so MSA=1<MSE=4\mathrm{MSA} = 1 < \mathrm{MSE} = 4 and the ANOVA estimate of σu2\sigma_u^2 is −1-1. REML stops at σ^u2=0\hat\sigma_u^2 = 0 with σ^e2=SST/8=26/8\hat\sigma_e^2 = \mathrm{SST}/8 = 26/8, the pooled variance of all 9 values. The returned score for σu2\sigma_u^2 is −0.639-0.639 (ML: −1.198-1.198), which is at most 0, so the KKT condition holds and the point is the maximum on the boundary.

A test of σu2=0\sigma_u^2 = 0 in the balanced data compares the REML fit with the REML fit without the random effect, which has σ^e2=14.25\hat\sigma_e^2 = 14.25 and ℓ^=−21.9785\hat\ell = -21.9785. Both models have the same XX, so their restricted likelihoods are comparable. The statistic is 2(−18.5185+21.9785)=6.9202(-18.5185 + 21.9785) = 6.920. The null value is on the boundary, so the reference law for many groups is 12χ02+12χ12\frac12\chi^2_0 + \frac12\chi^2_1 (Chernoff 1954; Self and Liang 1987), and the p-value is 12P(χ12≥6.920)=0.0043\frac12P(\chi^2_1 \ge 6.920) = 0.0043 instead of the χ12\chi^2_1 value 0.0085. With only 3 groups this large-sample law is itself rough; the linear mixed model page gives the exact mass at 0 for the balanced layout.

Correctness

The proof in this folder shows these facts exactly. First, for every KK of rank n−pn - p with K⊤X=0K^\top X = 0, K(K⊤VK)−1K⊤=PK(K^\top VK)^{-1}K^\top = P and ∣K⊤VK∣=∣K⊤K∣ ∣V∣ ∣A∣/∣X⊤X∣|K^\top VK| = |K^\top K|\,|V|\,|A|/|X^\top X|, so the log density of K⊤yK^\top y is ℓR(θ)−12log⁡∣K⊤K∣\ell_R(\theta) - \frac12\log|K^\top K|; the criterion depends on XX only through its column space and not on bb. Second, the score and the expected information have the forms above. Third, with V=σ2IV = \sigma^2I the REML estimate is RSS/(n−p)\mathrm{RSS}/(n - p), which is unbiased, and the ML estimate is RSS/n\mathrm{RSS}/n; for one normal sample (X=1X = \mathbf 1) the REML estimate is the sample variance with divisor n−1n - 1. Fourth, in the balanced one-way layout REML gives the ANOVA estimates when MSA≥MSE\mathrm{MSA} \ge \mathrm{MSE} and (0,SST/(N−1))(0, \mathrm{SST}/(N - 1)) otherwise, and the score of σu2\sigma_u^2 at that boundary point is at most 0. Fifth, the loops stop after at most max_iter\mathrm{max\_iter} outer passes, every iterate is in the parameter space, and the restricted likelihood does not decrease from one iterate to the next.

What is proved is the criterion, its derivatives, the closed forms in the two special cases and the termination. Convergence of Fisher scoring to the global maximum is not proved: ℓR\ell_R need not be concave in θ\theta, and the active set rule of line L6 does not by itself guarantee the sign of the score of a component held at 0. These are measured: the tests check the closed forms against the iterative output on random balanced data, including data that end on the boundary, and check the score against a numerical derivative.

Proof: The restricted likelihood is the likelihood of the error contrasts, gives the divisor n - p, and has a closed form in the balanced one-way layoutfull

Throughout, XX is n×pn \times p of rank p<np < n, V=V(θ)=∑jθjVjV = V(\theta) = \sum_j\theta_jV_j is positive definite, A=X⊤V−1XA = X^\top V^{-1}X, P=V−1−V−1XA−1X⊤V−1P = V^{-1} - V^{-1}XA^{-1}X^\top V^{-1}, b^=A−1X⊤V−1y\hat b = A^{-1}X^\top V^{-1}y and

ℓR(θ)=−12[(n−p)log⁡2π+log⁡∣V∣+log⁡∣A∣−log⁡∣X⊤X∣+y⊤Py].\ell_R(\theta) = -\tfrac12\bigl[(n - p)\log 2\pi + \log|V| + \log|A| - \log|X^\top X| + y^\top Py\bigr].

The vector bb holds the fixed-effect coefficients. Two facts about PP are used: PX=V−1X−V−1XA−1A=0PX = V^{-1}X - V^{-1}XA^{-1}A = 0, and VPV=V−XA−1X⊤VPV = V - XA^{-1}X^\top, by direct multiplication. Also y⊤Py=(y−Xb^)⊤V−1(y−Xb^)y^\top Py = (y - X\hat b)^\top V^{-1}(y - X\hat b), because V−1(y−Xb^)=PyV^{-1}(y - X\hat b) = Py and b^⊤X⊤Py=0\hat b^\top X^\top Py = 0.

Lemma 1 (error contrasts). Let KK be n×(n−p)n \times (n - p) of rank n−pn - p with K⊤X=0K^\top X = 0. Then (a) K(K⊤VK)−1K⊤=PK(K^\top VK)^{-1}K^\top = P, and (b) ∣K⊤VK∣=∣K⊤K∣ ∣V∣ ∣A∣/∣X⊤X∣|K^\top VK| = |K^\top K|\,|V|\,|A|/|X^\top X|. So w=K⊤y∼N(0,K⊤VK)w = K^\top y \sim N(0, K^\top VK) has log density ℓR(θ)−12log⁡∣K⊤K∣\ell_R(\theta) - \frac12\log|K^\top K|, which is ℓR(θ)\ell_R(\theta) when K⊤K=IK^\top K = I.

Proof. K⊤VKK^\top VK is positive definite because KK has full column rank. The n×nn \times n matrix [VK X][VK\ X] is invertible: if VKα+Xβ=0VK\alpha + X\beta = 0, multiply by K⊤K^\top to get K⊤VKα=0K^\top VK\alpha = 0, so α=0\alpha = 0, and then Xβ=0X\beta = 0 gives β=0\beta = 0. Let Q=K(K⊤VK)−1K⊤Q = K(K^\top VK)^{-1}K^\top. Then QVK=KQVK = K and QX=0QX = 0, and also PVK=K−V−1XA−1X⊤K=KPVK = K - V^{-1}XA^{-1}X^\top K = K and PX=0PX = 0. So QQ and PP agree on the columns of an invertible matrix, and Q=PQ = P. This is (a).

For (b) let T=[K X]T = [K\ X], which is invertible by the same argument with V=IV = I. Since K⊤X=0K^\top X = 0, T⊤TT^\top T is block diagonal and ∣T∣2=∣K⊤K∣ ∣X⊤X∣|T|^2 = |K^\top K|\,|X^\top X|. Now

T⊤VT=(K⊤VKK⊤VXX⊤VKX⊤VX),T^\top VT = \begin{pmatrix} K^\top VK & K^\top VX \\ X^\top VK & X^\top VX \end{pmatrix},

and the Schur complement of the upper block is X⊤VX−X⊤VQVX=X⊤(V−VPV)X=X⊤XA−1X⊤XX^\top VX - X^\top VQVX = X^\top(V - VPV)X = X^\top XA^{-1}X^\top X by (a) and the fact VPV=V−XA−1X⊤VPV = V - XA^{-1}X^\top. So ∣T⊤VT∣=∣K⊤VK∣ ∣X⊤X∣2/∣A∣|T^\top VT| = |K^\top VK|\,|X^\top X|^2/|A|. Also ∣T⊤VT∣=∣T∣2∣V∣=∣K⊤K∣ ∣X⊤X∣ ∣V∣|T^\top VT| = |T|^2|V| = |K^\top K|\,|X^\top X|\,|V|. Equating the two gives (b).

Finally E[w]=K⊤Xb=0E[w] = K^\top Xb = 0 and Cov⁡(w)=K⊤VK\operatorname{Cov}(w) = K^\top VK, so the log density of ww is −12[(n−p)log⁡2π+log⁡∣K⊤VK∣+w⊤(K⊤VK)−1w]-\frac12[(n - p)\log 2\pi + \log|K^\top VK| + w^\top(K^\top VK)^{-1}w]. By (a) the quadratic form is y⊤Qy=y⊤Pyy^\top Qy = y^\top Py, and by (b) the log determinant is log⁡∣K⊤K∣+log⁡∣V∣+log⁡∣A∣−log⁡∣X⊤X∣\log|K^\top K| + \log|V| + \log|A| - \log|X^\top X|. □\square

Consequences. ℓR\ell_R does not depend on bb. If XX is replaced by XMXM for an invertible p×pp \times p matrix MM, then ∣A∣|A| and ∣X⊤X∣|X^\top X| are both multiplied by ∣M∣2|M|^2 and PP does not change, so ℓR\ell_R depends on XX only through its column space.

Lemma 2 (score and expected information). If V=∑jθjVjV = \sum_j\theta_jV_j, then ∂ℓR/∂θj=−12tr⁡(PVj)+12y⊤PVjPy\partial\ell_R/\partial\theta_j = -\frac12\operatorname{tr}(PV_j) + \frac12y^\top PV_jPy, and E[−∂2ℓR/∂θj∂θl]=12tr⁡(PVjPVl)E[-\partial^2\ell_R/\partial\theta_j\partial\theta_l] = \frac12\operatorname{tr}(PV_jPV_l).

Proof. Take KK with K⊤K=IK^\top K = I and write Σ=K⊤VK\Sigma = K^\top VK, Σj=∂Σ/∂θj=K⊤VjK\Sigma_j = \partial\Sigma/\partial\theta_j = K^\top V_jK, so that ℓR=−12[const+log⁡∣Σ∣+w⊤Σ−1w]\ell_R = -\frac12[\text{const} + \log|\Sigma| + w^\top\Sigma^{-1}w] by Lemma 1. The rules ∂log⁡∣Σ∣=tr⁡(Σ−1∂Σ)\partial\log|\Sigma| = \operatorname{tr}(\Sigma^{-1}\partial\Sigma) and ∂Σ−1=−Σ−1(∂Σ)Σ−1\partial\Sigma^{-1} = -\Sigma^{-1}(\partial\Sigma)\Sigma^{-1} give

∂ℓR∂θj=−12tr⁡(Σ−1Σj)+12w⊤Σ−1ΣjΣ−1w.\frac{\partial\ell_R}{\partial\theta_j} = -\tfrac12\operatorname{tr}(\Sigma^{-1}\Sigma_j) + \tfrac12w^\top\Sigma^{-1}\Sigma_j\Sigma^{-1}w.

By Lemma 1(a), KΣ−1K⊤=PK\Sigma^{-1}K^\top = P, so tr⁡(Σ−1K⊤VjK)=tr⁡(PVj)\operatorname{tr}(\Sigma^{-1}K^\top V_jK) = \operatorname{tr}(PV_j) and w⊤Σ−1K⊤VjKΣ−1w=y⊤PVjPyw^\top\Sigma^{-1}K^\top V_jK\Sigma^{-1}w = y^\top PV_jPy. Since Σ\Sigma is linear in θ\theta, differentiating again gives

−∂2ℓR∂θj∂θl=−12tr⁡(Σ−1ΣlΣ−1Σj)+12w⊤Σ−1(ΣlΣ−1Σj+ΣjΣ−1Σl)Σ−1w.-\frac{\partial^2\ell_R}{\partial\theta_j\partial\theta_l} = -\tfrac12\operatorname{tr}(\Sigma^{-1}\Sigma_l\Sigma^{-1}\Sigma_j) + \tfrac12w^\top\Sigma^{-1}(\Sigma_l\Sigma^{-1}\Sigma_j + \Sigma_j\Sigma^{-1}\Sigma_l)\Sigma^{-1}w.

With E[w⊤Bw]=tr⁡(BΣ)E[w^\top Bw] = \operatorname{tr}(B\Sigma) the expectation of the second term is tr⁡(Σ−1ΣjΣ−1Σl)\operatorname{tr}(\Sigma^{-1}\Sigma_j\Sigma^{-1}\Sigma_l), and the sum is 12tr⁡(Σ−1ΣjΣ−1Σl)=12tr⁡(PVjPVl)\frac12\operatorname{tr}(\Sigma^{-1}\Sigma_j\Sigma^{-1}\Sigma_l) = \frac12\operatorname{tr}(PV_jPV_l), again by Lemma 1(a). □\square

The ML criterion ℓ=−12[nlog⁡2π+log⁡∣V∣+y⊤Py]\ell = -\frac12[n\log 2\pi + \log|V| + y^\top Py] has the score −12tr⁡(V−1Vj)+12y⊤PVjPy-\frac12\operatorname{tr}(V^{-1}V_j) + \frac12y^\top PV_jPy and the information 12tr⁡(V−1VjV−1Vl)\frac12\operatorname{tr}(V^{-1}V_jV^{-1}V_l) by the same rules; this is the "ml" branch of the implementation.

Theorem 1 (one variance: the divisor n - p). Let V=σ2IV = \sigma^2I (k=1k = 1, V1=IV_1 = I) and RSS=min⁡b∥y−Xb∥2>0\mathrm{RSS} = \min_b\lVert y - Xb\rVert^2 > 0. The REML estimate is σ^R2=RSS/(n−p)\hat\sigma^2_R = \mathrm{RSS}/(n - p), which is unbiased, and the ML estimate is σ^M2=RSS/n\hat\sigma^2_M = \mathrm{RSS}/n. For one normal sample, X=1X = \mathbf 1 and p=1p = 1, so σ^R2=1n−1∑i(yi−yˉ)2\hat\sigma^2_R = \frac{1}{n-1}\sum_i(y_i - \bar y)^2, the sample variance S2S^2 with divisor n−1n - 1.

Proof. Here ∣V∣=σ2n|V| = \sigma^{2n}, A=X⊤X/σ2A = X^\top X/\sigma^2 so log⁡∣A∣−log⁡∣X⊤X∣=−plog⁡σ2\log|A| - \log|X^\top X| = -p\log\sigma^2, and P=(I−H)/σ2P = (I - H)/\sigma^2 with H=X(X⊤X)−1X⊤H = X(X^\top X)^{-1}X^\top, so y⊤Py=RSS/σ2y^\top Py = \mathrm{RSS}/\sigma^2. Hence

ℓR(σ2)=−12[(n−p)log⁡2π+(n−p)log⁡σ2+RSS/σ2].\ell_R(\sigma^2) = -\tfrac12\bigl[(n - p)\log 2\pi + (n - p)\log\sigma^2 + \mathrm{RSS}/\sigma^2\bigr].

The function g(s)=clog⁡s+R/sg(s) = c\log s + R/s with c,R>0c, R > 0 has g′(s)=(cs−R)/s2g'(s) = (cs - R)/s^2, negative for s<R/cs < R/c and positive for s>R/cs > R/c, so −12g-\frac12 g has its unique maximum at s=R/cs = R/c. With c=n−pc = n - p this is RSS/(n−p)\mathrm{RSS}/(n - p); for ML, c=nc = n and the maximum is RSS/n\mathrm{RSS}/n. Since y−Xb^=(I−H)y=(I−H)(y−Xb)y - X\hat b = (I - H)y = (I - H)(y - Xb) and I−HI - H is a projection of rank n−pn - p, E[RSS]=tr⁡((I−H)σ2I)=(n−p)σ2E[\mathrm{RSS}] = \operatorname{tr}((I - H)\sigma^2I) = (n - p)\sigma^2. □\square

Theorem 2 (balanced one-way layout). Let yij=b0+ui+eijy_{ij} = b_0 + u_i + e_{ij} for a≥2a \ge 2 groups of size m≥2m \ge 2, N=amN = am, θ=(σu2,σe2)\theta = (\sigma_u^2, \sigma_e^2), V1=ZZ⊤V_1 = ZZ^\top, V2=IV_2 = I, X=1X = \mathbf 1. Let SSA\mathrm{SSA}, SSE\mathrm{SSE} and SST=SSA+SSE\mathrm{SST} = \mathrm{SSA} + \mathrm{SSE} be the sums of squares between groups, within groups and in total, with MSA=SSA/(a−1)\mathrm{MSA} = \mathrm{SSA}/(a - 1) and MSE=SSE/(a(m−1))\mathrm{MSE} = \mathrm{SSE}/(a(m - 1)), and assume SSA>0\mathrm{SSA} > 0 and SSE>0\mathrm{SSE} > 0. Then the maximizer of ℓR\ell_R over σu2≥0\sigma_u^2 \ge 0, σe2>0\sigma_e^2 > 0 is

  • σ^e2=MSE\hat\sigma_e^2 = \mathrm{MSE} and σ^u2=(MSA−MSE)/m\hat\sigma_u^2 = (\mathrm{MSA} - \mathrm{MSE})/m if MSA≥MSE\mathrm{MSA} \ge \mathrm{MSE},
  • σ^u2=0\hat\sigma_u^2 = 0 and σ^e2=SST/(N−1)\hat\sigma_e^2 = \mathrm{SST}/(N - 1) if MSA<MSE\mathrm{MSA} < \mathrm{MSE}.

For ML the same holds with SSA/a\mathrm{SSA}/a in place of MSA\mathrm{MSA} and SST/N\mathrm{SST}/N in place of SST/(N−1)\mathrm{SST}/(N - 1). In the second case the score of σu2\sigma_u^2 at the maximum is negative.

Proof. Let λ=σe2+mσu2\lambda = \sigma_e^2 + m\sigma_u^2. VV is block diagonal with blocks σe2Im+σu211⊤\sigma_e^2I_m + \sigma_u^2\mathbf 1\mathbf 1^\top, which have the eigenvalue λ\lambda on 1\mathbf 1 and σe2\sigma_e^2 on the m−1m - 1 directions orthogonal to 1\mathbf 1. So ∣V∣=λaσe2a(m−1)|V| = \lambda^a\sigma_e^{2a(m-1)}, and

(y−1b0)⊤V−1(y−1b0)=SSEσe2+m∑i(yˉi⋅−b0)2λ,(y - \mathbf 1b_0)^\top V^{-1}(y - \mathbf 1b_0) = \frac{\mathrm{SSE}}{\sigma_e^2} + \frac{m\sum_i(\bar y_{i\cdot} - b_0)^2}{\lambda},

which is smallest at b0=yˉ⋅⋅b_0 = \bar y_{\cdot\cdot}, so y⊤Py=SSE/σe2+SSA/λy^\top Py = \mathrm{SSE}/\sigma_e^2 + \mathrm{SSA}/\lambda. Also A=1⊤V−11=N/λA = \mathbf 1^\top V^{-1}\mathbf 1 = N/\lambda and X⊤X=NX^\top X = N, so log⁡∣A∣−log⁡∣X⊤X∣=−log⁡λ\log|A| - \log|X^\top X| = -\log\lambda. Therefore, with the precisions μ=1/σe2\mu = 1/\sigma_e^2 and ν=1/λ\nu = 1/\lambda,

ℓR=const+12[celog⁡μ−SSE μ+cλlog⁡ν−SSA ν],ce=a(m−1), cλ=a−1.\ell_R = \text{const} + \tfrac12\bigl[c_e\log\mu - \mathrm{SSE}\,\mu + c_\lambda\log\nu - \mathrm{SSA}\,\nu\bigr], \qquad c_e = a(m - 1),\ c_\lambda = a - 1.

For ML the same calculation without the log⁡∣A∣\log|A| terms gives cλ=ac_\lambda = a. The constraint σu2≥0\sigma_u^2 \ge 0 is λ≥σe2\lambda \ge \sigma_e^2, that is ν≤μ\nu \le \mu. So the problem is to maximize f(μ,ν)=celog⁡μ−SSE μ+cλlog⁡ν−SSA νf(\mu, \nu) = c_e\log\mu - \mathrm{SSE}\,\mu + c_\lambda\log\nu - \mathrm{SSA}\,\nu over the convex set D={0<ν≤μ}D = \{0 < \nu \le \mu\}.

ff is strictly concave and tends to −∞-\infty as ν→0\nu \to 0 or μ→∞\mu \to \infty in DD, so it has a maximum on DD, and the maximum is unique. Its unconstrained maximizer is μ∗=ce/SSE\mu^* = c_e/\mathrm{SSE}, ν∗=cλ/SSA\nu^* = c_\lambda/\mathrm{SSA}, by the argument for gg in Theorem 1 applied to each variable.

If SSA/cλ≥SSE/ce\mathrm{SSA}/c_\lambda \ge \mathrm{SSE}/c_e, then ν∗≤μ∗\nu^* \le \mu^*, so (μ∗,ν∗)∈D(\mu^*, \nu^*) \in D is the maximum: σ^e2=SSE/ce\hat\sigma_e^2 = \mathrm{SSE}/c_e and λ^=SSA/cλ\hat\lambda = \mathrm{SSA}/c_\lambda, and σ^u2=(λ^−σ^e2)/m\hat\sigma_u^2 = (\hat\lambda - \hat\sigma_e^2)/m. For REML SSA/cλ=MSA\mathrm{SSA}/c_\lambda = \mathrm{MSA}, which gives the first case.

If SSA/cλ<SSE/ce\mathrm{SSA}/c_\lambda < \mathrm{SSE}/c_e, then (μ∗,ν∗)∉D(\mu^*, \nu^*) \notin D. Suppose the maximum (μ0,ν0)(\mu_0, \nu_0) had ν0<μ0\nu_0 < \mu_0. Then it would be a local maximum of ff on an open set, so ∇f(μ0,ν0)=0\nabla f(\mu_0, \nu_0) = 0, and by strict concavity it would be the unconstrained maximizer, which is not in DD. So ν0=μ0=ω\nu_0 = \mu_0 = \omega, which maximizes (ce+cλ)log⁡ω−SST ω(c_e + c_\lambda)\log\omega - \mathrm{SST}\,\omega, so ω=(ce+cλ)/SST\omega = (c_e + c_\lambda)/\mathrm{SST}. Then σ^u2=0\hat\sigma_u^2 = 0 and σ^e2=SST/(ce+cλ)\hat\sigma_e^2 = \mathrm{SST}/(c_e + c_\lambda), which is SST/(N−1)\mathrm{SST}/(N - 1) for REML and SST/N\mathrm{SST}/N for ML.

For the score, ∂/∂σu2=m ∂/∂λ\partial/\partial\sigma_u^2 = m\,\partial/\partial\lambda with σe2\sigma_e^2 fixed, so su=m2[SSA/λ2−cλ/λ]s_u = \frac m2[\mathrm{SSA}/\lambda^2 - c_\lambda/\lambda]. At λ=σe2=σ^2=SST/(ce+cλ)\lambda = \sigma_e^2 = \hat\sigma^2 = \mathrm{SST}/(c_e + c_\lambda) this is mcλ2σ^4[SSA/cλ−σ^2]\frac{m c_\lambda}{2\hat\sigma^4}[\mathrm{SSA}/c_\lambda - \hat\sigma^2]. Since σ^2\hat\sigma^2 is the weighted mean of SSA/cλ\mathrm{SSA}/c_\lambda and SSE/ce\mathrm{SSE}/c_e with weights cλc_\lambda and cec_e, SSA/cλ<σ^2\mathrm{SSA}/c_\lambda < \hat\sigma^2 exactly in the second case, and then su<0s_u < 0. □\square

So in the balanced layout σ^u,R2=max⁡((MSA−MSE)/m,0)\hat\sigma_{u,R}^2 = \max((\mathrm{MSA} - \mathrm{MSE})/m, 0), and the KKT condition (score ≤0\le 0 at a component equal to 0) holds at the REML boundary point. With γ=σu2/σe2\gamma = \sigma_u^2/\sigma_e^2, MSA/((1+mγ)MSE)\mathrm{MSA}/((1 + m\gamma)\mathrm{MSE}) has the Fa−1,a(m−1)F_{a-1, a(m-1)} law (proved on the linear mixed model page), so P(σ^u,R2=0)=P(Fa−1,a(m−1)≤1/(1+mγ))P(\hat\sigma_{u,R}^2 = 0) = P(F_{a-1, a(m-1)} \le 1/(1 + m\gamma)) and P(σ^u,M2=0)=P(Fa−1,a(m−1)≤a/((a−1)(1+mγ)))P(\hat\sigma_{u,M}^2 = 0) = P(F_{a-1, a(m-1)} \le a/((a - 1)(1 + m\gamma))).

Theorem 3 (termination, feasibility and monotonicity). Assume V1,…,Vk−1V_1, \dots, V_{k-1} are positive semidefinite and Vk=IV_k = I. Then the algorithm stops after at most max_iter\mathrm{max\_iter} passes of the loop L3, with at most 28 max_iter+128\,\mathrm{max\_iter} + 1 evaluations; every iterate has θj≥0\theta_j \ge 0 and θk≥\theta_k \ge the floor, so V(θ)V(\theta) is positive definite; and the accepted values of ℓR\ell_R never decrease, apart from the relative tolerance 10−1210^{-12} that the implementation allows for rounding.

Proof. Lines L5 and L6 repeat only when at least one index leaves FF, so they run at most k+1k + 1 times in one pass. In lines L8 to L10, λ\lambda takes the values 20,2−1,…2^0, 2^{-1}, \dots and the loop ends at the latest when λ<10−8\lambda < 10^{-8}, after at most 28 evaluations, since 2−27<10−82^{-27} < 10^{-8}. Line L3 runs at most max_iter\mathrm{max\_iter} times. Line L1 and line L8 set every entry to at least 0 and the last entry to at least the floor, so V=∑j<kθjVj+θkIV = \sum_{j<k}\theta_jV_j + \theta_kI is a positive semidefinite matrix plus a positive multiple of II, hence positive definite. A trial point is accepted in line L9 only if its ℓR\ell_R is not below the current value, and otherwise line L10 keeps θ\theta. □\square

If the information matrix I[F,F]I[F, F] is positive definite and sF≠0s_F \ne 0, the direction δ\delta has s⊤δ=sF⊤I[F,F]−1sF>0s^\top\delta = s_F^\top I[F,F]^{-1}s_F > 0, and for small λ\lambda no free component is clipped in line L8 (those at 0 in FF have δj≥0\delta_j \ge 0), so the halving in line L10 finds an increase in exact arithmetic. A pass that ends with no move has a change of 0 and stops the loop in line L12. That a stopping point is the global maximum, and that a component held at 0 has a score at most 0, is not proved for general VjV_j; Theorem 2 gives the answer in the balanced one-way case, and the tests check the output against it.

Complexity

One evaluation in this dense implementation costs a Cholesky factor and an inverse of VV (73n3\frac73n^3 flops), the kk products PVjPV_j (2kn32kn^3) and the k2k^2 traces of the information (2k2n22k^2n^2), plus O(p2n2)O(p^2n^2) for PP. With tt evaluations the time is Θ(tkn3)\Theta(tkn^3) and the extra space Θ(kn2)\Theta(kn^2) for the products. The number of outer iterations is not bounded by a formula; it was 2 to 10 in the example, and each outer iteration with no halving costs one evaluation. Production programs never form VV: they work with Henderson's equations of order p+qp + q or a sparse Cholesky factor, so that one evaluation costs about as much as one factorization of the mixed model coefficient matrix.

Properties

  • Reparametrization. Centering covariates, rescaling them or changing the coding of a factor does not change the column space of XX, so it does not change the REML estimates.
  • Not exactly unbiased in general. The unbiased closed forms hold only in special cases such as the sample variance. Elsewhere the equations are nonlinear, and the truncation at 0 moves the mean of σ^u2\hat\sigma_u^2 up, as the simulation below shows.
  • Bayesian view. Integrating the normal likelihood over bb with a flat prior gives exp⁡ℓR\exp\ell_R up to a constant (Harville 1974), so REML maximizes a marginal likelihood for θ\theta.
  • Boundary rates. In the balanced one-way layout with aa groups of size mm, the ML estimate of σu2\sigma_u^2 is 0 exactly when (a−1)MSA/a≤MSE(a - 1)\mathrm{MSA}/a \le \mathrm{MSE}, more often than REML. With a=5a = 5, m=4m = 4 and σu2=σe2\sigma_u^2 = \sigma_e^2 the exact probabilities of an estimate of 0 are P(F4,15≤1/5)=0.0656P(F_{4,15} \le 1/5) = 0.0656 for REML and P(F4,15≤1/4)=0.0948P(F_{4,15} \le 1/4) = 0.0948 for ML.
  • Measured bias. In 2000 simulated balanced data sets with a=5a = 5, m=4m = 4 and σu2=σe2=1\sigma_u^2 = \sigma_e^2 = 1 (seed 20261114, using the closed forms proved here), the mean of σ^u2\hat\sigma_u^2 was 1.025 for REML, 0.775 for ML and 1.018 for the ANOVA estimate, which can be negative; the mean of σ^e2\hat\sigma_e^2 was 0.996 for REML and 0.991 for ML. The estimate was 0 in 6.95% of the REML fits and 9.5% of the ML fits.

Variants and improvements

  • Newton-Raphson. The observed information in line L5 converges faster near the maximum but can fail to be positive definite far from it (Lindstrom and Bates 1988).
  • EM. Treating uu as missing data gives an EM algorithm for ML and REML (Laird and Ware 1982; see expectation-maximization). Each step is cheap and keeps the variances positive, but convergence is slow, most when a variance is near 0, and an estimate of exactly 0 is reached only in the limit.
  • Average information. Gilmour, Thompson and Cullis (1995) use the average of the observed and expected information, which needs only quadratic forms in PyPy and is cheap to compute from the mixed model equations. This is the standard algorithm in animal breeding programs.
  • Through the mixed model equations. The traces need not use VV. For G=σu2IqG = \sigma_u^2I_q, tr⁡(Z⊤PZ)=q/σu2−tr⁡(C22)/σu4\operatorname{tr}(Z^\top PZ) = q/\sigma_u^2 - \operatorname{tr}(C^{22})/\sigma_u^4, where C22C^{22} is the lower block of the inverse of the coefficient matrix of Henderson's mixed model equations.
  • Profiled criterion with bounds. lme4 (Bates et al. 2015) writes the random effects through a relative covariance factor, profiles out bb and the residual variance, and minimizes the REML criterion over the factor with a derivative-free optimizer and lower bounds of 0, so a component at 0 is an ordinary bound.

When to use it

Use REML to estimate variance and covariance parameters in a linear mixed model, most of all when the number of groups is small or pp is not small compared with nn, where the ML bias is largest. Use the REML fit for the standard errors of b^\hat b and for comparing covariance structures with the same fixed effects. Use ML when the fixed effects differ between the models compared: REML likelihoods with different fixed effects cannot be compared (use ML for those LR tests). For generalized linear mixed models the likelihood has no closed form; a Laplace approximation or numerical integration replaces it.

Pitfalls

  • Comparing different fixed effects. Two models with different XX have different error contrasts, so their restricted likelihoods are densities of different data, and their difference, or an AIC computed from it, means nothing.
  • Testing a variance component. The likelihood ratio test of σu2=0\sigma_u^2 = 0 does not have the χ12\chi^2_1 law of Wilks' theorem because the null value is on the boundary; use 12χ02+12χ12\frac12\chi^2_0 + \frac12\chi^2_1 for one component, check it by a parametric bootstrap when there are few groups (Crainiceanu and Ruppert 2004), and do not use a Wald test with the inverse information.
  • Estimates at 0. A component at 0 is a valid maximum, not a failure, but the inverse information gives no standard error for it. Removing the component or keeping it at 0 gives the same fit of bb.
  • Local maxima and slow convergence. With many components or a weakly identified structure, scoring can stop at a local maximum or take many halvings; try several starts and compare ℓ^\hat\ell.
  • Plug-in standard errors. (X⊤V(θ^)−1X)−1(X^\top V(\hat\theta)^{-1}X)^{-1} ignores the error in θ^\hat\theta; use the Kenward and Roger (1997) adjustment for small samples.
  • Floating point. Forming VV and PP for large nn is slow and can lose accuracy when the components differ much in size; the methods that use the mixed model equations or a profiled Cholesky factor avoid this.

Implementations

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.

restricted_maximum_likelihood.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/restricted-maximum-likelihood/. The authors are listed in prov/6YVPGK.jsonl.
"""Restricted (residual) maximum likelihood for variance components, by Fisher scoring.

The model is y ~ N(X b, V(theta)) with V(theta) = theta_1 V_1 + ... + theta_m V_m,
known symmetric matrices V_j and theta_j >= 0 (for example V_1 = Z Z^T for a
random effect and V_m = I for the residual). With A = X^T V^-1 X and
P = V^-1 - V^-1 X A^-1 X^T V^-1, the REML log-likelihood is

    l_R(theta) = -1/2 [ (n - p) log 2 pi + log|V| + log|A| - log|X^T X| + y^T P y ],

the log density of n - p error contrasts K^T y with K^T X = 0 and K^T K = I.
Its score is s_j = -1/2 tr(P V_j) + 1/2 y^T P V_j P y and its expected
information is I_jk = 1/2 tr(P V_j P V_k). Ordinary maximum likelihood
(method="ml") is the same with V^-1 in place of P in the trace terms.

Each step is theta + I^-1 s, projected onto theta >= 0 (a small floor keeps the
last component, the residual, positive), and halved until the log-likelihood
does not decrease. A component that ends at 0 is on the boundary; the
returned score must then be <= 0 (the Karush-Kuhn-Tucker condition).
"""

import math
from typing import NamedTuple

FLOOR = 1e-10


def _cholesky(a):
    n = len(a)
    l = [[0.0] * n for _ in range(n)]
    for j in range(n):
        d = a[j][j] - math.fsum(l[j][k] ** 2 for k in range(j))
        if not d > 0.0:
            raise ValueError("matrix is not positive definite")
        l[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            l[i][j] = (a[i][j] - math.fsum(l[i][k] * l[j][k] for k in range(j))) / l[j][j]
    return l


def _chol_solve(l, b):
    n = len(l)
    z = [0.0] * n
    for i in range(n):
        z[i] = (b[i] - math.fsum(l[i][k] * z[k] for k in range(i))) / l[i][i]
    x = [0.0] * n
    for i in reversed(range(n)):
        x[i] = (z[i] - math.fsum(l[k][i] * x[k] for k in range(i + 1, n))) / l[i][i]
    return x


def _logdet(l):
    return 2.0 * math.fsum(math.log(l[i][i]) for i in range(len(l)))


def _inverse(a):
    l = _cholesky(a)
    n = len(a)
    cols = [_chol_solve(l, [1.0 if i == j else 0.0 for i in range(n)]) for j in range(n)]
    return [list(r) for r in zip(*cols)], _logdet(l)


def _matmul(a, b):
    bt = list(zip(*b))
    return [[math.fsum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


class Pieces(NamedTuple):
    loglik: float
    score: list
    info: list
    b: list


def evaluate(y, x, vs, theta, method="reml"):
    """Log-likelihood, score, expected information and GLS estimate b at theta."""
    n, p = len(y), len(x[0])
    v = [[math.fsum(t * vj[i][k] for t, vj in zip(theta, vs)) for k in range(n)] for i in range(n)]
    vi, logdet_v = _inverse(v)
    vix = _matmul(vi, x)
    a = _matmul([list(c) for c in zip(*x)], vix)
    ai, logdet_a = _inverse(a)
    proj = [[vi[i][k] - math.fsum(vix[i][s] * math.fsum(ai[s][t] * vix[k][t] for t in range(p)) for s in range(p))
             for k in range(n)] for i in range(n)]
    py = [math.fsum(proj[i][k] * y[k] for k in range(n)) for i in range(n)]
    quad = math.fsum(a_ * b_ for a_, b_ in zip(y, py))
    xty_v = [math.fsum(vix[k][s] * y[k] for k in range(n)) for s in range(p)]
    b = [math.fsum(ai[s][t] * xty_v[t] for t in range(p)) for s in range(p)]
    if method == "reml":
        xtx = _matmul([list(c) for c in zip(*x)], x)
        logdet_xtx = _logdet(_cholesky(xtx))
        loglik = -0.5 * ((n - p) * math.log(2 * math.pi) + logdet_v + logdet_a - logdet_xtx + quad)
        m = proj
    elif method == "ml":
        loglik = -0.5 * (n * math.log(2 * math.pi) + logdet_v + quad)
        m = vi
    else:
        raise ValueError("method must be 'reml' or 'ml'")
    mv = [_matmul(m, vj) for vj in vs]
    score = []
    for j, vj in enumerate(vs):
        tr = math.fsum(mv[j][i][i] for i in range(n))
        vpy = [math.fsum(vj[i][k] * py[k] for k in range(n)) for i in range(n)]
        score.append(-0.5 * tr + 0.5 * math.fsum(a_ * b_ for a_, b_ in zip(py, vpy)))
    info = [[0.5 * math.fsum(mv[j][i][k] * mv[l][k][i] for i in range(n) for k in range(n))
             for l in range(len(vs))] for j in range(len(vs))]
    return Pieces(loglik, score, info, b)


def _solve_small(a, b):
    k = len(a)
    m = [list(row) + [b[i]] for i, row in enumerate(a)]
    for c in range(k):
        piv = max(range(c, k), key=lambda r: abs(m[r][c]))
        m[c], m[piv] = m[piv], m[c]
        if m[c][c] == 0.0:
            raise ValueError("singular information matrix")
        for r in range(c + 1, k):
            f = m[r][c] / m[c][c]
            m[r] = [u - f * w for u, w in zip(m[r], m[c])]
    out = [0.0] * k
    for i in reversed(range(k)):
        out[i] = (m[i][k] - math.fsum(m[i][j] * out[j] for j in range(i + 1, k))) / m[i][i]
    return out


class VarianceFit(NamedTuple):
    theta: list        # the estimates of theta_1, ..., theta_m
    b: list            # the GLS estimate of b at theta
    loglik: float      # the maximized (restricted) log-likelihood
    iterations: int
    at_boundary: list  # True for each theta_j that ended at 0
    score: list        # the score at the end; <= 0 for the components at 0


def fit_variance_components(y, x, vs, method="reml", theta0=None, tol=1e-10, max_iter=200):
    """Fisher scoring with projection onto theta >= 0 and step halving."""
    m = len(vs)
    if theta0 is None:
        mean = math.fsum(y) / len(y)
        s2 = math.fsum((v - mean) ** 2 for v in y) / max(1, len(y) - 1)
        theta0 = [s2 / m] * m
    theta = [max(float(t), FLOOR) for t in theta0]  # @line L1
    cur = evaluate(y, x, vs, theta, method)  # @line L2
    for it in range(1, max_iter + 1):  # @line L3
        # Active set: a component at 0 whose step points below 0 stays at 0, and the rest is solved without it.
        free = list(range(m))  # @line L4
        while True:
            sub = _solve_small([[cur.info[i][j] for j in free] for i in free], [cur.score[i] for i in free]) if free else []  # @line L5
            step = [0.0] * m
            for i, s in zip(free, sub):
                step[i] = s
            stuck = [j for j in free if theta[j] == 0.0 and step[j] < 0.0]  # @line L6
            if not stuck:
                break
            free = [j for j in free if j not in stuck]  # @line L6
        lam = 1.0  # @line L7
        while True:
            new = [max(t + lam * s, 0.0) for t, s in zip(theta, step)]  # @line L8
            new[-1] = max(new[-1], FLOOR)  # @line L8
            try:
                nxt = evaluate(y, x, vs, new, method)  # @line L9
                if nxt.loglik >= cur.loglik - 1e-12 * abs(cur.loglik):  # @line L9
                    break
            except ValueError:
                pass
            lam /= 2.0  # @line L10
            if lam < 1e-8:  # @line L10
                new, nxt = theta, cur
                break
        change = max(abs(a - b) for a, b in zip(new, theta))
        theta, cur = new, nxt  # @line L11
        if change <= tol * (1.0 + max(abs(t) for t in theta)):  # @line L12
            break
    at_zero = [t == 0.0 for t in theta]
    return VarianceFit(theta, cur.b, cur.loglik, it, at_zero, cur.score)  # @line L13


def one_way_design(groups):
    """y, X = 1 and the matrices Z Z^T and I for a one-way random effects layout."""
    y, label = [], []
    for g, values in enumerate(groups):
        for v in values:
            y.append(float(v))
            label.append(g)
    n = len(y)
    zzt = [[1.0 if label[i] == label[k] else 0.0 for k in range(n)] for i in range(n)]
    eye = [[1.0 if i == k else 0.0 for k in range(n)] for i in range(n)]
    return y, [[1.0] for _ in range(n)], [zzt, eye]


def anova_one_way(groups):
    """The ANOVA (method of moments) estimates (sigma_u^2, sigma_e^2) for a balanced one-way layout."""
    a, m = len(groups), len(groups[0])
    if any(len(g) != m for g in groups):
        raise ValueError("the layout is not balanced")
    means = [math.fsum(g) / m for g in groups]
    grand = math.fsum(means) / a
    msb = m * math.fsum((mu - grand) ** 2 for mu in means) / (a - 1)
    msw = math.fsum((v - mu) ** 2 for g, mu in zip(groups, means) for v in g) / (a * (m - 1))
    return (msb - msw) / m, msw
test_restricted_maximum_likelihood.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/restricted-maximum-likelihood/. The authors are listed in prov/6YVPGK.jsonl.

import math
import random

import pytest

from restricted_maximum_likelihood import (
    anova_one_way, evaluate, fit_variance_components, one_way_design,
)

GROUPS = [[10, 12, 14], [15, 16, 17], [18, 20, 22]]


def test_one_sample_reml_uses_divisor_n_minus_1():
    rng = random.Random(20261114)
    for n in (2, 3, 5, 9):
        y = [rng.gauss(3.0, 2.0) for _ in range(n)]
        x = [[1.0] for _ in range(n)]
        eye = [[1.0 if i == k else 0.0 for k in range(n)] for i in range(n)]
        mean = math.fsum(y) / n
        ss = math.fsum((v - mean) ** 2 for v in y)
        reml = fit_variance_components(y, x, [eye], "reml")
        ml = fit_variance_components(y, x, [eye], "ml")
        assert math.isclose(reml.theta[0], ss / (n - 1), rel_tol=1e-9)
        assert math.isclose(ml.theta[0], ss / n, rel_tol=1e-9)
        assert math.isclose(reml.b[0], mean, rel_tol=1e-12)


def test_balanced_one_way_example():
    y, x, vs = one_way_design(GROUPS)
    reml = fit_variance_components(y, x, vs, "reml")
    assert math.isclose(reml.theta[0], 15.0, rel_tol=1e-8)
    assert math.isclose(reml.theta[1], 3.0, rel_tol=1e-8)
    assert reml.at_boundary == [False, False]
    assert all(abs(s) < 1e-7 for s in reml.score)
    ml = fit_variance_components(y, x, vs, "ml")
    assert math.isclose(ml.theta[0], 29.0 / 3.0, rel_tol=1e-8)
    assert math.isclose(ml.theta[1], 3.0, rel_tol=1e-8)
    assert anova_one_way(GROUPS) == (15.0, 3.0)


def test_reml_equals_anova_or_the_boundary_solution():
    rng = random.Random(7)
    seen_boundary = seen_inside = 0
    for _ in range(16):
        a, m = 4, 3
        su = rng.choice([0.0, 0.3, 2.0])
        groups = []
        for _ in range(a):
            u = rng.gauss(0.0, math.sqrt(su))
            groups.append([5.0 + u + rng.gauss(0.0, 1.0) for _ in range(m)])
        y, x, vs = one_way_design(groups)
        fit = fit_variance_components(y, x, vs, "reml")
        su_hat, se_hat = anova_one_way(groups)
        if su_hat > 0:
            seen_inside += 1
            assert math.isclose(fit.theta[0], su_hat, rel_tol=1e-7, abs_tol=1e-9)
            assert math.isclose(fit.theta[1], se_hat, rel_tol=1e-7)
        else:
            seen_boundary += 1
            mean = math.fsum(y) / len(y)
            sst = math.fsum((v - mean) ** 2 for v in y)
            assert fit.theta[0] == 0.0 and fit.at_boundary[0]
            assert math.isclose(fit.theta[1], sst / (a * m - 1), rel_tol=1e-8)
            assert fit.score[0] <= 1e-9  # the KKT condition at theta_u = 0
    assert seen_boundary > 0 and seen_inside > 0


def test_restricted_likelihood_is_the_likelihood_of_error_contrasts():
    # Helmert contrasts K (n x (n - 1)) satisfy K^T 1 = 0; then l_K = l_R - (1/2) log|K^T K|.
    y, x, vs = one_way_design(GROUPS)
    n = len(y)
    k = [[(1.0 if i < c + 1 else (-(c + 1.0) if i == c + 1 else 0.0)) for c in range(n - 1)] for i in range(n)]
    theta = [4.0, 2.0]
    v = [[theta[0] * vs[0][i][j] + theta[1] * vs[1][i][j] for j in range(n)] for i in range(n)]
    ktvk = [[math.fsum(k[i][a] * v[i][j] * k[j][b] for i in range(n) for j in range(n)) for b in range(n - 1)] for a in range(n - 1)]
    kty = [math.fsum(k[i][a] * y[i] for i in range(n)) for a in range(n - 1)]
    ktk = [[math.fsum(k[i][a] * k[i][b] for i in range(n)) for b in range(n - 1)] for a in range(n - 1)]

    def logdet_and_solve(a, b):
        size = len(a)
        m = [row[:] + [b[i]] for i, row in enumerate(a)]
        logdet = 0.0
        for c in range(size):
            logdet += math.log(m[c][c])
            for r in range(c + 1, size):
                f = m[r][c] / m[c][c]
                m[r] = [u - f * w for u, w in zip(m[r], m[c])]
        out = [0.0] * size
        for i in reversed(range(size)):
            out[i] = (m[i][size] - math.fsum(m[i][j] * out[j] for j in range(i + 1, size))) / m[i][i]
        return logdet, out

    ld, sol = logdet_and_solve(ktvk, kty)
    l_k = -0.5 * ((n - 1) * math.log(2 * math.pi) + ld + math.fsum(a * b for a, b in zip(kty, sol)))
    ld_ktk, _ = logdet_and_solve(ktk, [0.0] * (n - 1))
    assert math.isclose(l_k, evaluate(y, x, vs, theta).loglik - 0.5 * ld_ktk, rel_tol=1e-11)


def test_score_matches_a_numerical_derivative():
    y, x, vs = one_way_design(GROUPS)
    theta = [7.0, 2.5]
    for method in ("reml", "ml"):
        here = evaluate(y, x, vs, theta, method)
        for j in range(2):
            h = 1e-5
            up = list(theta)
            dn = list(theta)
            up[j] += h
            dn[j] -= h
            num = (evaluate(y, x, vs, up, method).loglik - evaluate(y, x, vs, dn, method).loglik) / (2 * h)
            assert math.isclose(here.score[j], num, rel_tol=1e-6, abs_tol=1e-8)


def test_bad_method():
    y, x, vs = one_way_design(GROUPS)
    with pytest.raises(ValueError):
        evaluate(y, x, vs, [1.0, 1.0], "mom")
    with pytest.raises(ValueError):
        anova_one_way([[1.0, 2.0], [3.0]])

History

W. A. Thompson (1962) maximized the likelihood of the part of the data that is free of the fixed effects in balanced designs, and set negative estimates to 0. Patterson and Thompson (1971) gave the method for any design with unequal block sizes, with its score equations and an iterative solution. Harville (1974) wrote the restricted likelihood in the determinant form used on this page and showed that it is a marginal likelihood with a flat prior on the fixed effects, and Harville (1977) reviewed ML and REML and their algorithms. EM for REML came with Laird and Ware (1982), Newton-Raphson with Lindstrom and Bates (1988), and the average information algorithm with Gilmour, Thompson and Cullis (1995). The lme4 package (Bates et al. 2015) made the profiled REML criterion with sparse Cholesky factors the common route in general software.

References

  1. H. D. Patterson and R. Thompson, Recovery of inter-block information when block sizes are unequal, Biometrika 58(3), 1971, pp. 545 to 554, The whole paper (the likelihood of the error contrasts, its score equations and their iterative solution)
  2. W. A. Thompson, The problem of negative estimates of variance components, Annals of Mathematical Statistics 33(1), 1962, pp. 273 to 289, The restricted likelihood for balanced designs and the estimates that replace a negative value by 0
  3. David A. Harville, Bayesian inference for variance components using only error contrasts, Biometrika 61(2), 1974, pp. 383 to 385, The whole paper (the restricted likelihood in determinant form and as the marginal likelihood with a flat prior on the fixed effects)
  4. David A. Harville, Maximum likelihood approaches to variance component estimation and to related problems, Journal of the American Statistical Association 72(358), 1977, pp. 320 to 338, The whole paper (ML and REML compared, their score equations, and Newton, scoring and EM algorithms)
  5. Nan M. Laird and James H. Ware, Random-effects models for longitudinal data, Biometrics 38(4), 1982, pp. 963 to 974, The EM algorithm for ML and REML estimates in the two-stage model
  6. Mary J. Lindstrom and Douglas M. Bates, Newton-Raphson and EM algorithms for linear mixed-effects models for repeated-measures data, Journal of the American Statistical Association 83(404), 1988, pp. 1014 to 1022, The whole paper (Newton-Raphson on the profiled ML and REML likelihoods compared with EM)
  7. Arthur R. Gilmour, Robin Thompson and Brian R. Cullis, Average information REML: an efficient algorithm for variance parameter estimation in linear mixed models, Biometrics 51(4), 1995, pp. 1440 to 1450, The whole paper (the average of the observed and expected information and its computation from the mixed model equations)
  8. Douglas Bates, Martin Mächler, Ben Bolker and Steve Walker, Fitting linear mixed-effects models using lme4, Journal of Statistical Software 67(1), 2015, pp. 1 to 48, Sections 3 and 4 (the profiled REML criterion from a sparse Cholesky factor and its optimization with bounds that allow a variance of 0)
  9. Steven G. Self and Kung-Yee Liang, Asymptotic properties of maximum likelihood estimators and likelihood ratio tests under nonstandard conditions, Journal of the American Statistical Association 82(398), 1987, pp. 605 to 610, The mixture of chi-squared laws when the true parameter is on the boundary
  10. Ciprian M. Crainiceanu and David Ruppert, Likelihood ratio tests in linear mixed models with one variance component, Journal of the Royal Statistical Society Series B 66(1), 2004, pp. 165 to 185, The whole paper (the exact null law of the restricted likelihood ratio and its mass at 0)
  11. Michael G. Kenward and James H. Roger, Small sample inference for fixed effects from restricted maximum likelihood, Biometrics 53(3), 1997, pp. 983 to 997, The whole paper (the covariance of the fixed effects after REML and the F approximation)
  12. Shayle R. Searle, George Casella and Charles E. McCulloch, Variance Components, Wiley, 1992, Chapter 6 (ML and REML) and Chapter 8 (computing ML and REML estimates)

Where this leads

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
  • a full proof of flops.worst
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example