Verification protocol
Verification requires distinguishing numerical agreement from evidence about an inferential procedure. Agreement between analytic and numerical derivatives concerns two ways of evaluating the same quantity under matched conditions. A coverage estimate from simulated samples concerns how often an interval procedure includes the true parameter, and has Monte Carlo uncertainty. The examples here help identify what each check can establish, so that a discrepancy is interpreted in relation to the calculation and the claim being checked.
D.1 Comparing analytic and numerical derivatives
Suppose $y_1,\ldots,y_n$ are independent observations from a normal distribution with mean $\mu$ and standard deviation $\sigma$. The function to minimize is the negative log likelihood, so its derivatives have the opposite sign from those of the log likelihood. The second coordinate is the log standard deviation (SD), $\lambda=\log\sigma$. Up to a constant independent of both parameters, the negative log likelihood is
\[F(\mu,\lambda)=n\lambda+\frac{1}{2}e^{-2\lambda}\sum_{i=1}^n(y_i-\mu)^2.\]The observations remain fixed. Each partial derivative varies one entry of $u=(\mu,\lambda)^\top$ with the other fixed. Both coordinates range over the real line. Moving $\lambda$ by $h$ multiplies $\sigma$ by $e^h$, so either sign of the increment gives a positive standard deviation.
Write $r_i=y_i-\mu$ and $S=\sum_i r_i^2$. Differentiating $S$ with respect to $\mu$ gives $-2\sum_i r_i$. The terms $n\log\sigma$ and $S/(2\sigma^2)$ contribute $n/\sigma$ and $-S/\sigma^3$ to the derivative with respect to $\sigma$. Since $d\sigma/d\lambda=\sigma$, multiplying their sum by $\sigma$ yields the second component of the gradient
\[g(u)=\begin{pmatrix}-\sum_i r_i/\sigma^2 \\ n-S/\sigma^2\end{pmatrix}.\]Start a fresh R session in the book directory and continue there unless a new session is specified. For the four stipulated observations below, nll() sums the log densities and reverses the sign. The evaluation points are $(0.4,\log 1.6)$, $(-0.2,\log 0.75)$ and the maximum likelihood estimate (MLE). Setting the two components to zero gives the sample mean and the variance $S/n$ evaluated at that mean. At each point, both $\mu$ and $\log\sigma$ can change slightly in either direction while $\sigma$ remains positive. The derivative along the unit vector $d=(0.6,-0.8)^\top$ is $g(u)^\top d$.
1
2
3
4
5
6
7
8
9
10
11
source("code/lib/differentiation.R")
data <- c(.1,1.3,-.5,2.4)
nll <- function(u) -sum(dnorm(data,u[1],exp(u[2]),log=TRUE))
at <- c(.4,log(1.6))
analytic <- function(u) {
E <- data-u[1]; v <- exp(2*u[2])
c(-sum(E)/v,length(E)-sum(E^2)/v)
}
points <- list(positive_variance_1=at,positive_variance_2=c(-.2,log(.75)),
MLE=c(mean(data),log(sqrt(mean((data-mean(data))^2)))))
direction <- c(.6,-.8)
The function analytic() implements the two gradient components, using E for the residual vector and v for the variance.
At each point, the calculation uses eight absolute steps from $10^{-1}$ through $10^{-8}$. For either coordinate, num_grad() takes the central difference of $F$ with step $h$ (Section 3.1). The R vector d stores those two partial derivatives. The R vector direction stores the mathematical direction $d$ for the simultaneous change in both coordinates evaluated by along. This separate calculation evaluates $[F(u+hd)-F(u-hd)]/(2h)$, which can detect a sign or ordering error when compared with the inner product.
The absolute column gives the magnitude of the difference between numerical and analytic derivatives in the same coordinate. The scaled column divides this by the larger derivative magnitude or one, whichever is larger. It equals the absolute error when both magnitudes are below one, and depends on the derivative units. The signed final column deliberately compares the numerical log-SD derivative with the analytic SD derivative, omitting their chain-rule factor.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
errors <- lapply(names(points),function(label) {
u <- points[[label]]
g <- analytic(u)
do.call(rbind,lapply(10^-(1:8),function(h) {
d <- num_grad(nll,u,step=h)$gradient
along <- (nll(u+h*direction)-nll(u-h*direction))/(2*h)
exact <- c(g,sum(g*direction))
approximation <- c(d,along)
data.frame(point=label,component=c("mean","log SD","direction"),step=h,
exact=exact,numerical=approximation,absolute=abs(approximation-exact),
scaled=abs(approximation-exact)/pmax(1,abs(exact),abs(approximation)),
numerical_log_sd_minus_analytic_sd_derivative=c(NA,d[2]-g[2]/exp(u[2]),NA))
}))
})
print(do.call(rbind,errors),row.names=FALSE)
The code prints all 72 combinations of three evaluation points, three components and eight steps. The following excerpt retains only the eight log SD rows at positive_variance_1, where $u=(0.4,\log 1.6)^\top$. Both portions show these same rows; the signed final column is paired with step to identify its entries. The mean and directional derivatives, the second point and the MLE remain part of the full calculation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
point component step exact numerical absolute scaled
positive_variance_1 log SD 1e-01 1.769531e+00 1.754632e+00 1.489956e-02 8.420060e-03
positive_variance_1 log SD 1e-02 1.769531e+00 1.769383e+00 1.487009e-04 8.403406e-05
positive_variance_1 log SD 1e-03 1.769531e+00 1.769530e+00 1.486980e-06 8.403242e-07
positive_variance_1 log SD 1e-04 1.769531e+00 1.769531e+00 1.486821e-08 8.402342e-09
positive_variance_1 log SD 1e-05 1.769531e+00 1.769531e+00 1.155633e-10 6.530732e-11
positive_variance_1 log SD 1e-06 1.769531e+00 1.769531e+00 2.674527e-11 1.511433e-11
positive_variance_1 log SD 1e-07 1.769531e+00 1.769531e+00 4.023548e-09 2.273793e-09
positive_variance_1 log SD 1e-08 1.769531e+00 1.769531e+00 6.175515e-08 3.489916e-08
step numerical_log_sd_minus_analytic_sd_derivative
1e-01 6.486747e-01
1e-02 6.634255e-01
1e-03 6.635727e-01
1e-04 6.635742e-01
1e-05 6.635742e-01
1e-06 6.635742e-01
1e-07 6.635742e-01
1e-08 6.635742e-01
For the log-SD derivative at positive_variance_1, the absolute error fell from $1.49\times10^{-2}$ at $h=10^{-1}$ to $1.49\times10^{-8}$ at $10^{-4}$. Over this range, dividing the step by ten removed about two decimal orders of error, as expected from the leading $h^2$ truncation term in a central difference. The error reached $2.7\times10^{-11}$ at $10^{-6}$ and rose to $6.2\times10^{-8}$ at $10^{-8}$. At small steps, the two function values agree in many digits. Subtracting them and dividing by a small number magnifies the effect of rounding.
The signed column numerical_log_sd_minus_analytic_sd_derivative compares different coordinates. At positive_variance_1, the squared residuals sum to $5.71$, so the analytic derivative with respect to log SD is $4-5.71/1.6^2=1.76953125$. At $h=10^{-3}$, its numerical approximation printed as $1.769530$, but the analytic derivative with respect to SD is $1.76953125/1.6=1.10595703125$. Subtracting the latter from the numerical derivative explains why the signed difference settles near $0.6635742$ as the approximation improves. At the MLE, the derivatives with respect to SD and to log SD both vanish in exact arithmetic. A check confined to the MLE could therefore miss the omitted chain-rule factor.
Evaluation error and Richardson extrapolation
The four-observation calculation evaluates the normal log density directly. In a model that requires numerical integration or an inner optimization, each evaluation of the negative log likelihood can itself have appreciable error. Suppose the two evaluation errors are $\delta_+$ and $\delta_-$, each bounded in magnitude by $\epsilon$. Their contribution to the derivative is $(\delta_+-\delta_-)/(2h)$, with magnitude at most $\epsilon/h$. Halving the step doubles this bound. If the bound is large relative to the accuracy needed for the derivative, tighten the integration or optimization tolerance at both perturbed points and compare several steps again.
Omitting step selects the Richardson extrapolation of num_grad() (Section 3.1). Here absolute measures error against the analytic derivative, while numDeriv_gap compares the two numerical implementations at the same point.
1
2
3
4
5
6
print(do.call(rbind,lapply(names(points),function(label) {
u <- points[[label]]
d <- num_grad(nll,u)$gradient
data.frame(point=label,component=c("mean","log SD"),exact=analytic(u),Richardson=d,
absolute=abs(d-analytic(u)),numDeriv_gap=abs(d-numDeriv::grad(nll,u)))
})),row.names=FALSE)
1
2
3
4
5
6
7
point component exact Richardson absolute numDeriv_gap
positive_variance_1 mean -6.640625e-01 -6.640625e-01 1.028844e-11 0
positive_variance_1 log SD 1.769531e+00 1.769531e+00 6.587442e-11 0
positive_variance_2 mean -7.288889e+00 -7.288889e+00 7.821663e-10 0
positive_variance_2 log SD -1.233778e+01 -1.233778e+01 2.008278e-10 0
MLE mean -1.780809e-16 -1.898730e-15 1.720649e-15 0
MLE log SD 0.000000e+00 -8.099190e-11 8.099190e-11 0
All six implementation differences were zero. The book’s num_grad() is adapted from numDeriv, as its source and attribution record specify. Their agreement checks the adaptation at these inputs. The separately derived analytic gradient supplies the check by a different calculation. That comparison gave absolute errors from $1.028844\times10^{-11}$ to $7.821663\times10^{-10}$ away from the optimum and below $8.1\times10^{-11}$ for both components at the MLE. For log SD at the first point, the fixed step $10^{-6}$ gave a smaller absolute error than the default, $2.674527\times10^{-11}$ against $6.587442\times10^{-11}$. For a component whose accuracy matters to a fit, compare several steps with its analytic derivative at a point where that derivative is appreciably different from zero. The numDeriv package provides numerical gradients by Richardson extrapolation.
D.2 Checking monotonicity of EM iterations
In a two-class normal mixture, each person contributes one observed response $y_i$. Class membership is unobserved. Each component mean is the expected response within that class, and its standard deviation measures within-class spread in response units. A mixing proportion gives the probability of belonging to the class before seeing the response; the two proportions sum to one.
To check a proposed expectation-maximization (EM) update, fix the responses and compute each person’s posterior class probabilities at the current parameters $\theta_0$. Use them to average the log joint density over the missing memberships at both $\theta_0$ and the candidate $\theta_1$. The change in expected complete-data log likelihood is $\Delta Q=Q(\theta_1\mid\theta_0)-Q(\theta_0\mid\theta_0)$. To obtain the observed-data log likelihood $\ell$ at either parameter vector, sum the two products of mixing proportion and component density for each person before taking the logarithm, then add across people. Since mix_nll() returns $-\ell$, subtract its candidate value from its old value to obtain $\Delta\ell=\ell(\theta_1)-\ell(\theta_0)$.
With an exact E step, the old posterior probabilities give a lower bound on $\ell$ that touches $\ell(\theta_0)$ at the starting point. The bound adds the entropy of those probabilities to $Q$. That entropy remains constant while the candidate varies, so raising $Q$ raises the bound by the same amount. This gives $\Delta\ell\geq\Delta Q$. A nonnegative change in $Q$ therefore guarantees a nonnegative change in $\ell$. If $Q$ falls, the sign of $\Delta\ell$ still has to be checked. For the two candidates below, the changes print to six decimal places. The calculation reports both rows and applies no tolerance to accept or reject a candidate.
For six stipulated responses treated as independent, compare two candidate updates from means $-2$ and $2$, standard deviations $0.2$ and mixing proportions $0.5$. For component $k$, let $\pi_k$ denote its mixing proportion and $f_k$ its normal density. Entry $(i,k)$ of e$weights is $w_{ik}^0$, the conditional probability of membership in class $k$ given $y_i$ under $\theta_0$. The quantity used to judge either candidate is
From the book directory, load the mixture functions and compute the E step once. For either matrix of class probabilities used here, m_step() maximizes the corresponding weighted complete-data log likelihood. One candidate uses the old posterior probabilities, and the other assigns probability one half to each class for every observation. These mean and variance updates require a positive class count and a positive resulting variance to define the normal component used here.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
source("code/lib/stability.R")
source("code/lib/em_models.R")
y <- c(-2,-2,-1.9,1.9,2,2)
old <- mix_pack(c(.5,.5),c(-2,2),c(.2,.2))
e <- mix_estep(old,y)
m_step <- function(w) {
count <- colSums(w)
means <- drop(crossprod(w,y))/count
centered <- outer(y,means,"-")
sds <- sqrt(colSums(w*centered^2)/count)
mix_pack(count/length(y),means,sds)
}
# Both updates maximize a weighted complete-data log likelihood function. The EM update
# uses the conditional class probabilities evaluated at the previous parameter estimates.
correct <- m_step(e$weights)
wrong <- m_step(matrix(.5,length(y),2L))
In m_step(), a column sum gives the expected class count, the sum of membership probabilities rather than a count of assigned people. Dividing the corresponding entry of crossprod(w,y) by that count gives the class mean. The weighted sum of squared deviations divided by the same count gives the variance.
Every call to mix_q() uses the same e, so both changes in $Q$ are averaged under the old posterior probabilities.
1
2
3
print(do.call(rbind,lapply(list(posterior_weights=correct,uniform_weights=wrong),
function(u) c(old_posterior_Q_change=mix_q(u,e,y)-mix_q(old,e,y),
observed_data_loglik_change=mix_nll(old,y)-mix_nll(u,y)))))
1
2
3
old_posterior_Q_change observed_data_loglik_change
posterior_weights 5.921115 5.921115
uniform_weights -16.466391 -12.307508
The EM candidate gained $5.921115$ in both columns to the reported precision. The uniform candidate lost $16.466391$ in $Q$ and $12.307508$ in observed-data log likelihood. mix_unpack() expresses the component means and standard deviations on their original scales.
1
2
print(rbind(posterior_weights=unlist(mix_unpack(correct)),
uniform_weights=unlist(mix_unpack(wrong))))
1
2
3
4
5
6
probability1 probability2 mean1 mean2 sd1 sd2 log_probability1
posterior_weights 0.5 0.5 -1.966667 1.966667 0.04714045 0.04714045 -0.6931472
uniform_weights 0.5 0.5 0.000000 0.000000 1.96723156 1.96723156 -0.6931472
log_probability2
posterior_weights -0.6931472
uniform_weights -0.6931472
Under the old posterior probabilities, the three negative observations accounted for nearly all of the first class’s expected count. Their mean, $(-2-2-1.9)/3$, gives the printed estimate of $-1.966667$. The new standard deviations of $0.04714045$ made the two groups even more distinct. To connect this separation to the first table, write each joint density as the observed-data density times the posterior class probability. Subtract the old log joint density from the candidate log joint density and average under the old probabilities. Rearrangement gives
\[\Delta\ell-\Delta Q =\sum_{i=1}^{6}\sum_{k=1}^{2}w_{ik}^0\log\frac{w_{ik}^0}{w_{ik}^1} =\sum_{i=1}^{6}D_{\mathrm{KL}}(w_i^0\Vert w_i^1),\]where $w_i^1$ is the candidate’s posterior vector for person $i$. Each Kullback-Leibler divergence is nonnegative and vanishes when that person’s two posterior distributions coincide. For the EM candidate, class membership was nearly certain for the same class before and after the update. For the uniform candidate, both means became zero and both standard deviations became $1.96723156$. With identical component densities and equal proportions, its posterior probabilities are exactly one half. For each person, moving from near certainty to equal probabilities contributes about $\log 2$ to the divergence. Across six people, this accounts for the gap of about $4.16$ between the changes. The displayed identity uses the actual conditional class probabilities and finite log densities. Replacing these probabilities by a simulation estimate adds uncertainty to the computed change.
A simulated E step averages over draws of the missing data conditional on the observations at the old parameters. For a fixed candidate, evaluate the complete-data log likelihood difference on each draw. If the $M$ draws are independent and $s_D$ is the sample standard deviation of their differences, the estimated Monte Carlo standard error is $s_D/\sqrt{M}$. A small negative estimated change relative to this error leaves its sign uncertain. More draws can reduce this uncertainty. Dependent draws require a variance estimate that accounts for serial dependence. If the candidate was selected using these same draws, assess its change with separate evaluation draws before interpreting this fixed-candidate standard error. If a fit changes quadrature rules between iterations, evaluate the observed-data log likelihood at both parameter vectors with the same sufficiently accurate rule before interpreting a small decrease.
An iteration trace records failed candidates, their starting parameters, update probabilities and both changes. Here posterior_weights used the conditional probabilities computed from old, and both increases support that step, without establishing convergence. For uniform_weights, the lower observed-data log likelihood identifies the failed step. Its decrease in $Q$ under the old posterior pinpoints the consequence of changing the class probabilities used for maximization. The mclust package provides EM estimation for normal mixtures.
D.3 Measuring simulation bias and interval coverage
How often would a confidence interval cover the mean of the lower-scoring class if a study sampled a new group of people each time? The MIX1 simulation generated 200 independent samples of 300 people, with one score per person. A person belonged to the lower-mean class with probability 0.4 and to the higher-mean class with probability 0.6. Within classes, scores were normally distributed with means 55 and 80, respectively, and standard deviation 6 in both. The fit used only the scores to estimate the class proportions, means and variances. The EM estimates supplied starting values for a Broyden-Fletcher-Goldfarb-Shanno (BFGS) minimization of the negative observed-data log likelihood. The nominal 95% Wald interval for the lower mean was the refitted estimate plus or minus $z_{0.975}$ times its observed-information standard error. This standard error estimates the repeated-sample standard deviation of the fitted mean. The constant $z_{0.975}$ is the 97.5th percentile of the standard normal distribution.
For usable sample $b$, write $e_b=\hat\mu_b-55$, so a negative error places its estimate below the true lower mean. Averaging the signed errors over $B$ usable samples estimates bias among the fits that meet the usability rule, $\bar e=\sum_b e_b/B$. Subtracting 55 from every estimate leaves their dispersion unchanged. For empirical variance, square the deviations from $\bar e$ and use divisor $B-1$. For mean squared error, square the deviations from zero and average over all $B$ usable samples. In the original score units, the two summaries are
\[s=\sqrt{\frac{\sum_b(e_b-\bar e)^2}{B-1}},\qquad \mathrm{RMSE}=\sqrt{\frac{\sum_b e_b^2}{B}}.\]For $B\ge 2$, the empirical standard deviation $s$ describes how much the estimates vary across samples. The root mean squared error (RMSE) also counts a systematic displacement from 55. For independent replications, the variance of their mean error is the variance of one error divided by $B$. Taking the square root gives $s/\sqrt B$ as the estimated Monte Carlo standard error for bias.
For interval coverage, first specify the event being counted. Among the $B$ samples with a usable interval, let $c$ count those whose lower and upper limits enclose 55, endpoints included. When $B>0$, the proportion $\hat p=c/B$ estimates the probability of covering 55 conditional on obtaining a usable interval. Let $A$ be the total number of samples assigned. Then $\hat q=c/A$ estimates the probability that the procedure both produces a usable interval and covers 55. A sample without an interval contributes zero to this second event. From the variance of a Bernoulli indicator, the estimated Monte Carlo standard error is $\sqrt{\hat p(1-\hat p)/B}$ for conditional coverage and $\sqrt{\hat q(1-\hat q)/A}$ for the all-sample proportion. At an estimated proportion of zero or one, this substituted standard-error formula gives zero; that does not establish zero Monte Carlo uncertainty about the population proportion.
The lower mean must represent the same class across replications. Interchanging the two class labels preserves the mixture density but would turn an estimate near 80 into a large apparent error if it were compared with 55. The study orders the EM means when constructing the starting vector for BFGS. Because the refit does not constrain that order, the study compares the two final mean coordinates and selects the smaller one for estimate. It takes the matching diagonal entry of the inverse observed information for the estimated variance. The field final_mean_coordinate records which coordinate was selected.
Factor loadings also need a common orientation before averaging. Two solutions with opposite signs for the same factor would otherwise cancel even if their loadings agreed in magnitude. If a component’s mixing proportion approaches zero, the observations give little information about its mean. At a mixing proportion of zero, its mean is unidentified. The study marks a row usable only if EM and the refit both recorded successful stopping, the observed information was finite and positive definite, the selected estimate was finite, and its standard error was positive and finite. A failed row still counts toward $A$.
Rerunning a fit with different starting values on the same scores can reveal computational variation, such as convergence to different local maxima. The scores themselves must vary to measure repeated-sample performance. Each replication identifier in MIX1 has its own random-number stream, used to draw new class memberships and new within-class score deviations. The study fits each new sample by the same procedure. Each row thus represents one sample of 300 people when estimating bias or coverage.
The replication records of the MIX1 study supply these quantities. From the book directory, read the replication records. The usable column selects rows for the signed errors and their coverage indicators. If there are no usable rows, the conditional proportion is undefined and the calculation stops. The full row count supplies the denominator for the fraction of assigned samples producing a usable interval that covers 55. The empirical standard deviation and the Monte Carlo standard error estimated for bias require at least two usable rows. Interpreting the full row count as $A$ also requires one retained record for every assigned replication, including failed fits.
1
2
3
4
5
6
7
8
9
10
11
12
rows <- read.csv("data/derived/ch04/replications.csv")
ok <- rows$usable
stopifnot(!anyNA(ok),all(is.finite(rows$estimate[ok])),!anyNA(rows$covered[ok]))
B <- sum(ok)
if(!B) stop(
"No usable replicate for bias or conditional coverage; inspect the saved reasons")
err <- rows$estimate[ok]-55
cover <- mean(rows$covered[ok])
print(c(assigned=nrow(rows),usable=B,failures=sum(!ok),bias=mean(err),sd=sd(err),
rmse=sqrt(mean(err^2)),bias_MCSE=sd(err)/sqrt(B),coverage=cover,
coverage_MCSE=sqrt(cover*(1-cover)/B),
fraction_assigned_with_documented_coverage=sum(rows$covered[ok])/nrow(rows)))
1
2
3
4
5
6
7
8
9
10
assigned usable
200.00000000 200.00000000
failures bias
0.00000000 -0.03682603
sd rmse
0.67460739 0.67392567
bias_MCSE coverage
0.04770195 0.95500000
coverage_MCSE fraction_assigned_with_documented_coverage
0.01465862 0.95500000
All 200 samples met the recorded usability rule. The empirical standard deviation was $0.67461$ score units and the RMSE was slightly smaller at $0.67393$. Expanding the squared errors about their mean gives $\mathrm{RMSE}^2=[(B-1)/B]s^2+\bar e^2$. The estimated bias was $-0.03683$ score units, less than one Monte Carlo standard error of $0.04770$ below zero. Of the 200 intervals, 191 contained 55, so both coverage proportions were $0.955$. The Monte Carlo standard error for this proportion was $0.01466$, or about 1.47 percentage points. The observed excess over the nominal 95% was half a percentage point. The first three estimates connect these aggregate measures to individual samples.
1
2
print(c(first_three=rows$estimate[1:3],
first_three_mean_error=mean(rows$estimate[1:3]-55)))
1
2
first_three1 first_three2 first_three3 first_three_mean_error
54.1795441 55.0864565 55.4138199 -0.1067265
The estimates printed as $54.1795441$, $55.0864565$ and $55.4138199$. Subtracting 55 from the stored values before averaging gave a mean error of $-0.1067265$ for these three samples. For the first interval, rows$se[1] gives a within-sample standard error of $0.6581089477$. Its limits are $54.1795441\pm1.959964(0.6581089477)$, approximately $[52.88967,55.46941]$. Because 55 lies between them, this sample contributes one to the 191 covering intervals. The rsimsum package provides bias and coverage estimates with Monte Carlo standard errors.
D.4 Comparing estimates with existing implementations
Suppose two programs fit a growth curve to the same people. Before comparing estimates, match the observations by person and occasion, including any exclusions for missing responses and any observation weights. The simulated GROWTH4 data represent 200 people with four responses each at times 0, 1, 2 and 3. All 800 responses enter each fit with unit weight. The fixed intercept and time slope describe the population line. Each person has a random deviation in both coefficients, and the two deviations may be correlated. The model assumes normal random effects and independent normal residuals, independent of those effects. The reference functions lme4::lmer() and nlme::lme() fit this model to the same long-format data, once by maximum likelihood (ML) and once by restricted maximum likelihood (REML). More generally, match parameter constraints and, for fits that use priors, the prior distributions as well.
Matching the model also requires putting the estimates in the same units. The same intercept and time columns in the fixed-effects design $X$ make each intercept refer to time zero and each slope to one unit of time. Let $G$ denote the covariance matrix of the two random effects and $\sigma^2$ the residual variance. The entry $G_{11}$ is the between-person variance in starting levels, in squared response units; $G_{22}$ is the variance in slopes, in squared response units per squared time unit. Their covariance $G_{21}$ is in squared response units per time unit. The residual variance describes responses around each person’s own line, in squared response units.
For person $i$, the random-effects design $Z_i$ also has intercept and time columns. The response covariance is $Z_iGZ_i^\top+\sigma^2 I_4$. If software reports $G/\sigma^2$, multiplying by the residual variance recovers $G$. Squaring a reported residual standard deviation gives that variance. With $N$ observations and a fixed-effects design of rank $p$, profiling the scale for a given relative covariance uses divisor $N$ for ML and $N-p$ for REML. An omitted normalizing constant shifts the reported log likelihood even when the fitted coefficients remain unchanged. In models requiring numerical integration, the integration rule and its accuracy also affect the reported likelihood.
The parameter spaces must also coincide for the model being compared. If a reference function allows only independent random effects, fix the intercept-slope covariance to zero in both fits and re-estimate the remaining parameters. Check whether a zero variance is admissible if an estimate reaches that boundary. Both reference functions here allow the intercept and slope to covary, so the four comparison rows below concern fits of the correlated model.
A comparison across parameterizations needs a quantity with the same statistical meaning. In a factor model, equivalent rotations can change the loadings while preserving the covariance they imply for the responses. For the growth model, G_gap is the largest absolute difference between corresponding entries of $G$ on its absolute scale. The prediction comparison requires one further match. For a single growth-model fit, blup() (Section 8.7) returns the predicted random effects in its random_effects matrix. Its two entries for person $i$ predict how far that person’s intercept and time slope depart from their population values. The package’s ranef() output supplies the same two deviations. The comparison matches its rows by person identifier, with intercept and slope in the same column order. Taking the largest absolute difference across all 400 matched entries gives prediction_gap. This maximum does not identify the person or coefficient responsible. A predicted response at a particular visit would also need the fixed coefficients and that visit’s time.
The comparison for GROWTH4 proceeds as follows. From the book directory, read the fitted models and the table comparing each book fit with the indicated package fit. The beta_gap column reports the largest absolute fixed-coefficient difference, and sigma2_gap is the absolute residual-variance difference. The signed nll_gap subtracts the package’s negative log likelihood from the book’s, with each evaluated at its own fitted parameters under the indicated ML or REML criterion.
1
2
3
own <- readRDS("data/derived/ch08/fits.rds")$routes
ref <- read.csv("data/derived/ch08/reference-comparison.csv")
print(ref)
1
2
3
4
5
criterion package beta_gap G_gap sigma2_gap prediction_gap nll_gap
1 ML lme4 2.273737e-13 1.498180e-05 2.720892e-06 1.516473e-05 -4.367394e-09
2 ML nlme 3.108624e-15 4.397037e-06 5.225867e-09 6.379094e-06 -4.286221e-09
3 REML lme4 8.548717e-14 3.823707e-05 7.687778e-06 4.887710e-05 -2.885781e-08
4 REML nlme 1.154632e-14 1.630954e-09 2.168837e-10 1.128654e-09 6.821210e-13
In the first row, the book’s negative ML log likelihood is $4.367394\times10^{-9}$ lower than that from lmer(). One further check would pass both fitted vectors to a single likelihood function, with the data and likelihood convention fixed. Any resulting difference would then reflect the change in parameter values under that common evaluation.
In the four rows, the largest absolute criterion difference was $2.885781\times10^{-8}$ and the largest random-effect prediction difference was $4.887710\times10^{-5}$, both for lme4 under REML. The next calculation subtracts the book’s fitted negative restricted log likelihood from its fitted negative ML log likelihood.
1
print(c(ML_minus_REML_native=own$ML_profile$value-own$REML_profile$value))
1
2
ML_minus_REML_native
-3.750237
The change in criterion can be isolated by fixing $G$ and $\sigma^2$ at their ML estimates. Let $V$ be the resulting marginal response covariance and use the generalized least squares estimate for the fixed effects. With $C=X^\top V^{-1}X$, both criteria have the same residual quadratic form and the same log determinant of $V$. The restricted criterion adds half the log determinant of $C$ and uses $N-p$ in its normalizing constant. At these covariance estimates, its excess over the ML criterion is therefore
\[\tfrac12\log\det C-\tfrac p2\log(2\pi),\qquad p=2.\]Pass the fitted ML values of $G$ and $\sigma^2$ to lmm_cluster_nll() with REML=TRUE. In half_log_det, summing the logarithms of the Cholesky diagonal entries gives the first term.
1
2
3
4
5
6
source("code/lib/lmm.R")
ml <- own$ML_profile
at_ml <- lmm_cluster_nll(ml$data,ml$G,ml$sigma2,REML=TRUE)
print(c(half_log_det=sum(log(diag(chol(at_ml$C)))),p_half_log_2pi=ml$data$p/2*log(2*pi),
REML_minus_ML_at_ML=at_ml$value-ml$value,
REML_lowered_by=at_ml$value-own$REML_profile$value))
1
2
half_log_det p_half_log_2pi REML_minus_ML_at_ML REML_lowered_by
5.590616758 1.837877066 3.752739691 0.002502978
The two terms printed as $5.590616758$ and $1.837877066$. Subtracting before rounding gave the printed adjustment of $3.752739691$. Minimizing the restricted criterion then lowered it by $0.002502978$. Hence ML minus REML at their separate estimates is $-(3.752739691-0.002502978)\approx-3.750237$. The change in definition accounts for nearly all of that difference. Agreement with lmer() or lme() is measured by the signed difference within the corresponding ML or REML row. The two references differ in what agreement can show (Section E.3). The book’s profiled likelihood is translated from internal routines of nlme (code/NOTICE.md), so agreement with lme() checks that translation. The comparison with lmer() uses a separately implemented fitting calculation. Agreement at these data and settings provides additional evidence, but common numerical dependencies and errors in the shared model specification can remain.
D.5 Reproducing results with fixed random seeds
To reproduce a stochastic calculation, record what was observed, what was generated, and where the generator started. Here the first experiment generates three standard normal values for each of three identifiers. The next starts a chain at zero with a standard normal target distribution. A third calculation fits the same simulated item-response matrix twice. The stream and chain examples used R 4.5.2 and parallel 4.5.2. Their three generator settings select L’Ecuyer-CMRG for uniform variates, Inversion for normal variates, and Rejection for sampling discrete uniform indices. That last setting concerns how R samples an index. The chain makes its own acceptance decision. With these settings, the integer 105005 supplied to set.seed() reconstructs the starting stream. Partway through the computation, .Random.seed contains a header followed by six state integers. Saving that entire vector allows the generator to resume at the position already reached.
What should agree on a second run? With the same inputs, generator state, implementation and numerical environment, the same operations in the same order should reproduce the returned values exactly. identical() compares the unrounded objects. Two estimates that print alike can still differ in digits hidden by the display. An exact match answers a question about replaying this calculation. To measure variation due to stochastic fitting, use the same observations and refit with independent streams. To study variation across samples, generate new observations for each replicate and apply the fitting procedure to each sample.
From the book directory, load the two files below. The stream allocator gives identifier 1 the initial state and uses parallel::nextRNGStream() to obtain the starting states for identifiers 2 and 3. Each call to short() restores the state indexed by its argument before drawing three normals. The second traversal visits identifiers 3, 2 and 1. Applying rev() to its completed list puts the results back in identifier order without drawing again.
1
2
3
4
5
6
7
source("code/lib/boundary_test.R");source("code/lib/mcmc.R")
RNGkind("L'Ecuyer-CMRG","Inversion","Rejection");set.seed(105005)
streams <- replicate_streams(3L,.Random.seed)
short <- function(id) { assign(".Random.seed",streams[[id]],envir=.GlobalEnv);rnorm(3) }
forward <- lapply(1:3,short); reverse <- rev(lapply(3:1,short))
print(data.frame(id=1:3,first_draw=vapply(forward,function(x)x[1],0.0),
same=vapply(1:3,function(i)identical(forward[[i]],reverse[[i]]),TRUE)))
1
2
3
4
id first_draw same
1 1 0.1886892 TRUE
2 2 -0.3822198 TRUE
3 3 -0.4341921 TRUE
The first value drawn for identifier 1 is 0.1886892, for identifier 2 it is −0.3822198, and for identifier 3 it is −0.4341921. Only the first value is printed. Each TRUE compares the entire vector of three draws for that identifier with its counterpart from the other traversal.
Resuming a Metropolis chain
Continue in the same session. Identifier 1 was visited last, so the chain begins at the position just after its third normal draw. From a current point $x$, the transition function proposes $x+Z$ with a fresh standard normal $Z$. It uses the two normal log densities and one uniform draw to decide whether to move. Rejection retains the current point. After five steps the saved object contains the point, iteration number and generator state. The call to resume_mcmc() restores them and takes four more steps. Restore the five-step generator state once more and call the transition function once on the saved point.
1
2
3
4
5
6
7
kernel <- function(x)mh_step(x,function(v)dnorm(v,log=TRUE),function(v)v+rnorm(1))
prefix <- mcmc(0,kernel,5L)
suffix <- resume_mcmc(prefix,kernel,4L)
assign(".Random.seed",prefix$rng_after,envir=.GlobalEnv)
one <- kernel(prefix$state)
print(c(first_retained_iteration=suffix$first_iteration,proposal=one$proposal,
resumed_proposal=suffix$diagnostics[[1]]$proposal,first_state=suffix$draws[[1]]))
1
2
first_retained_iteration proposal resumed_proposal first_state
6.000000 1.053634 1.053634 1.053634
1
2
stopifnot(identical(one$proposal, suffix$diagnostics[[1]]$proposal),
identical(one$state, suffix$draws[[1]]))
Iteration 6 is the first resumed step. Both proposals and the first retained point print as 1.053634. The two assertions check exact equality of the proposals and of the retained points at that step. To test an entire split run, start a separate experiment with seed 140312. Save the initial stream, run twelve steps, restore that stream and split the same calculation after step five.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
RNGkind("L'Ecuyer-CMRG","Inversion","Rejection");set.seed(140312)
kernel<-function(x) mh_step(x,function(z)dnorm(z,log=TRUE),function(z)z+rnorm(1))
initial_stream<-.Random.seed
whole<-mcmc(0,kernel,12L)
assign(".Random.seed",initial_stream,.GlobalEnv)
prefix<-mcmc(0,kernel,5L);suffix<-resume_mcmc(prefix,kernel,7L)
stopifnot(identical(whole$draws,c(prefix$draws,suffix$draws)),
identical(whole$diagnostics,c(prefix$diagnostics,suffix$diagnostics)),
identical(whole$rng_after,suffix$rng_after),
suffix$first_iteration==6L,suffix$iteration==12L)
write.csv(data.frame(step=1:12,proposal=vapply(whole$diagnostics,`[[`,0.0,"proposal"),
accept=vapply(whole$diagnostics,`[[`,TRUE,"accepted"),state=unlist(whole$draws),
split_state=unlist(c(prefix$draws,suffix$draws)),
end_rng_identical=identical(whole$rng_after,suffix$rng_after)),
row.names=FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
"step","proposal","accept","state","split_state","end_rng_identical"
1,1.58394436833608,FALSE,0,0,TRUE
2,-0.86884135977636,TRUE,-0.86884135977636,-0.86884135977636,TRUE
3,-1.8832217750917,FALSE,-0.86884135977636,-0.86884135977636,TRUE
4,1.09367057169625,FALSE,-0.86884135977636,-0.86884135977636,TRUE
5,-0.366489705817641,TRUE,-0.366489705817641,-0.366489705817641,TRUE
6,-0.550725761994403,TRUE,-0.550725761994403,-0.550725761994403,TRUE
7,-0.623135636008449,TRUE,-0.623135636008449,-0.623135636008449,TRUE
8,-0.743861547134101,TRUE,-0.743861547134101,-0.743861547134101,TRUE
9,-2.19140822899016,FALSE,-0.743861547134101,-0.743861547134101,TRUE
10,-1.90747204568716,TRUE,-1.90747204568716,-1.90747204568716,TRUE
11,-3.4680123854897,FALSE,-1.90747204568716,-1.90747204568716,TRUE
12,-1.05684237803012,TRUE,-1.05684237803012,-1.05684237803012,TRUE
The sixth state is now −0.550725762 to nine decimal places. At step nine both paths retain the eighth state when the proposal is rejected. The assertions cover every retained point, every diagnostic record and the generator state after step twelve. The last column repeats that single endpoint comparison. Starting at the saved point with a different stream would preserve the five steps already taken and allow a different continuation. This restart example uses a fixed proposal rule. Resuming an adaptive rule would also require its adjustment history or sufficient saved summaries; point, iteration and random-number state alone would not suffice.
Consuming an extra draw can shift subsequent draws on the same stream. Restoring a separate starting state for each identifier protects the other replicates from that change.
Replaying a fit with an internal seed
For a fit with an internal seed, locate the reset in the fitting function. In a fresh session in the book directory, use the recorded two-factor Metropolis-Hastings Robbins-Monro (MH-RM) setup with R 4.5.2, Mersenne-Twister, Inversion and Rejection. The reference environment included mirt 1.45.1. Both calls below use the book’s multidim_mhrm() on the same 500 examinees’ responses to twelve dichotomous items.
For item $j$, the conditional log odds of a response coded one are $d_j+a_{j1}z_{i1}+a_{j2}z_{i2}$. The two traits are independent standard normal variables, and item responses are independent given them. The intercept $d_j$ is the log odds at both traits zero; each loading changes the log odds per standard deviation of its trait with the other fixed. The first item’s second loading is fixed at zero; the free loadings start positive but can change sign. After constructing the starting parameters from the responses, the function calls set.seed(seed) with its default of 12345 before drawing.
1
2
3
4
5
6
7
8
9
10
.libPaths(c(".R-library", .libPaths()))
for (file in c("stability","result","line_search","quasi_newton",
"differentiation","dogleg","factored_secant",
"simulation","logit","integration","mcmc","stochastic_items","inference","multidim_items"))
source(paste0("code/lib/",file,".R"))
RNGkind("Mersenne-Twister","Inversion","Rejection")
data14 <- list(two = readRDS("data/source/ch14/IRT12-two.rds"))
mhrm2 <- multidim_mhrm(data14$two,2L)
again <- multidim_mhrm(data14$two,2L)
print(c(same_MHRM_estimate=identical(again$par_vec,mhrm2$par_vec)))
1
2
same_MHRM_estimate
TRUE
The result TRUE establishes exact equality of the two complete parameter vectors returned in par_vec for these inputs and settings. For replicates whose processing order can change, the parallel package supplies the separate stream starts used in the first example. The software versions and numerical environment remain part of the reproduction record.