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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- H. D. Patterson, Robin Thompson, 1971
Restricted maximum likelihood (REML), also called residual maximum likelihood, estimates the covariance parameters of a linear mixed model by maximizing the likelihood of error contrasts with . On this page is the vector of fixed-effect coefficients. The contrasts have mean 0 whatever is, so their likelihood depends on only. Plain maximum likelihood estimates and together and does not allow for the degrees of freedom that the estimate of 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 . After is found, is estimated by generalized least squares at . 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 ; a fixed-effects design () of rank ; symmetric positive semidefinite matrices () with , so that . For the one-way layout, and . The parameter space is and .
Output. A maximizer of the restricted log-likelihood over the parameter space, the GLS estimate at , the maximum value, the set of components with and the score there.
The criterion. With and ,
This is the log density of for any matrix with and . The ML criterion is , with already replaced by ; the difference is the term and in place of . The score and the expected information of are
For ML, replaces in both trace terms.
The algorithm
REML-FISHER-SCORING(y[1..n], X[1..n, 1..p], V_1, ..., V_k, θ⁰, tol, max_iter)- 1
θ ← θ⁰, each entry raised to a small positive floor - 2
(ℓ, s, I) ← restricted log-likelihood, score and information at θ - 3
for it ← 1 to max_iter - 4
F ← {1, ..., k} ▷ the free components - 5
δ_F ← solution of I[F, F] δ_F = s_F; δ_j ← 0 for j ∉ F - 6
if some j ∈ F has θ_j = 0 and δ_j < 0 then remove those j from F and go to L5 - 7
λ ← 1 - 8
θ' ← max(θ + λδ, 0) entry by entry; θ'_k ← max(θ'_k, floor) - 9
(ℓ', s', I') ← the same quantities at θ'; if ℓ' ≥ ℓ then go to L11 - 10
λ ← λ/2; if λ < 10⁻⁸ then θ' ← θ (no move) else go to L8 - 11
record the change max_j |θ'_j - θ_j|; (θ, ℓ, s, I) ← (θ', ℓ', s', I') - 12
if the change ≤ tol (1 + max_j θ_j) then leave the loop - 13
return θ, 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 stays positive definite. Each evaluation in lines L2 and L9 forms , its Cholesky factor, , and the products .
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 ; 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 tests do not apply to those components.
Example
Three data sets in the one-way layout , each with an intercept and . Balanced: . Unbalanced: . Near-null: . The start is the sample variance divided by 2 for each component, and .
| data | method | iterations | ||||
|---|---|---|---|---|---|---|
| balanced | REML | 15 | 3 | 16 | 2 | |
| balanced | ML | 3 | 16 | 2 | ||
| unbalanced | REML | 19.2418 | 4.9723 | 16.3693 | 9 | |
| unbalanced | ML | 12.4571 | 4.9413 | 16.3867 | 10 | |
| near-null | REML | 0 | 3.25 | 12.3333 | 3 | |
| near-null | ML | 0 | 2.8889 | 12.3333 | 3 |
In the balanced data the group means are 12, 16 and 20, so and . REML gives and , the unbiased ANOVA estimates. ML gives , 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 than ML.
In the near-null data the group means are 12, 13 and 12, so and the ANOVA estimate of is . REML stops at with , the pooled variance of all 9 values. The returned score for is (ML: ), which is at most 0, so the KKT condition holds and the point is the maximum on the boundary.
A test of in the balanced data compares the REML fit with the REML fit without the random effect, which has and . Both models have the same , so their restricted likelihoods are comparable. The statistic is . The null value is on the boundary, so the reference law for many groups is (Chernoff 1954; Self and Liang 1987), and the p-value is instead of the 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 of rank with , and , so the log density of is ; the criterion depends on only through its column space and not on . Second, the score and the expected information have the forms above. Third, with the REML estimate is , which is unbiased, and the ML estimate is ; for one normal sample () the REML estimate is the sample variance with divisor . Fourth, in the balanced one-way layout REML gives the ANOVA estimates when and otherwise, and the score of at that boundary point is at most 0. Fifth, the loops stop after at most 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: need not be concave in , 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, is of rank , is positive definite, , , and
The vector holds the fixed-effect coefficients. Two facts about are used: , and , by direct multiplication. Also , because and .
Lemma 1 (error contrasts). Let be of rank with . Then (a) , and (b) . So has log density , which is when .
Proof. is positive definite because has full column rank. The matrix is invertible: if , multiply by to get , so , and then gives . Let . Then and , and also and . So and agree on the columns of an invertible matrix, and . This is (a).
For (b) let , which is invertible by the same argument with . Since , is block diagonal and . Now
and the Schur complement of the upper block is by (a) and the fact . So . Also . Equating the two gives (b).
Finally and , so the log density of is . By (a) the quadratic form is , and by (b) the log determinant is .
Consequences. does not depend on . If is replaced by for an invertible matrix , then and are both multiplied by and does not change, so depends on only through its column space.
Lemma 2 (score and expected information). If , then , and .
Proof. Take with and write , , so that by Lemma 1. The rules and give
By Lemma 1(a), , so and . Since is linear in , differentiating again gives
With the expectation of the second term is , and the sum is , again by Lemma 1(a).
The ML criterion has the score and the information by the same rules; this is the "ml" branch of the implementation.
Theorem 1 (one variance: the divisor n - p). Let (, ) and . The REML estimate is , which is unbiased, and the ML estimate is . For one normal sample, and , so , the sample variance with divisor .
Proof. Here , so , and with , so . Hence
The function with has , negative for and positive for , so has its unique maximum at . With this is ; for ML, and the maximum is . Since and is a projection of rank , .
Theorem 2 (balanced one-way layout). Let for groups of size , , , , , . Let , and be the sums of squares between groups, within groups and in total, with and , and assume and . Then the maximizer of over , is
- and if ,
- and if .
For ML the same holds with in place of and in place of . In the second case the score of at the maximum is negative.
Proof. Let . is block diagonal with blocks , which have the eigenvalue on and on the directions orthogonal to . So , and
which is smallest at , so . Also and , so . Therefore, with the precisions and ,
For ML the same calculation without the terms gives . The constraint is , that is . So the problem is to maximize over the convex set .
is strictly concave and tends to as or in , so it has a maximum on , and the maximum is unique. Its unconstrained maximizer is , , by the argument for in Theorem 1 applied to each variable.
If , then , so is the maximum: and , and . For REML , which gives the first case.
If , then . Suppose the maximum had . Then it would be a local maximum of on an open set, so , and by strict concavity it would be the unconstrained maximizer, which is not in . So , which maximizes , so . Then and , which is for REML and for ML.
For the score, with fixed, so . At this is . Since is the weighted mean of and with weights and , exactly in the second case, and then .
So in the balanced layout , and the KKT condition (score at a component equal to 0) holds at the REML boundary point. With , has the law (proved on the linear mixed model page), so and .
Theorem 3 (termination, feasibility and monotonicity). Assume are positive semidefinite and . Then the algorithm stops after at most passes of the loop L3, with at most evaluations; every iterate has and the floor, so is positive definite; and the accepted values of never decrease, apart from the relative tolerance that the implementation allows for rounding.
Proof. Lines L5 and L6 repeat only when at least one index leaves , so they run at most times in one pass. In lines L8 to L10, takes the values and the loop ends at the latest when , after at most 28 evaluations, since . Line L3 runs at most times. Line L1 and line L8 set every entry to at least 0 and the last entry to at least the floor, so is a positive semidefinite matrix plus a positive multiple of , hence positive definite. A trial point is accepted in line L9 only if its is not below the current value, and otherwise line L10 keeps .
If the information matrix is positive definite and , the direction has , and for small no free component is clipped in line L8 (those at 0 in have ), 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 ; 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 ( flops), the products () and the traces of the information (), plus for . With evaluations the time is and the extra space 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 : they work with Henderson's equations of order 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 , 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 up, as the simulation below shows.
- Bayesian view. Integrating the normal likelihood over with a flat prior gives up to a constant (Harville 1974), so REML maximizes a marginal likelihood for .
- Boundary rates. In the balanced one-way layout with groups of size , the ML estimate of is 0 exactly when , more often than REML. With , and the exact probabilities of an estimate of 0 are for REML and for ML.
- Measured bias. In 2000 simulated balanced data sets with , and (seed 20261114, using the closed forms proved here), the mean of was 1.025 for REML, 0.775 for ML and 1.018 for the ANOVA estimate, which can be negative; the mean of 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 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 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 . For , , where 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 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 is not small compared with , where the ML bias is largest. Use the REML fit for the standard errors of 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 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 does not have the law of Wilks' theorem because the null value is on the boundary; use 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 .
- 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 .
- Plug-in standard errors. ignores the error in ; use the Kenward and Roger (1997) adjustment for small samples.
- Floating point. Forming and for large 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.
# 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
- 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)
- 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
- 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)
- 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)
- 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
- 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)
- 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)
- 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)
- 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
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 6YVPGK Edit this page History Report an error Markdown