Linear factor analysis
Two measurements may tend to be high or low together across people. If the variation specific to each measurement is independent, a common factor offers an explanation for their covariance. Their covariance does not by itself determine how much of either measurement’s variance reflects the common factor. The relationships with other measurements provide further evidence. Linear factor analysis uses these relationships to distinguish variation attributed to common factors from variation unique to each measurement, so that the strength of a measurement’s connection to a common factor can be assessed. The simulated sample FA6 runs through the chapter: the same likelihood is maximized by three routes, and the fitted model is then rotated and used to predict factor scores.
6.1 The common factor model, covariance structure, and identification
For one independently sampled person $i$, let $y_i$ be the column vector of $p$ responses and let $\mu$ contain their population means. The common factor model describes the deviations from those means by
\[y_i=\mu+\Lambda z_i+\epsilon_i.\]The $q$ entries of $z_i$ are the person’s common factors, with distribution $N_q(0,\Phi)$ and $q\times q$ covariance matrix $\Phi$. Its diagonal entries describe how much the factors vary across people, and its off-diagonal entries describe their covariation. The $p\times q$ loading matrix $\Lambda$ has one row $\lambda_j^\top$ for response $j$. Increasing factor $h$ by one unit with the others fixed changes the conditional mean of response $j$ by $\lambda_{jh}$ response units. Thus $\lambda_j^\top z_i$ is the common part of the deviation for response $j$, and $\mu_j$ is the conditional mean when all factors are zero.
The remaining deviation $\epsilon_{ij}$ is the unique factor for response $j$: the part not accounted for by the common factors. It can include variation specific to that response as well as measurement error; this model does not separate those two sources. The error vector $\epsilon_i$ is independent of $z_i$ and has distribution $N_p(0,\Psi)$, where $\Psi$ is a $p\times p$ diagonal covariance matrix. Conditional on a person’s factors, two responses depend on separate, independent errors. Across people, their conditional means can rise together because both depend on the same factor.
Both random terms have mean zero, so $E(y_i)=\mu$. To obtain the covariance, expand the outer product of $y_i-\mu$ and take expectations. The cross term $\Lambda E(z_i\epsilon_i^\top)$ and its transpose vanish by independence. The factor term contributes $\Lambda E(z_i z_i^\top)\Lambda^\top$, and the error term contributes $E(\epsilon_i\epsilon_i^\top)$. The sum of the independent normal vectors $\Lambda z_i$ and $\epsilon_i$ is normal, so the covariance calculation also specifies the marginal distribution
\[\Sigma=\operatorname{Var}(y_i)=\Lambda\Phi\Lambda^\top+\Psi,\qquad y_i\sim N_p(\mu,\Sigma).\]For distinct responses $j$ and $k$, the covariance is $\lambda_j^\top\Phi\lambda_k$. For response $j$ itself, the common variance $\lambda_j^\top\Phi\lambda_j$ and its unique variance, or uniqueness, $\psi_j=\Psi_{jj}$ add to give the total variance. The uniqueness is also the conditional variance of response $j$ at any given factor vector. It is measured in squared response units: increasing it with the loadings and factor covariance fixed increases that response’s variance while leaving its covariances with other responses unchanged. The model permits $\psi_j\ge 0$. The logarithmic parameterization used below requires $\psi_j>0$; it cannot represent zero at a finite parameter value.
Which loading values could these covariances identify? For the exploratory fit, the factors have unit variances and zero correlations, so $\Phi=I_q$. One factor unit is therefore one population standard deviation of that factor. The loadings still refer to the original response units; fixing the factor variances does not standardize the responses.
For any orthogonal $q\times q$ matrix $P$, the transformed loadings $\Lambda P^\top$ give the same common covariance because $P^\top P=I_q$. In the two-factor example, the first factor axis can be chosen along the first response’s loading vector. Its first loading is then positive and its second is zero. If the second loading row is linearly independent of the first, the sign of the second axis can be chosen to make the second response’s second loading positive. More generally, a full-rank leading $q\times q$ block can be made lower triangular with positive diagonal, fixing the orientation and signs for that loading matrix. The triangular constraint fixes $q(q-1)/2$ entries above the diagonal. With $p=6$ and $q=2$, this leaves eleven free loadings. Adding six unique variances gives 17 parameters for $p(p+1)/2=21$ distinct covariance entries, or four degrees of freedom. The six means are estimated separately. Fixing this rotation does not by itself establish that the loadings and unique variances are uniquely determined by the response covariance. The parameter count alone cannot establish that identification either.
Parameter layout and the simulated responses
To work with this model numerically, its parameters are arranged in a single vector and a sample of responses is generated from it. The R examples use the book directory as the working directory.
1
2
3
4
for (file in c("result", "differentiation", "line_search", "quasi_newton", "em",
"simulation", "dogleg", "lbfgsb")) {
source(paste0("code/lib/", file, ".R"))
}
fa_implied() takes the loadings, unique variances and factor covariance matrix and returns the implied response covariance.
1
2
3
4
5
6
7
8
9
10
11
12
fa_implied <- function(loadings, uniquenesses, Phi = diag(ncol(loadings))) {
p <- nrow(loadings)
q <- ncol(loadings)
stopifnot(is.matrix(loadings), length(uniquenesses) == p,
all(is.finite(c(loadings, uniquenesses, Phi))), all(uniquenesses >= 0),
identical(dim(Phi), c(q, q)), isSymmetric(Phi))
chol(Phi)
# The unique variances enter only on the diagonal of the response covariance.
Sigma <- loadings %*% Phi %*% t(loadings) + diag(uniquenesses, p)
chol(Sigma)
Sigma
}
The default Phi is the identity. A zero unique variance is allowed in this calculation when $\Phi$ and the resulting $\Sigma$ are positive definite, as checked by chol(). To store a fit with strictly positive unique variances and strictly positive diagonal loadings in the leading block, fa_layout() records the free row and column positions. fa_pack() uses these positions to put the parameters into one vector.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fa_layout <- function(p, q) {
stopifnot(q >= 1L, p > q, p == as.integer(p), q == as.integer(q))
# Each row of free is a loading position, in column order.
free <- which(row(matrix(0, p, q)) >= col(matrix(0, p, q)), arr.ind = TRUE)
list(p = p, q = q, free = free, anchor = free[, 1] == free[, 2])
}
fa_pack <- function(loadings, uniquenesses) {
layout <- fa_layout(nrow(loadings), ncol(loadings))
stopifnot(all(loadings[row(loadings) < col(loadings)] == 0),
length(uniquenesses) == layout$p, all(uniquenesses > 0))
values <- loadings[layout$free]
stopifnot(all(values[layout$anchor] > 0))
# Log only the diagonal loadings before appending the log unique variances.
values[layout$anchor] <- log(values[layout$anchor])
par <- c(values, log(uniquenesses))
stopifnot(all(is.finite(par)))
par
}
The first six rows of layout$free select loading column one. The next five select rows two through six of column two. Positions 1 and 7 of the packed vector therefore contain the logarithms of the positive diagonal loadings. The other free loadings enter directly, followed in positions 12 through 17 by the logarithms of the unique variances. Exponentiating the logged entries recovers the original loadings and variances. The logical vector layout$anchor marks those diagonal loading positions. These loadings are estimated on a log scale; they are not fixed at one as marker-variable loadings would be.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
fa_unpack <- function(par, p, q) {
layout <- fa_layout(p, q)
k <- nrow(layout$free)
stopifnot(length(par) == k + p, all(is.finite(par)))
values <- par[seq_len(k)]
values[layout$anchor] <- exp(values[layout$anchor])
uniquenesses <- exp(par[k + seq_len(p)])
stopifnot(all(is.finite(c(values, uniquenesses))), all(uniquenesses > 0),
all(values[layout$anchor] > 0))
# Fill the free positions in a zero matrix to restore the triangular constraint.
loadings <- matrix(0, p, q)
loadings[layout$free] <- values
list(loadings = loadings, uniquenesses = uniquenesses)
}
The list returned by fa_unpack() stores $\Lambda$ in loadings and the diagonal entries of $\Psi$ in uniquenesses. The exploratory model fixes $\Phi=I_q$ through the default argument of fa_implied(); layout$free describes where parameters belong, while the unpacked list contains their values. For example, fa_unpack() takes the exponential of par[1] and places it at row one, column one of loadings through layout$free. Row one, column two remains zero. Those two entries now form the first row that fa_implied() uses to calculate the first response’s covariances. In exact arithmetic, exponentiating a finite log uniqueness gives a strictly positive variance. In floating-point arithmetic the exponential can overflow or round to zero, so fa_unpack() checks the transformed entries for finiteness and positivity.
To generate FA6, the simulation draws two independent standard normal factors for each of 600 people. Each row of lambda_true specifies how those two factors enter one response. Multiplying a person’s row of factor values by t(lambda_true) gives the common parts of all six responses. The six entries of psi_true are variances, so their square roots scale the columns of independent standard normal errors.
1
2
3
4
5
6
7
8
9
10
11
12
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
set.seed(601)
lambda_true <- matrix(c(.8, 0, .2, .8, .7, .2, .1, .7, .6, .3, .3, .6), 6, 2,
byrow = TRUE)
psi_true <- c(.36, .36, .45, .45, .50, .50)
z_true <- matrix(rnorm(600 * 2), 600, 2)
# Each response has its own error standard deviation.
errors <- sweep(matrix(rnorm(600 * 6), 600, 6), 2, sqrt(psi_true), "*")
Y <- z_true %*% t(lambda_true) + errors
colnames(Y) <- paste0("y", 1:6)
FA6 <- list(observed = Y, truth = list(latent = z_true, loadings = lambda_true,
uniquenesses = psi_true, mean = rep(0, 6)))
FA6$observed contains the response matrix Y. Only the observed rows enter the sample means and covariances. The simulated factor values in FA6$truth$latent allow predictions to be checked against the values that produced the responses. The same data object is distributed in data/source/ch06/FA6.rds. The vector ybar estimates $\mu$ by the column means $\bar y$. Subtracting each column mean and dividing the matrix of cross products by $n=600$ gives the sample covariance for the normal likelihood,
1
2
3
4
5
ybar <- colMeans(Y)
centered <- sweep(Y, 2, ybar)
S <- crossprod(centered) / nrow(Y)
Sigma_true <- fa_implied(lambda_true, psi_true)
print(rbind(mean = ybar, variance = diag(S)))
1
2
3
y1 y2 y3 y4 y5 y6
mean 0.004525385 -0.0312663 -0.01902355 -0.05060648 0.02391298 -0.04249609
variance 0.980321458 0.9971108 0.96756385 0.99155687 0.89663742 0.90749427
The sample means ranged from $-0.051$ to $0.024$ around their generating value of zero. The diagonal of S gave sample variances from 0.897 to 0.997. At the generating loadings and unique variances, the corresponding population variances range from 0.95 to 1.04.
For the first pair of responses, the loading rows are $(0.8,0)$ and $(0.2,0.8)$. With independent unit-variance factors, their population covariance is $0.8\times0.2+0\times0.8=0.16$. The second factor contributes to the second response’s variance but has zero loading on the first. The unique errors also contribute zero to this covariance.
1
2
3
4
print(c(population_cov12 = Sigma_true[1, 2], sample_cov12 = S[1, 2],
maximum_moment_error = max(abs(S - Sigma_true)),
minimum_population_eigenvalue = min(eigen(Sigma_true, symmetric = TRUE)$values),
maximum_population_eigenvalue = max(eigen(Sigma_true, symmetric = TRUE)$values)))
1
2
3
4
population_cov12 sample_cov12 maximum_moment_error
0.16000000 0.12969097 0.05336258
minimum_population_eigenvalue maximum_population_eigenvalue
0.39647508 2.79233877
The mean product of the two centered response columns was 0.12969, about 0.030 below the population covariance. The simulation used exactly these loading values, but the average of the centered products varies from sample to sample. The largest absolute difference anywhere in the matrix was in the variance of the fifth response. Its population variance is $0.6^2+0.3^2+0.50=0.95$, and its sample variance was 0.89664, a difference of 0.05336 in absolute value.
The smallest and largest eigenvalues bound the variances of unit-length linear combinations of the responses. For any unit vector $a$, the linear combination $a^\top y_i$ has variance $a^\top\Sigma a$. As $a$ varies over unit vectors, this variance ranges from the smallest eigenvalue of $\Sigma$, 0.39648, to the largest, 2.79234. Every nonzero linear combination consequently has positive variance. Thus Sigma_true is positive definite and defines a nonsingular normal distribution for one person’s response vector before any parameters are fitted. The stats package provides maximum likelihood factor analysis.
6.2 The maximum likelihood discrepancy function and its derivatives
How much log likelihood is lost when the two-factor model has to account for all 21 distinct entries of the FA6 sample covariance? Each of the $n=600$ independent people contributes the marginal normal density of a vector of $p=6$ responses. For any positive definite model covariance $\Sigma$, the likelihood is maximized over the unrestricted mean vector at $\mu=\bar y$. Write $r_i=y_i-\bar y$ for the centered responses of person $i$. The quadratic term in that person’s log density is $-\tfrac12 r_i^\top\Sigma^{-1}r_i$. The scalar inside this term equals $\operatorname{tr}(\Sigma^{-1}r_i r_i^\top)$. Summing over people replaces the outer product inside the trace by $nS_n$. The normalizing constant and the log determinant each occur once per person, giving the log likelihood at the estimated mean,
All the information in the centered rows that enters this likelihood is now in $S_n$. Its divisor is $n$ because $nS_n$ must recover the sum of the $n$ outer products.
The saturated normal model allows all 21 covariance entries to vary subject to positive definiteness. When $S_n$ is positive definite, this model attains its maximum at $\Sigma=S_n$. The trace in its log likelihood then equals $\operatorname{tr}(I_p)=p$. The same constant $p\log(2\pi)$ appears in the factor model. It cancels when the factor model log likelihood is subtracted from the saturated log likelihood. Expressing the loss per person and multiplying by two gives the maximum likelihood discrepancy function
\[F(\Sigma)=\frac{2}{n}\{\ell(\bar y,S_n)-\ell(\bar y,\Sigma)\} =\log|\Sigma|+\operatorname{tr}(S_n\Sigma^{-1})-\log|S_n|-p.\]A covariance that reproduces $S_n$ has zero discrepancy. For these 600 people, a difference of one unit in $F$ corresponds to 300 units of negative log likelihood. Minimizing either quantity therefore gives the same fitted covariance.
How does $F$ change when the model covariance moves by a small symmetric increment $d\Sigma$? For the log determinant, the differential is $d\log\vert \Sigma\vert =\operatorname{tr}(\Sigma^{-1}d\Sigma)$. The trace term also depends on $\Sigma$ through its inverse. Differentiating $\Sigma\Sigma^{-1}=I_p$ gives $(d\Sigma)\Sigma^{-1}+\Sigma\,d(\Sigma^{-1})=0$. Multiplication on the left by $\Sigma^{-1}$ yields $d(\Sigma^{-1})=-\Sigma^{-1}(d\Sigma)\Sigma^{-1}$. The observed $S_n$ is fixed. Substituting this differential into $\operatorname{tr}(S_n\,d(\Sigma^{-1}))$ and moving the last matrix in the product to the front under the trace puts $d\Sigma$ on the right in both terms. Together they give
\[dF=\operatorname{tr}(A\,d\Sigma),\qquad A=\Sigma^{-1}-\Sigma^{-1}S_n\Sigma^{-1}.\]Both terms in $A$ are symmetric. At the saturated covariance they cancel, so the first-order change vanishes in every direction.
A change in one loading can alter several response covariances at once. With $\Phi=I_q$, differentiating $\Sigma=\Lambda\Lambda^\top+\Psi$ gives $d\Sigma=(d\Lambda)\Lambda^\top+\Lambda(d\Lambda)^\top+d\Psi$. In the trace for $dF$, each of the first two terms contributes $\operatorname{tr}[(A\Lambda)^\top d\Lambda]$ by symmetry of $A$. For the loading of response $j$ on factor $h$, the coefficient of $d\lambda_{jh}$ is therefore twice entry $(j,h)$ of $A\Lambda$. A change in $\psi_j$ affects only covariance entry $(j,j)$, with coefficient $A_{jj}$. In matrix and vector form, the derivatives on the original parameter scales are
\[\frac{\partial F}{\partial\Lambda}=2A\Lambda,\qquad \frac{\partial F}{\partial\psi}=\operatorname{diag}(A), \qquad \psi=(\psi_1,\ldots,\psi_p)^\top.\]The function used for fitting needs derivatives of the negative log likelihood in the 17 coordinates of par. Consider position 12, which stores $u=\log\psi_1$. Increasing $u$ changes the first unique variance at rate $d\psi_1/du=\psi_1$. Since $-\ell(\bar y,\Sigma)=-\ell(\bar y,S_n)+(n/2)F(\Sigma)$, the derivative at this position is $(n/2)A_{11}\psi_1$.
Evaluating the discrepancy and its gradient
In code, the calculation starts with fa_data(), which centers each column of Y and divides the cross products by the number of rows. If the input is already a covariance computed with divisor $d$, multiplication by $d/n$ converts it to the scale of $S_n$. For example, a covariance computed with divisor 599 is multiplied by $599/600$.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fa_data <- function(Y = NULL, covariance = NULL, n = NULL, divisor = NULL) {
if (!is.null(Y)) {
stopifnot(is.null(covariance), is.matrix(Y), all(is.finite(Y)), nrow(Y) > 1L)
n <- nrow(Y)
mean <- colMeans(Y)
covariance <- crossprod(sweep(Y, 2, mean)) / n
divisor <- n
} else {
stopifnot(is.matrix(covariance), length(n) == 1L, n > 1,
n == as.integer(n), length(divisor) == 1L, divisor > 0)
mean <- NULL
# Restore the centered cross products, then divide by the likelihood divisor.
covariance <- covariance * divisor / n
}
stopifnot(all(is.finite(covariance)), isSymmetric(covariance))
chol(covariance)
list(S = covariance, n = n, p = ncol(covariance), mean = mean,
Y = Y, input_divisor = divisor, divisor = n)
}
The returned S is the matrix whose positive definiteness chol() has checked. A singular sample covariance cannot be used by this implementation. For a proposed $\Sigma$, fa_criterion() computes the negative log likelihood, discrepancy and derivative matrix from the covariance and these data.
1
2
3
4
5
6
7
8
9
fa_criterion <- function(Sigma, data) {
R <- chol(Sigma)
inverse <- chol2inv(R)
logdet <- 2 * sum(log(diag(R)))
kernel <- logdet + sum(data$S * inverse)
list(nll = data$n / 2 * (data$p * log(2 * pi) + kernel),
discrepancy = kernel - 2 * sum(log(diag(chol(data$S)))) - data$p,
A = inverse - inverse %*% data$S %*% inverse)
}
For a proposed $\Sigma$, the upper triangular Cholesky factor $R$ satisfies $\Sigma=R^\top R$. Twice the sum of the logarithms of its diagonal entries gives $\log\vert \Sigma\vert $, and chol2inv(R) gives $\Sigma^{-1}$. In the trace, each entry of $S_n$ multiplies the corresponding transposed entry of $\Sigma^{-1}$. Symmetry makes that entry equal to the one in the same position, which explains sum(data$S * inverse). The final Cholesky factorization also requires the supplied or computed sample covariance to be positive definite.
The local name kernel denotes $\log\vert \Sigma\vert +\operatorname{tr}(S_n\Sigma^{-1})$, the covariance-dependent part of the criterion. The returned nll includes the normalizing constant, discrepancy gives twice the log likelihood loss per person, and A is the derivative of the discrepancy with respect to $\Sigma$, supplying the matrix for both parameter derivatives.
make_fa_objective() turns this covariance calculation into a function of the packed parameter vector and supplies its negative log likelihood gradient.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
make_fa_objective <- function(data, q) {
layout <- fa_layout(data$p, q)
evaluate <- function(par) {
natural <- fa_unpack(par, data$p, q)
values <- fa_criterion(fa_implied(natural$loadings, natural$uniquenesses), data)
loading_gradient <- 2 * values$A %*% natural$loadings
free_gradient <- loading_gradient[layout$free]
# Apply the chain rule to the positive diagonal loadings.
free_gradient[layout$anchor] <- free_gradient[layout$anchor] *
natural$loadings[layout$free][layout$anchor]
gradient <- data$n / 2 * c(free_gradient, diag(values$A) * natural$uniquenesses)
list(value = values$nll, gradient = gradient, natural = natural,
discrepancy = values$discrepancy)
}
fn <- function(par) tryCatch(evaluate(par)$value, error = function(e) Inf)
gr <- function(par) evaluate(par)$gradient
list(fn = fn, gr = gr, evaluate = evaluate, layout = layout, data = data, q = q)
}
fa6_data <- fa_data(Y)
objective <- make_fa_objective(fa6_data, 2)
truth_par <- fa_pack(lambda_true, psi_true)
make_fa_objective() unpacks each proposed vector before computing the criterion. The selection loading_gradient[layout$free] omits the fixed zero. The derivative with respect to each diagonal loading is multiplied by the loading itself, just as the derivative with respect to each unique variance is multiplied by that variance. The other free loadings enter directly.
At a point where these calculations succeed, gr returns the 17 derivatives in packing order. If an evaluation raises an error, fn returns Inf, so a proposal that raises an error cannot improve a finite negative log likelihood. This catches errors; it does not separately check the returned objective and gradient for finite values.
A central difference approximates a component of gr by changing one coordinate of par. For position 12, the two evaluations of fn use first unique variances $\psi_1 e^h$ and $\psi_1 e^{-h}$. The difference between the two negative log likelihoods, divided by $2h$, estimates the derivative with respect to $\log\psi_1$. The three test points use the generating parameters, an increase of 0.15 in every packed coordinate, and a change in the first unique variance alone to 0.005. The last value is in response-variance units and is logged by fa_pack(). check_grad() computes the scaled error defined in Section 3.1. The columns maximum_absolute and maximum_scaled give the largest absolute error and the largest scaled error across the 17 coordinates.
1
2
3
4
5
6
7
8
9
10
11
derivative_points <- list(generating = truth_par, perturbed = truth_par + .15,
small_uniqueness = fa_pack(lambda_true, c(.005, psi_true[-1])))
gradient_checks <- do.call(rbind, lapply(names(derivative_points), function(name) {
do.call(rbind, lapply(c(1e-3, 1e-4, 1e-5), function(step) {
result <- check_grad(objective$fn, objective$gr, derivative_points[[name]],
step = step)
data.frame(point = name, step = step, maximum_absolute = max(result$absolute_error),
maximum_scaled = max(result$scaled_error))
}))
}))
print(gradient_checks, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
point step maximum_absolute maximum_scaled
generating 1e-03 1.861874e-04 9.967344e-05
generating 1e-04 1.865157e-06 9.992541e-07
generating 1e-05 5.846860e-08 2.329335e-08
perturbed 1e-03 1.288919e-04 4.118593e-06
perturbed 1e-04 1.288442e-06 4.130726e-08
perturbed 1e-05 6.672608e-08 3.403376e-09
small_uniqueness 1e-03 1.260292e-03 9.835049e-06
small_uniqueness 1e-04 1.260823e-05 9.860399e-08
small_uniqueness 1e-05 1.527017e-07 8.901172e-09
Reducing the step from $10^{-3}$ to $10^{-4}$ reduced the maximum scaled error from $9.97\times10^{-5}$ to $9.99\times10^{-7}$ at the generating point, from $4.12\times10^{-6}$ to $4.13\times10^{-8}$ at the shifted point, and from $9.84\times10^{-6}$ to $9.86\times10^{-8}$ when the first unique variance was 0.005. A tenfold reduction in step gives this hundredfold improvement when the leading error is proportional to the square of the step. At $10^{-5}$ the three errors fell to $2.33\times10^{-8}$, $3.40\times10^{-9}$ and $8.90\times10^{-9}$. Subtraction of nearly equal values of the negative log likelihood function amplifies rounding error after division by the smaller step.
For a check on the likelihood itself, rowSums() computes one quadratic form per person from centered and the inverse of Sigma_true. Each row contributes half its quadratic form plus the normalizing terms to the negative log likelihood. A second check uses the sample covariance S as the proposed covariance.
1
2
3
4
5
raw_nll <- sum(nrow(Sigma_true) / 2 * log(2 * pi) +
sum(log(diag(chol(Sigma_true)))) +
rowSums((centered %*% chol2inv(chol(Sigma_true))) * centered) / 2)
print(c(raw_minus_covariance = raw_nll - objective$fn(truth_par),
saturated_discrepancy = fa_criterion(S, fa6_data)$discrepancy))
1
2
raw_minus_covariance saturated_discrepancy
-9.094947e-13 8.881784e-16
The row sum differed from the covariance-based negative log likelihood by $-9.09\times10^{-13}$. The saturated discrepancy was $8.88\times10^{-16}$, zero to rounding precision. To recover the value of fn at a proposed set of loadings and unique variances, add $300F$ to the saturated negative log likelihood. Maximum likelihood fitting of normal factor models is available in the stats package.
6.3 Joint optimization of loadings and unique variances
For the 600 people in FA6, which loadings and unique variances give the observed responses the highest normal likelihood? With two independent unit-variance factors, the loading matrix has six rows and two columns. Fixing the first response’s loading on the second factor at zero leaves eleven loadings to estimate. Each response also has its own unique variance. The joint fit varies these seventeen quantities together on their original scales. For example, its twelfth coordinate is the first unique variance itself. The reporting convention assigns a positive sign to each diagonal loading, one for each factor. The fixed zero is built into the loading matrix at every evaluation. The search allows either sign for each free loading, so the convention can be checked against the estimated matrix.
The sample covariance $S=S_n$ uses divisor $n=600$, and a proposed set of parameters implies $\Sigma=\Lambda\Lambda^\top+\Psi$. The function minimized in the joint fit is half the maximum likelihood discrepancy,
\[F_{\mathrm{joint}}=\frac{F}{2} =\frac12\left\{\log|\Sigma|+\operatorname{tr}(S\Sigma^{-1})-\log|S|-p\right\}.\]It equals zero at $\Sigma=S$. The negative log likelihood per person is $F_{\mathrm{joint}}$ plus the saturated negative log likelihood per person, a constant for these data. Thus a decrease in $F_{\mathrm{joint}}$ corresponds to an increase in log likelihood equal to $n$ times that decrease. To find the direction of change, let $A=\Sigma^{-1}-\Sigma^{-1}S\Sigma^{-1}$. In $dF_{\mathrm{joint}}=\tfrac12\operatorname{tr}(A\,d\Sigma)$, the two terms arising from $d(\Lambda\Lambda^\top)$ give equal contributions. Their sum gives the gradient with respect to the loadings, $A\Lambda$. Since $d\Psi$ is diagonal, the gradient for the unique variances is $\tfrac12\operatorname{diag}(A)$. These are derivatives with respect to the quantities the joint fit actually varies.
FABIN3 starting values
The search needs an initial value for each of the seventeen coordinates. The function fabin3_start() uses a preliminary one-factor calculation, the FABIN3 method from factor analysis by instrumental variables, to obtain one starting loading per response from the full sample covariance. Initially the first loading is one. This puts the preliminary factor in the units of response 1: one factor unit changes that response’s conditional mean by one unit. Its variance is estimated in this preliminary calculation. For response $i>1$, the four responses other than 1 and $i$ form the instrument set $J$. Under the preliminary one-factor assumptions, any covariance of response $i$ with a linear combination of those four comes through the common factor. The vector $b=S_{JJ}^{-1}s_{J1}$ gives the regression coefficients for predicting response 1 from those four. The covariance of response $i$ with that prediction is $s_{iJ}b$, and the covariance of response 1 with the prediction is $s_{1J}b$. Their ratio gives a preliminary loading relative to the first. Here the one-factor calculation supplies starting values for a two-factor fit; the final model does not assume that these ratios consistently estimate its two columns:
The function below implements this preliminary calculation and rescales its loadings to the unit-factor-variance convention used in the joint fit.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
fabin3_start <- function(s, std_lv = TRUE) {
n_var <- ncol(s)
# Response 1 is the reference indicator with loading one.
lambda <- c(1.0, numeric(n_var - 1))
# Each set of instruments excludes response 1 and the response being initialized.
iv_ratio <- function(i) {
rest <- setdiff(seq_len(n_var), c(i, 1L))
s_i_rest <- s[i, rest]; s_rest_1 <- s[rest, 1L]
x_i <- try(solve(s[rest, rest], s_rest_1), silent = TRUE)
if (inherits(x_i, "try-error")) sum(s_i_rest * s_rest_1) / sum(s_rest_1^2) else
sum(s_i_rest * x_i) / sum(s_rest_1 * x_i)
}
for (i in 2:n_var) lambda[i] <- iv_ratio(i)
# Bound the provisional loading ratios before estimating their common scale.
lower_psi <- s[1, 1] - (1 - 0.1) * s[1, 1]
bound <- sqrt(diag(s)[-1] / lower_psi)
lambda[-1] <- pmin(pmax(-bound, lambda[-1]), bound)
# Remove the provisional unique variances to estimate the factor variance.
l2 <- sum(lambda^2); d <- tcrossprod(lambda) / l2
implied <- d %*% s %*% d
theta <- solve(diag(n_var) - d^2, diag(s - implied))
s1 <- s - diag(theta)
psi <- sum(lambda * colSums(as.numeric(lambda) * s1)) / l2^2
if (std_lv) lambda <- lambda * sign(psi) * sqrt(abs(psi))
lambda
}
For $i=2$, rest selects responses 3 through 6. The solve gives x_i, and the two sums involving x_i give the numerator and denominator. If the solve fails, the calculation uses the column of covariances s_rest_1 as the weights. The function limits each preliminary ratio in magnitude to $\sqrt{s_{ii}/(0.1s_{11})}$.
To put the loadings on a unit-factor-variance scale, it forms the projection $D=aa^\top/(a^\top a)$, called d in the code. The provisional unique variances theta are chosen so that the diagonal of $D(S-\operatorname{diag}(\theta))D+\operatorname{diag}(\theta)$ equals the diagonal of $S$. Collecting the coefficients of $\theta$ gives the linear system in solve(), where d^2 squares the entries of $D$ individually. Subtracting diag(theta) from $S$ gives s1. The scalar called psi inside this function is the provisional factor variance, $v=a^\top\texttt{s1}\,a/(a^\top a)^2$. For the positive $v$ obtained here, multiplying $a$ by $\sqrt v$ puts its common variation into the loadings. If the provisional factor variance is negative, the code instead multiplies by sign(psi) * sqrt(abs(psi)). That operation still returns starting numbers, but it cannot convert a negative variance into the same valid unit-variance factor model.
Fitting the seventeen parameters together
The joint-fitting function uses these preliminary loadings to initialize both factors, adds starting unique variances, and minimizes the half-discrepancy over all seventeen original-scale parameters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
fa_joint <- function(data, q) {
layout <- fa_layout(data$p, q)
k <- nrow(layout$free)
start_lambda <- fabin3_start(data$S)
# A response gets the same starting loading in each of its free positions.
start <- c(start_lambda[layout$free[, 1]], (1.0 - 0.50) * diag(data$S))
logdet_S <- sum(log(diag(chol(data$S))^2))
# Build the candidate covariance from the 17 original-scale parameters.
unpack <- function(x) {
L <- matrix(0, data$p, q)
L[layout$free] <- x[seq_len(k)]
list(loadings = L, uniquenesses = x[k + seq_len(data$p)])
}
pieces <- function(x) {
natural <- unpack(x)
Sigma <- natural$loadings %*% t(natural$loadings) +
diag(natural$uniquenesses, data$p)
R <- tryCatch(chol(Sigma), error = function(e) NULL)
list(natural = natural, Sigma = Sigma, R = R)
}
# Evaluate the half-discrepancy and differentiate it on the same scale.
fn <- function(x) {
part <- pieces(x)
if (is.null(part$R)) return(Inf)
inverse <- chol2inv(part$R)
fx <- sum(log(diag(part$R)^2)) + sum(data$S * inverse) - logdet_S - data$p
if (is.finite(fx) && fx < 0) fx <- 0
0.5 * fx
}
gr <- function(x) {
part <- pieces(x)
inverse <- chol2inv(part$R)
A <- inverse - inverse %*% data$S %*% inverse
c((A %*% part$natural$loadings)[layout$free], diag(A) / 2)
}
# Scale the starting coordinates for the double-dogleg trust-region steps.
big <- abs(start) > 1.0
scale <- rep(1.0, length(start))
scale[big] <- abs(1.0 / start[big])
run <- dogleg_minimize(start, fn, gr, scale = scale, control = list(max_evals = 20000L,
max_iter = 10000L, x_tol = 1.5e-8, false_tol = 2.2e-14, step_lo = 1.0, step_hi = 1.0,
rel_tol = 1e-10, abs_tol = 10 * .Machine$double.eps))
natural <- unpack(run$par)
list(loadings = natural$loadings, uniquenesses = natural$uniquenesses, start = start,
run = run, fn = fn, gr = gr)
}
Inside fa_joint(), a single call to fabin3_start(data$S) supplies both columns of the starting matrix. For response 2, multiplying the relative loading of 0.46334 by 0.79611 gives a starting loading of 0.36887. The row index in layout$free places 0.36887 in both free positions for that response. Response 1 contributes only to column one. Half the six sample variances complete the vector, starting with $0.980321458/2=0.49016$ for the first uniqueness.
For each trial vector, unpack() fills the free positions in a zero matrix and takes the final six entries as variances. pieces() forms the implied covariance and tries its Cholesky factorization. A failed factorization gives fn an infinite value. Individual loadings and unique variances have no sign bounds during the search, so even a negative trial uniqueness can pass this test if the response covariance is positive definite. Such a trial covariance defines a normal distribution for the responses, but its negative uniqueness cannot be the variance of a unique factor in the stated model. The discrepancy is nonnegative in exact arithmetic. The implementation replaces a finite negative value by zero before halving it. The function gr selects the eleven free entries of $A\Lambda$ and appends the six variance derivatives.
The setup code loads the double-dogleg trust-region function dogleg_minimize() from code/lib/dogleg.R. It uses a quadratic approximation, formed from the gradient and an updated approximation to the second derivatives, to predict how much a proposed step will reduce the half-discrepancy. A starting coordinate with magnitude above one receives the reciprocal of its magnitude as its scale. All seventeen starting magnitudes are below one in this example, so their scales are one. The call allows 10,000 iterations and 20,000 function evaluations. Its relative function tolerance is $10^{-10}$, its relative parameter tolerance is $1.5\times10^{-8}$, and its absolute function tolerance is ten times machine epsilon. The false-convergence tolerance is $2.2\times10^{-14}$, and the controls for the initial and later step bounds are both one.
For the two-factor fit to fa6_data, the first print reports the minimized half-discrepancy as F. The log likelihood in the same line comes from evaluating fa_criterion() at the covariance reconstructed from the returned loadings and unique variances.
1
2
3
4
joint_fit <- fa_joint(fa6_data, 2)
print(c(F = joint_fit$run$objective, iterations = joint_fit$run$iterations,
joint_fit$run$evaluations, logLik = -fa_criterion(fa_implied(joint_fit$loadings,
joint_fit$uniquenesses), fa6_data)$nll))
1
2
F iterations function gradient logLik
1.000168e-03 2.200000e+01 2.400000e+01 2.300000e+01 -4.505966e+03
dogleg_minimize() reported $F_{\mathrm{joint}}=0.001000168$ and a log likelihood of $-4505.966$ after 22 iterations, with 24 function evaluations and 23 gradient evaluations. At this value of the half-discrepancy the log likelihood is about $600\times0.001000168=0.6001$ below the saturated log likelihood. The message stored in joint_fit$run$message was relative convergence (4). Its quadratic approximation predicted too little further reduction relative to the current function value to continue under this criterion. The parameter estimates below show whether the returned unique variances and the two diagonal loadings are strictly positive. The stopping message alone does not establish that all free-parameter derivatives vanish.
1
print(cbind(joint_fit$loadings, uniqueness = joint_fit$uniquenesses))
1
2
3
4
5
6
7
uniqueness
[1,] 0.80469524 0.0000000 0.3327870
[2,] 0.16621069 0.7438543 0.4161654
[3,] 0.69245010 0.2436853 0.4286942
[4,] 0.07885626 0.6949250 0.5024178
[5,] 0.54725158 0.3001934 0.5070371
[6,] 0.23744010 0.6331387 0.4502519
The first row has its fixed zero in column two. The diagonal loadings, 0.80470 and 0.74385, have the chosen positive signs. With factor one fixed, a one-standard-deviation increase in factor two raises the fitted conditional mean of response 2 by 0.74385 response units. All six unique variances are positive. The two responses had generating loadings of 0.8 on their respective factors. The first diagonal estimate exceeds its generating value by about 0.005, and the second falls below its generating value by about 0.056.
For response 1, the estimated common variance is $0.80469524^2=0.64753$ to five decimal places. Adding its unique variance of 0.3327870 gives 0.98032, its sample variance. The largest absolute difference across all six variances reconstructed from the printed digits is $1.87\times10^{-7}$. Why should all six agree? At an exact stationary point with strictly positive unique variances and nonzero diagonal loadings, all free-parameter derivatives vanish. The six uniqueness equations then give $\operatorname{diag}(A)=0$, and $G=A\Lambda$ vanishes at every free loading position. The fixed position $(1,2)$ also has $G_{12}=0$ here. Indeed, $\Lambda^\top G$ is symmetric. Its $(2,1)$ entry is zero because the first column of $G$ is zero, and its $(1,2)$ entry reduces to $\lambda_{11}G_{12}$. Since $\lambda_{11}>0$, this proves $A\Lambda=0$. Its transpose gives $\Lambda^\top A=0$ as well. Multiplying $A$ on the left and right by $\Sigma$ therefore gives
\[\Sigma-S=\Sigma A\Sigma =(\Lambda\Lambda^\top+\Psi)A(\Lambda\Lambda^\top+\Psi)=\Psi A\Psi.\]The $j$th diagonal difference is $\psi_j^2 A_{jj}=0$. Off the diagonal, the fitted covariance of responses 1 and 2 is $0.80469524\times0.16621069=0.13375$ after rounding, compared with 0.12969 in the sample and 0.16 in the generating model. The likelihood equations reproduce the individual variances while allowing differences in the covariances between responses. The smallest estimated unique variance as a fraction of its sample variance is $0.3327870/0.980321458=0.339$ for response 1. Even for this response about a third of its variance is unique, well above the zero boundary. The supplied fabin3_start() is adapted from the FABIN3 start of the lavaan package (code/NOTICE.md), in which joint maximum likelihood estimation of this factor model is also available.
6.4 Concentrating the likelihood with an eigendecomposition
Suppose the six unique variances in FA6 were known. Would finding the eleven free loadings still require a numerical search? Let $S=S_n$ be the sample covariance and $\Sigma=\Lambda\Lambda^\top+\Psi$ the model covariance for a fixed positive diagonal matrix $\Psi$. Dividing each centered response by its unique standard deviation gives a sample covariance $B=\Psi^{-1/2}S\Psi^{-1/2}$. On this scale, each unique error has variance one. This change of units preserves the normal discrepancy $F$. The model and sample log determinants both change by $-\log\vert \Psi\vert $, and cyclically permuting the matrices inside the trace gives $\operatorname{tr}(B C^{-1})=\operatorname{tr}(S\Sigma^{-1})$, where $C=\Psi^{-1/2}\Sigma\Psi^{-1/2}$. The remaining question is which directions of variation in $B$ the common factors should explain.
In the rescaled covariance $C=I+WW^\top$, the columns of $W=\Psi^{-1/2}\Lambda$ describe common variation relative to the unique errors. At most $q$ eigenvalues of $C$ can exceed one. For a unit direction $u$ with model eigenvalue $t>1$, the inverse covariance gives that direction weight $1/t$. Relative to $C=I$, this reduces the trace term by $(1-1/t)u^\top B u$. For one direction, $u^\top B u$ is largest on a leading eigenvector of $B$. With several orthogonal directions, the trace is minimized by pairing the largest weights with the leading sample eigenvalues. For two weights $w_k=1-1/t_k$ with $w_1>w_2$ and sample eigenvalues $e_1>e_2$, the larger-to-larger pairing reduces the trace by an additional $(w_1-w_2)(e_1-e_2)$ compared with the reversed pairing. The log determinant depends only on the model eigenvalues, so this choice of directions minimizes the discrepancy. For a sample eigenvalue $e>0$ paired with a model eigenvalue $t\ge 1$, the contribution of that direction to the discrepancy and its derivative are
\[\log t+\frac{e}{t}-\log e-1,\qquad \frac{d}{dt}\left(\log t+\frac{e}{t}\right)=\frac{t-e}{t^2}.\]The minimum is at $t=\max(e,1)$. For $e>1$, matching $t$ to $e$ removes the entire discrepancy $e-\log e-1$ that this direction would have at $t=1$. This gain increases with $e$, which explains why the first $q$ directions are selected. Write $U_q$ for their eigenvectors in columns and $\Gamma_q$ for the diagonal matrix of their eigenvalues. A minimizing loading matrix in the units of $S$ is
\[\Lambda=\Psi^{1/2}U_q(\Gamma_q-I)_+^{1/2}.\]The positive part replaces a negative diagonal entry by zero. The following function computes this minimizing loading matrix for fixed unique variances.
1
2
3
4
5
6
7
8
9
fa_concentrated_loadings <- function(Psi, S, q) {
# Eigenvectors of the uniqueness-scaled matrix Psi^(-1/2) S Psi^(-1/2).
root <- sqrt(Psi)
ev <- eigen(diag(1 / root) %*% S %*% diag(1 / root), symmetric = TRUE)
# A selected direction gets the common variance above one.
stretch <- sqrt(pmax(ev$values[seq_len(q)] - 1, 0))
# Columns: leading eigenvectors stretched by sqrt(e - 1), then scaled back by Psi^(1/2).
diag(root) %*% (ev$vectors[, seq_len(q), drop = FALSE] %*% diag(stretch, q))
}
In fa_concentrated_loadings(), the vector Psi contains the diagonal of $\Psi$. The call to pmax() supplies the nonnegative common variance in each selected direction, and left multiplication by diag(root), with root the square roots of Psi, returns each loading row to the units of its response.
A selected eigenvalue at or below one gives a zero column and reduces the rank of the common covariance below the specified $q$. This is a property of the loading solution at the given unique variances, not a procedure for selecting the number of factors. An orthogonal rotation of the loading columns leaves the fitted covariance unchanged.
Concentrating the likelihood means maximizing it over the loadings at each proposed $\Psi$ and substituting that solution before optimizing over the unique variances. Order the eigenvalues of $B$ as $e_1\ge\cdots\ge e_p$. When $e_q>1$, each of the first $q$ directions contributes zero at its optimum. In every remaining direction, the model eigenvalue is one, so the concentrated discrepancy is
\[f(\Psi)=\sum_{j=q+1}^{p}(e_j-\log e_j-1).\]For six responses and two factors, fa_concentrated_value() computes this discrepancy from the last four eigenvalues. Any trailing eigenvalue equal to one contributes zero.
1
2
3
4
5
6
7
8
9
10
fa_concentrated_value <- function(Psi, S, q) {
# Only the eigenvalues are needed here.
scale_inv <- 1 / sqrt(Psi); root_inv <- diag(scale_inv)
standardized <- root_inv %*% S %*% root_inv
ev <- eigen(standardized, symmetric = TRUE, only.values = TRUE)$values
# With q active factors, the trailing directions have model eigenvalue one.
rest <- ev[-seq_len(q)]
# sum(e - log(e) - 1) over the p - q smallest eigenvalues, written as below.
-(sum(log(rest) - rest) - q + nrow(S))
}
The implementation accumulates $\log e_j-e_j$, adds $p-q$ and reverses the sign. The function always drops the first $q$ eigenvalues. If a selected $e_j$ falls below one, fa_concentrated_loadings() gives that direction a model eigenvalue of one. Its contribution $e_j-\log e_j-1$ is then positive, so dropping it would omit part of the discrepancy. The implemented expression omits that contribution on this branch.
The derivative below concerns the branch with the leading eigenvalues above one. When $e_q>1$ and $e_q>e_{q+1}$, small changes in the unique variances leave the leading eigenspace separated from the trailing directions. On this branch, the derivative of $f$ follows from the joint discrepancy. At the conditional loading solution, the gradient with respect to the loadings, $2A\Lambda$, is zero, where $A=\Sigma^{-1}-\Sigma^{-1}S\Sigma^{-1}$. Hence the change in loadings induced by varying $\psi_j$ contributes zero in the chain rule. The derivative that remains is $A_{jj}$. Since $A$ is symmetric and $A\Lambda=0$, expanding $\Sigma A\Sigma$ leaves only $\Psi A\Psi$. The definition of $A$ also gives $\Sigma A\Sigma=\Sigma-S$, so
\[\frac{\partial f}{\partial\psi_j} =\frac{\Sigma_{jj}-S_{jj}}{\psi_j^2}.\]The function fa_concentrated_gradient() evaluates this derivative after reconstructing the optimal loadings at the proposed unique variances.
1
2
3
4
5
6
7
8
fa_concentrated_gradient <- function(Psi, S, q) {
# The derivative of the discrepancy with respect to Psi is diag(L L' + Psi - S) / Psi^2,
# with L the loadings that the current uniquenesses imply.
lambda <- fa_concentrated_loadings(Psi, S, q)
# Each diagonal difference gives the numerator for the derivative with respect to one unique variance.
fitted <- lambda %*% t(lambda) + diag(Psi); residual <- fitted - S
diag(residual) / (Psi * Psi)
}
Its matrix residual is the fitted covariance minus the sample covariance. For response 1, residual[1, 1] measures how much its fitted variance exceeds its sample variance at this trial point. The first entry of diag(residual) / Psi^2 divides that signed difference by the square of its proposed uniqueness.
The concentrated fit to FA6
For the actual fit, fa_concentrated() first converts the sample covariance to the correlation matrix $R$. The divisor for entry $(j,k)$ is the product of the two sample standard deviations. In this call, S inside fa_concentrated_loadings(), fa_concentrated_value() and fa_concentrated_gradient() denotes this correlation matrix. Each unique variance is now a fraction of the corresponding sample variance. Its initial value is $(1-q/(2p))/(R^{-1})_{jj}$. For response 1, this gives 0.50788. The search below uses the concentrated discrepancy and gradient on this scale.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fa_concentrated <- function(covariance, factors, lower = 0.005) {
sds <- sqrt(diag(covariance))
corr <- covariance / (sds %o% sds)
start <- (1 - 0.5 * factors / ncol(corr)) / diag(solve(corr))
objective <- function(Psi) fa_concentrated_value(Psi, corr, factors)
gradient <- function(Psi) fa_concentrated_gradient(Psi, corr, factors)
res <- lbfgsb(start, objective, gradient, lower = lower, upper = 1,
control = list(value_scale = 1, par_scale = rep(0.01, length(start))))
loadings <- fa_concentrated_loadings(res$par, corr, factors)
# Reported order and signs: factors by decreasing sum of squared loadings, each column
# with a positive sum.
size <- colSums(loadings^2)
loadings <- loadings[, order(size, decreasing = TRUE), drop = FALSE]
flip <- which(colSums(loadings) < 0)
loadings[, flip] <- -loadings[, flip]
list(loadings = loadings, uniquenesses = res$par, correlation = corr, sds = sds,
converged = res$convergence == 0, objective = res$value, counts = res$counts,
message = res$message, start = start, lower = lower)
}
From this starting vector, lbfgsb(), loaded from code/lib/lbfgsb.R, searches using fa_concentrated_value() and fa_concentrated_gradient(), whose discrepancy interpretation requires the selected-eigenvalue condition just described. This limited-memory BFGS method searches over six unique variances with lower bound 0.005, upper bound 1 and parameter scale 0.01 for each coordinate. One unit in the optimizer’s working coordinates represents a change of 0.01 in a standardized unique variance.
At the returned variances, fa_concentrated_loadings() computes the two loading columns. For reporting, fa_concentrated() arranges them in descending order of their sums of squared loadings and reverses a column if its loadings sum to a negative value. These choices give the factors a reporting order and signs without changing their common covariance.
To compare the fit with joint estimation, both log likelihoods must refer to the original six responses. Multiplying each row of the correlation-scale loadings by its sample standard deviation gives conc_L. Multiplying each unique variance by the corresponding sample variance gives conc_psi. With these quantities, fa_implied() reconstructs a covariance in the units used by fa6_data.
1
2
3
4
5
6
7
8
9
conc_fit <- fa_concentrated(S, 2)
conc_L <- sweep(conc_fit$loadings, 1, conc_fit$sds, "*")
conc_psi <- conc_fit$uniquenesses * conc_fit$sds^2
print(c(concentrated_discrepancy = conc_fit$objective,
discrepancy_evaluations = unname(conc_fit$counts[1]),
gradient_evaluations = unname(conc_fit$counts[2]), converged = conc_fit$converged,
logLik = -fa_criterion(fa_implied(conc_L, conc_psi), fa6_data)$nll,
joint_logLik = -fa_criterion(fa_implied(joint_fit$loadings, joint_fit$uniquenesses),
fa6_data)$nll))
1
2
3
4
concentrated_discrepancy discrepancy_evaluations gradient_evaluations converged
2.000337e-03 1.100000e+01 1.100000e+01 1.000000e+00
logLik joint_logLik
-4.505966e+03 -4.505966e+03
The concentrated discrepancy was 0.002000337. Of the four trailing eigenvalues, the smallest was about 0.94810. Its contribution alone was $0.94810-\log(0.94810)-1\approx0.00140$. Doubling the joint half-discrepancy before rounding gives the same value at this precision. The two log likelihoods both rounded to $-4505.966$. The optimization used 11 discrepancy evaluations and 11 gradient evaluations. The iteration entry in data/derived/ch06/routes.csv is NA. The 1 under converged indicates that lbfgsb() returned convergence code zero. Its message, stored in conc_fit$message, identifies the relative reduction in discrepancy as the stopping rule. The parameter table gives the estimates on the correlation scale.
1
print(cbind(conc_fit$loadings, uniqueness = conc_fit$uniquenesses))
1
2
3
4
5
6
7
uniqueness
y1 0.6090305 -0.5381589 0.3394668
y2 0.6179958 0.4480049 0.4173733
y3 0.6915630 -0.2804910 0.4430653
y4 0.5214501 0.4705263 0.5066942
y5 0.6430031 -0.1451191 0.5654878
y6 0.6268660 0.3330031 0.4961476
For response 1, the unique variance in the original units is $0.3394668\times0.98032\approx0.33279$, also the joint estimate to five decimal places. The joint fit fixed the first response’s second loading at zero. Here it is $-0.5381589$: on these factor axes, increasing factor two by one population standard deviation with factor one fixed lowers the conditional mean of response 1 by 0.53816 standardized response units. Both columns contribute to the fitted covariance of the first two standardized responses through the row product $0.6090305(0.6179958)-0.5381589(0.4480049)$. Dividing by the product of the two fitted standard deviations gives a fitted correlation of 0.13528. In the original response units, the joint fit gives $0.13375/\sqrt{0.98032\times0.99711}$, also 0.13528 to five decimal places.
The two optimizations allow different trial values. The concentrated fit restricts each standardized unique variance to the interval from 0.005 to 1. The joint search used the original response units and imposed no individual bounds. All six reported correlation-scale unique variances lie strictly between 0.005 and 1, ranging from 0.33947 to 0.56549. At these values, the first two eigenvalues of the rescaled correlation matrix are about 6.147 and 3.209, followed by 1.032. Both selected directions therefore carry common variance, and no reported uniqueness equals either imposed bound. If a unique variance reaches the lower bound in another fit, an increase is the feasible direction, so a minimum there requires a nonnegative derivative in that coordinate. At the upper bound, the corresponding derivative must be nonpositive. For example, a strictly positive derivative at the lower bound means that a small decrease in that variance would improve the likelihood if the smaller value were allowed. The supplied fa_concentrated_loadings(), fa_concentrated_gradient() and the starting values are adapted from factanal() of the stats package (code/NOTICE.md), which provides maximum likelihood factor analysis by optimizing over the unique variances.
6.5 EM estimation using conditional factor moments
In FA6, each person supplies six responses, but neither of that person’s two factor values is observed. If the factors were observed, estimating the loadings would be a regression of the centered responses on the factors. What replaces the products in that regression when the factors are missing? At the current loadings $\Lambda$ and positive diagonal uniqueness matrix $\Psi$, write $x_i=y_i-\mu$, with $\mu=\bar y$ and $\Sigma=\Lambda\Lambda^\top+\Psi$. The vectors $z_i$ and $x_i$ are jointly normal. Their covariance blocks are $\operatorname{Var}(z_i)=I_q$, $\operatorname{Var}(x_i)=\Sigma$ and $\operatorname{Cov}(z_i,x_i)=\Lambda^\top$. Subtracting $\Lambda^\top\Sigma^{-1}x_i$ from $z_i$ leaves a normal residual uncorrelated with $x_i$ and hence independent of it. The residual has mean zero. Expanding its covariance gives $I_q-\Lambda^\top\Sigma^{-1}\Lambda$. Thus the conditional mean and covariance of the factors given $y_i$ are
The matrix inversion lemma gives the $q$-dimensional expression for $V$. Multiplying $\Lambda^\top\Sigma^{-1}$ on the left by $I_q+\Lambda^\top\Psi^{-1}\Lambda$ gives $\Lambda^\top\Psi^{-1}$, which yields the expression for $B$. The diagonal $\Psi^{-1}$ weights loading row $j$ by the reciprocal of its unique variance. The remaining inverse comes from a Cholesky factor of a two-by-two matrix, even though the response covariance has six rows and six columns.
For a given person, $m_i$ is the conditional mean of the two factors given the six responses. Their conditional covariance $V$ also enters second moments such as $E(z_{i1}^2\mid y_i)$. Writing $z_i=m_i+(z_i-m_i)$ and taking conditional expectations eliminates the two cross terms and gives
\[E(z_i z_i^\top\mid y_i)=V+m_i m_i^\top.\]The $(1,1)$ entry is $V_{11}+m_{i1}^2$. Even when the responses put the conditional mean of factor one near zero, its expected square includes $V_{11}$. Everyone in this sample was measured on the same six variables. At fixed parameters, $V$ is common to all 600 people, while $m_i$ depends on the six values observed for person $i$.
The M step uses conditional moments computed at the current parameters to estimate new loadings. Let $L$ be the candidate loading matrix and $\Delta$ the candidate diagonal matrix of unique variances. Averaging over people gives the response-factor cross moment $T_{yz}=n^{-1}\sum_i x_i m_i^\top=S_n B^\top$ and the factor second moment $T_{zz}=V+B S_n B^\top$. The factor density contains no parameters to update because it is standard normal. The part of the expected complete-data log likelihood that depends on $L$ and $\Delta$ comes from the normal density of the responses given the factors. Up to a constant, it is
\[Q(L,\Delta)=-\frac n2\{\log|\Delta|+\operatorname{tr}(\Delta^{-1}H(L))\}, \qquad H(L)=S_n-LT_{yz}^\top-T_{yz}L^\top+L T_{zz}L^\top.\]The two cross terms give $n\Delta^{-1}T_{yz}$ in the derivative with respect to $L$. The quadratic term contributes $-n\Delta^{-1}L T_{zz}$. Setting their sum equal to zero gives the normal equations $L_{\rm new}T_{zz}=T_{yz}$. Since $V$ is positive definite and the mean outer products are positive semidefinite, $T_{zz}$ is invertible.
For the unique variance of response $j$, write $l_j^\top$ for row $j$ of this updated loading matrix. The diagonal entry $h_j=H(L_{\rm new})_{jj}$ is the average conditional expectation of the squared residual. In $Q$, the terms for the candidate variance $\delta_j$ are $-(n/2)(\log\delta_j+h_j/\delta_j)$. Their derivative vanishes at $\delta_j=h_j$, the maximizing value for $h_j>0$. To see what that variance includes, fix the updated row and expand the residual around the old conditional mean $m_i$. The cross term has conditional expectation zero, giving
\[E\{(x_{ij}-l_j^\top z_i)^2\mid y_i\} =(x_{ij}-l_j^\top m_i)^2+l_j^\top V l_j.\]Averaging over people gives the new uniqueness. The first term is the squared residual when the factors are replaced by their conditional means. The second accounts for the uncertainty in those predictions. It is constant across people and positive for a nonzero loading row. In matrix form, these additions are the diagonal entries of $L_{\rm new}V L_{\rm new}^\top$, all computed in the factor orientation used for this E step.
Starting values and the first update
The first E step needs starting values for both $\Lambda$ and $\Psi$. For initialization only, fa_em_start() uses $S_{n-1}=nS_n/(n-1)$ and sets the initial uniquenesses to its diagonal. Let $D$ be the diagonal matrix of these variances, $H_q$ the leading eigenvectors of $D^{-1/2}S_{n-1}D^{-1/2}$, $\theta_1,\ldots,\theta_q$ their eigenvalues, and $s^2$ the mean of the remaining eigenvalues. The starting matrix is $D^{1/2}H_q\operatorname{diag}(\theta_1-s^2,\ldots,\theta_q-s^2)$. Each column is multiplied by the eigenvalue difference itself, rather than its square root. This is an initialization formula, not the conditional maximum likelihood loading solution in Section 6.4. The helper orient_loadings() imposes the lower triangular rotation and positive diagonal signs before the starting values are packed.
1
2
3
4
5
6
7
8
9
10
11
12
orient_loadings <- function(loadings) {
q <- ncol(loadings)
decomposition <- qr(t(loadings[seq_len(q), , drop = FALSE]), LAPACK = FALSE)
stopifnot(decomposition$rank == q)
transform <- qr.Q(decomposition)
preliminary <- loadings %*% transform
transform <- sweep(transform, 2,
sign(diag(preliminary[seq_len(q), , drop = FALSE])), "*")
identified <- loadings %*% transform
identified[row(identified) < col(identified)] <- 0
list(loadings = identified, transform = transform)
}
To impose this convention, orient_loadings() factors the transpose of the full-rank leading block as $QR$. Multiplying the loading matrix by $Q$ makes that block $R^\top$. Column sign changes make its diagonal positive, and the entries above the diagonal are set to zero before packing.
With this orientation helper in place, fa_em_start() constructs the initial loadings and unique variances. The following call also evaluates their likelihood.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
fa_em_start <- function(data, q) {
S <- data$S * data$n / (data$n - 1)
D <- diag(S)
eig <- eigen(S / sqrt(outer(D, D)), symmetric = TRUE)
s2 <- if (q == data$p) 0 else mean(eig$values[(q + 1):data$p])
# Multiply each leading eigenvector by its excess over the trailing mean.
loadings <- sweep(eig$vectors[, seq_len(q), drop = FALSE], 2,
eig$values[seq_len(q)] - s2, "*")
loadings <- sweep(loadings, 1, sqrt(D), "*")
fa_pack(orient_loadings(loadings)$loadings, D)
}
em_start <- fa_em_start(fa6_data, 2)
print(c(initial_nll = objective$fn(em_start),
minimum_uniqueness = min(fa_unpack(em_start, 6, 2)$uniquenesses)))
1
2
initial_nll minimum_uniqueness
4875.5430117 0.8981343
In fa_em_start(), D stores the six variances as a vector. The trailing four eigenvalues have a mean of 0.46880. The multiplier for the first column is therefore $2.78444-0.46880=2.31564$ to five decimal places. After the row rescaling by sqrt(D), fa_pack() stores the loadings with that orientation and sign convention and the initial unique variances.
The smallest starting uniqueness was 0.8981343. The negative log likelihood at the starting point was 4875.543. This likelihood and all subsequent conditional moment averages use the covariance with divisor 600.
The E step now computes the conditional covariance and the two average moment matrices needed for the loading and uniqueness updates.
1
2
3
4
5
6
7
8
9
fa_estep <- function(par, data, q) {
natural <- fa_unpack(par, data$p, q)
L <- natural$loadings
weighted <- sweep(L, 1, natural$uniquenesses, "/")
# The conditional covariance requires a factorization in the two factor dimensions.
V <- chol2inv(chol(diag(q) + crossprod(L, weighted)))
B <- V %*% t(weighted)
list(V = V, B = B, Tyz = data$S %*% t(B), Tzz = V + B %*% data$S %*% t(B))
}
For the first update, fa_estep() forms weighted by dividing each of the six loading rows by its uniqueness. Transposing this six-by-two matrix and multiplying on the left by V gives B, with one row per factor and one column per response. The E step returns $T_{yz}=S_n B^\top$ and $T_{zz}=V+BS_n B^\top$ using data$S.
The six-by-two Tyz and two-by-two Tzz average the required products over all the people before fa_mstep() estimates new parameters.
1
2
3
4
5
6
7
8
fa_mstep <- function(moments, par, data, q) {
L <- t(solve(moments$Tzz, t(moments$Tyz)))
# Compute the expected residual covariance on the current factor axes.
residual <- data$S - L %*% t(moments$Tyz) - moments$Tyz %*% t(L) +
L %*% moments$Tzz %*% t(L)
psi <- diag(residual)
fa_pack(orient_loadings(L)$loadings, psi)
}
The call to solve() uses t(Tyz) as its right-hand side, with one column for each response. Transposing the answer gives $L_{\rm new}$. The four terms of residual compute $H(L_{\rm new})$ at those loadings, before orient_loadings() rotates them for storage.
The first update below separates the uniqueness into the squared residual at the conditional factor means and the additional variance due to uncertainty about the factors. Both terms use the same updated loadings on the E-step factor axes.
1
2
3
4
5
6
7
8
9
moments <- fa_estep(em_start, fa6_data, 2)
first_update <- fa_unpack(fa_mstep(moments, em_start, fa6_data, 2), 6, 2)
conditional_means <- centered %*% t(moments$B)
# Use the E-step axes for both parts of the first uniqueness update.
unrotated_update <- t(solve(moments$Tzz, t(moments$Tyz)))
mean_residual <- centered - conditional_means %*% t(unrotated_update)
omitted_variance <- diag(unrotated_update %*% moments$V %*% t(unrotated_update))
print(data.frame(mean_residual_variance = colMeans(mean_residual^2),
missing_conditional_term = omitted_variance, EM_uniqueness = first_update$uniquenesses))
1
2
3
4
5
6
7
mean_residual_variance missing_conditional_term EM_uniqueness
y1 0.4259652 0.1680188 0.5939840
y2 0.4238043 0.1511114 0.5749158
y3 0.4043077 0.1469028 0.5512105
y4 0.4585050 0.1509360 0.6094410
y5 0.4273390 0.1159126 0.5432517
y6 0.4051395 0.1257742 0.5309137
At the start, the first person has a conditional mean of about 0.03972 on the first factor. Adding $V_{11}=0.27133$ to the square of that mean gives a conditional second moment of 0.27291. The calculation stores $m_i^\top$ in row $i$ of conditional_means.
The first row of unrotated_update is approximately $(0.78216,-0.00696)$ on the same axes as those means and moments$V. This is the row that multiplies the conditional covariance in the first response’s variance calculation. The column means of mean_residual^2 give the average squared residual, and omitted_variance gives the conditional-variance contribution.
For response 1, the squared residuals at the conditional means averaged 0.4259652. Uncertainty about the factors added 0.1680188, giving the updated uniqueness of 0.5939840. Across responses, the added terms ranged from 0.116 to 0.168, about 21 to 28 percent of the corresponding updated variances. The residual and conditional-variance terms use the same updated loadings. Changing the factor second moment in the loading equations would also change the coefficients used to calculate the residuals.
Iterating to convergence
Repeating the two steps requires evaluating the observed-data likelihood at each proposed set of parameters. In the R session containing Y and the factor functions, code/lib/result.R supplies the result constructor and code/lib/em.R supplies the complete em() function. The evaluation counter is already available from code/lib/line_search.R in the same session.
1
2
source("code/lib/result.R")
source("code/lib/em.R")
The factor-specific function fa_result() reconstructs the fitted covariance and reports its marginal log likelihood. When individual rows are available, it also evaluates each person’s normal log density.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
fa_result <- function(par, data, q, optimizer, route) {
natural <- fa_unpack(par, data$p, q)
Sigma <- fa_implied(natural$loadings, natural$uniquenesses)
objective <- make_fa_objective(data, q)
contributions <- NULL
if (!is.null(data$Y)) {
residual <- sweep(data$Y, 2, data$mean)
R <- chol(Sigma)
# One log density for each observed response vector.
contributions <- -data$p / 2 * log(2 * pi) - sum(log(diag(R))) -
rowSums((residual %*% chol2inv(R)) * residual) / 2
}
list(loadings = natural$loadings, uniquenesses = natural$uniquenesses,
Phi = diag(q), Sigma = Sigma, mean = data$mean, data = data, par = par,
logLik = -fa_criterion(Sigma, data)$nll,
discrepancy = fa_criterion(Sigma, data)$discrepancy,
max_abs_gradient = max(abs(objective$gr(par))), optimizer = optimizer, route = route,
contributions = contributions, approximation = "exact normal marginalization",
boundary_distance = min(natural$uniquenesses / diag(data$S)),
identification = "leading lower triangle with positive diagonal")
}
The field max_abs_gradient gives the largest absolute component of the negative log likelihood gradient with respect to the 17 packed parameters: the two log diagonal loadings, nine other free loadings, and six log unique variances.
The result label approximation = "exact normal marginalization" describes the analytic integration over the factors, not the accuracy of the fitted parameter values. The field boundary_distance is the minimum ratio of a fitted unique variance to its sample response variance. It is a variance ratio, not a distance in parameter space. The field identification records the rotation and sign convention only.
fa_em() combines the E and M steps into a complete fit, using the observed-data likelihood to monitor the iterations and fa_result() to report the result.
1
2
3
4
5
6
7
8
9
10
11
12
13
fa_em <- function(Y = NULL, covariance = NULL, n = NULL, divisor = NULL, factors,
start = NULL, control = list()) {
data <- fa_data(Y, covariance, n, divisor)
if (is.null(start)) start <- fa_em_start(data, factors)
objective <- make_fa_objective(data, factors)
settings <- modifyList(list(criterion = "loglik_change", tol = 1e-5,
maxit = 500L, monotone_tol = Inf), control)
settings$objective <- objective$fn
settings$gradient <- objective$gr
run <- em(function(par) fa_estep(par, data, factors),
function(moments, par) fa_mstep(moments, par, data, factors), start, settings)
fa_result(run$par, data, factors, run, "EM")
}
fa_em() passes the factor E and M steps, the starting vector and the likelihood settings to em(). On each iteration, em() calls the first supplied function with the current packed parameter vector. It passes the returned moments and that same vector to the second function, which returns the proposed updated vector. The resulting fit stores accepted vectors and their negative log likelihoods in history.
Each new set of unique variances has already been computed when the loading columns are rotated. The rotation preserves the response covariance. At the next E step, the new conditional moments are calculated on the rotated axes.
In em(), value and candidate_value are successive values of the negative log likelihood function. The function sets accepted to true if both is.finite(candidate_value) and candidate_value <= value + settings$monotone_tol * (1 + abs(value)) are true. With monotone_tol = Inf, a candidate with a finite negative log likelihood can be accepted even if the observed-data log likelihood falls. After acceptance, gain <- value - candidate_value gives the increase in the observed-data log likelihood. The selected test abs(gain) < settings$tol stops the run when the absolute change falls below $10^{-5}$, with a limit of 500 updates.
1
2
3
4
5
em_fit <- fa_em(Y, factors = 2)
em_values <- vapply(em_fit$optimizer$history, function(entry) entry$value, 0)
print(c(logLik = em_fit$logLik, maximum_absolute_nll_derivative = em_fit$max_abs_gradient,
maximum_signed_nll_change = max(diff(em_values)),
iterations = em_fit$optimizer$iterations))
1
2
3
4
logLik maximum_absolute_nll_derivative maximum_signed_nll_change
-4.505966e+03 4.009171e-02 -8.579354e-06
iterations
6.100000e+01
The largest signed change in the negative log likelihood was $-8.579354\times10^{-6}$. Every update therefore decreased it, and the smallest decrease was about $8.6\times10^{-6}$. After 61 updates, the observed-data log likelihood was $-4505.966$. The result records which stopping rule was satisfied.
1
print(em_fit$optimizer$reason)
1
[1] "small_loglik_change"
At this stopping point, the largest absolute derivative of the negative log likelihood was still 0.04009. When much of the complete-data information in a direction is missing, an EM update near the solution can remove only a small fraction of the remaining parameter error in that direction. A stopping rule based on the change in the log likelihood can then leave a measurable difference in the estimates.
1
2
print(cbind(em_fit$loadings, uniqueness = em_fit$uniquenesses,
common_variance = rowSums(em_fit$loadings^2)))
1
2
3
4
5
6
7
uniqueness common_variance
[1,] 0.8043377 0.0000000 0.3333374 0.6469591
[2,] 0.1663261 0.7438236 0.4161732 0.5809379
[3,] 0.6926841 0.2435168 0.4284372 0.5391117
[4,] 0.0789172 0.6949624 0.5023560 0.4892007
[5,] 0.5473688 0.3000716 0.5069737 0.3896555
[6,] 0.2375490 0.6330878 0.4502648 0.4572297
The first response had a fitted common variance of 0.6469591 and a unique variance of 0.3333374. The joint fit returned a first uniqueness of 0.3327870. The first uniqueness therefore differs by about 0.00055 at the endpoints selected by the two stopping rules. At three decimal places, the EM, joint and concentrated fits all give the same observed-data log likelihood.
6.6 Heywood cases and variance estimates at the boundary
In FA6, each fitted response variance included a positive unique variance. Can a common factor account for the entire variance of a response? With a single standardized factor, the variance of response 1 is $\lambda_1^2+\psi_1$. An estimate that assigns all of this variance to the factor gives $\psi_1=0$, a zero unique-variance estimate, commonly called a Heywood case. An estimate that assigns more than the total variance to the factor gives $\psi_1<0$, a negative unique-variance estimate. SAS calls the latter an ultra-Heywood case; some factor-analysis texts also use Heywood case for negative estimates. The numerical condition is therefore stated explicitly here.
A search that leaves the unique variances unconstrained can return a negative estimate even when it evaluates the likelihood correctly. A negative number cannot be a variance. The model allows each uniqueness to be zero or positive. A fit using $\eta_1=\log\psi_1$ can represent only positive values at finite $\eta_1$.
Consider HEYWOOD3, a population covariance constructed for three responses that share one factor. Its covariance matrix is $S=\lambda\lambda^\top+\operatorname{diag}(0,0.4,0.5)$. The loading vector is $\lambda=(0.9,0.7,0.6)^\top$. The off-diagonal covariances identify how much variance the first response shares with the factor. Since $S_{jk}=\lambda_j\lambda_k$ for distinct responses, $\lambda_1^2=S_{12}S_{13}/S_{23}=0.63\times0.54/0.42=0.81$. This accounts for the entire first variance, $S_{11}=0.81$. To check whether the response covariance is positive definite, consider a linear combination of the responses. With weights $a=(a_1,a_2,a_3)^\top$, its variance is
For this sum to vanish, the last two terms require $a_2=a_3=0$, and the first then requires $a_1=0$. The example uses $n=100$ to scale the normal likelihood criterion for this matrix. Setting the divisor to 100 in fa_data() preserves the supplied covariance. The file data/source/ch06/HEYWOOD3.rds contains the covariance and its generating parameters. No sample of 100 people is drawn for this example; 100 is only the multiplier in the criterion.
How does the negative log likelihood change if the first response is given a little unique variance? Fix all three loadings and both other unique variances at their current values. Then $\Sigma-S$ has just one nonzero entry, $\psi_1$ in position $(1,1)$. The derivative with respect to $\psi_1$ is $nA_{11}/2$, where $A=\Sigma^{-1}(\Sigma-S)\Sigma^{-1}$. Along this path $A_{11}=\psi_1[(\Sigma^{-1})_{11}]^2$. For the log coordinate, the chain rule gives
\[\frac{\partial(-\ell)}{\partial\eta_1} =\frac{\partial(-\ell)}{\partial\psi_1}\frac{d\psi_1}{d\eta_1} =\psi_1\,\frac{n}{2}A_{11}.\]From the book directory, load the factor and bounded optimization functions and construct $S$ at the stated parameters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
source("code/lib/factor.R")
source("code/lib/lbfgsb.R")
boundary_lambda <- matrix(c(.9, .7, .6), 3, 1)
boundary_psi <- c(0, .4, .5)
boundary_S <- fa_implied(boundary_lambda, boundary_psi)
boundary_data <- fa_data(covariance = boundary_S, n = 100, divisor = 100)
boundary_path <- do.call(rbind, lapply(c(.1, .01, .001, 1e-6), function(psi1) {
Sigma <- fa_implied(boundary_lambda, c(psi1, .4, .5))
value <- fa_criterion(Sigma, boundary_data)
# Differentiate the negative log likelihood in response-variance units.
variance_derivative <- boundary_data$n / 2 * value$A[1, 1]
data.frame(psi1 = psi1, log_psi1 = log(psi1), discrepancy = value$discrepancy,
covariance_gap = max(abs(Sigma - boundary_S)),
variance_derivative = variance_derivative, log_derivative = psi1 * variance_derivative)
}))
print(boundary_path, row.names = FALSE)
1
2
3
4
5
psi1 log_psi1 discrepancy covariance_gap variance_derivative log_derivative
1e-01 -2.302585 4.347729e-02 1e-01 3.554751e+01 3.554751e+00
1e-02 -4.605170 6.301733e-04 1e-02 6.153907e+00 6.153907e-02
1e-03 -6.907755 6.577619e-06 1e-03 6.561729e-01 6.561729e-04
1e-06 -13.815511 6.608936e-12 1e-06 6.609482e-04 6.609482e-10
Each row evaluates a specified positive variance with the loadings fixed. At 0.1, variance_derivative gives 35.5475 per unit increase in the variance. Multiplying by 0.1 gives 3.55475 in the log_derivative column. At 0.01 the corresponding values are 6.15391 and 0.06154. Moving from 0.001 to $10^{-6}$ reduces the largest covariance difference by a factor of a thousand, and the log-coordinate derivative falls from about $6.6\times10^{-4}$ to $6.6\times10^{-10}$. At each point the derivative in variance units is positive, so a small decrease in $\psi_1$ still improves the fit. A stopping test on the log-coordinate derivative alone could already be satisfied at a positive value. At the constructed zero, $\Sigma=S$ gives $A=0$ exactly. Evaluating the discrepancy at the same matrix gives a numerical check on the exact fit.
1
2
print(c(minimum_eigenvalue = min(eigen(boundary_S, symmetric = TRUE)$values),
exact_boundary_discrepancy = fa_criterion(boundary_S, boundary_data)$discrepancy))
1
2
minimum_eigenvalue exact_boundary_discrepancy
1.838532e-01 1.332268e-15
The smallest eigenvalue, about 0.18385, confirms positive definiteness even with the first uniqueness set to zero. The discrepancy of $1.33\times10^{-15}$ is zero to numerical precision.
Comparing a positive lower bound with zero unique variance
What happens if the fit requires each response to retain some unique variance? fa_concentrated() standardizes boundary_S to a correlation matrix and fits one factor with each standardized uniqueness between 0.005 and 1. For each trial set of uniquenesses it recomputes the loadings. To compare the fitted covariance with $S$, multiply each loading by its response standard deviation and each uniqueness by the corresponding response variance. fa_concentrated_gradient() uses the standardized estimates to differentiate the concentrated discrepancy. In boundary_comparison, bound_derivative selects the first coordinate, and max_abs_free_gradient summarizes the other two.
1
2
3
4
5
6
7
8
9
10
11
12
13
heywood_fit <- fa_concentrated(boundary_S, 1)
# Return to response units to evaluate the fitted covariance.
heywood_L <- sweep(heywood_fit$loadings, 1, heywood_fit$sds, "*")
heywood_psi <- heywood_fit$uniquenesses * heywood_fit$sds^2
heywood_Sigma <- fa_implied(heywood_L, heywood_psi)
# Differentiate the concentrated discrepancy on the correlation scale.
heywood_gradient <- fa_concentrated_gradient(heywood_fit$uniquenesses, heywood_fit$correlation, 1)
boundary_comparison <- c(
exact_discrepancy = fa_criterion(boundary_S, boundary_data)$discrepancy,
bounded_psi1 = heywood_psi[1],
bounded_discrepancy = fa_criterion(heywood_Sigma, boundary_data)$discrepancy,
max_abs_free_gradient = max(abs(heywood_gradient[-1])), bound_derivative = heywood_gradient[1])
print(boundary_comparison)
1
2
3
4
exact_discrepancy bounded_psi1 bounded_discrepancy
1.332268e-15 4.050000e-03 2.226983e-05
max_abs_free_gradient bound_derivative
1.754585e-08 8.951737e-03
The first uniqueness equals the lower bound. Since the first response variance is 0.81, the bound in the units of that variance is $0.005\times0.81=0.00405$. The discrepancy increases to about $2.227\times10^{-5}$. At the bound the feasible change in the first standardized uniqueness is an increase, and its positive derivative of 0.00895 means that a small increase raises the discrepancy. The other two uniquenesses lie strictly between 0.005 and 1, so sufficiently small changes of either sign are allowed. Their largest absolute derivative is about $1.8\times10^{-8}$, consistent with stationarity to numerical precision. The derivative sign at the first variance, which equals its lower bound, also explains why allowing a small decrease could improve the fit.
The exact-zero evaluation checks the constructed covariance, while the bounded fit estimates parameters under a positive lower bound. The model permits response 1 to share all its variance with the factor. Imposing the numerical lower bound reserves at least half a percent of each response variance for its unique component. An algorithm comparison therefore requires the same permitted variance range on the same scale for both fits. A lower bound of 0.005 in the original response units would require a first standardized uniqueness of at least $0.005/0.81\approx0.00617$.
At $\psi_1=0$, every open interval around the estimated variance contains negative values. The usual inverse-Hessian standard error and normal approximation require regularity conditions, including local identification, nonsingular information and a true parameter with an allowed neighborhood in every free-parameter direction. A zero unique variance fails the neighborhood condition. A symmetric interval centered at zero with positive width would extend below zero regardless of the curvature. The normal approximation used for that interval and the corresponding Wald test lacks its usual justification here.
The constructed exact-zero solution lies on the variance boundary. An estimate at the imposed positive lower bound of 0.005 is on the boundary of that restricted optimization problem; it is not a zero-variance estimate in the original model. It must be reported together with the bound and its scale. The stats package provides maximum likelihood factor analysis with a lower bound on standardized uniquenesses.
6.7 Implementing varimax and promax rotation
The EM fit to FA6 assigned a common variance of 0.64696 to the first response. This variance, the part explained by the common factors, is its communality. With orthogonal factors of unit variance, the communality of response $j$ is the sum of the squared loadings in row $j$. An orthogonal rotation preserves the row length while redistributing the communality between the two factors. Varimax seeks an orientation that makes the squared loadings within each factor column as variable across responses as possible.
For Kaiser normalization, divide each loading row by its length, the square root of its communality. Each response then enters the rotation with a row of length one. On the original response scale, communality is an amount of variance. Dividing it by the total response variance gives the proportion accounted for by the common factors. Kaiser normalization rescales the loading rows for rotation; it does not standardize the observed responses. Let $a_{jk}$ denote a loading after this normalization and an orthogonal rotation, with $p$ responses and $q$ factors. The criterion used here is
\[C(a)=\sum_{k=1}^q\left\{\sum_{j=1}^p a_{jk}^4 -\frac{1}{p}\left(\sum_{j=1}^p a_{jk}^2\right)^2\right\}.\]For each factor the term in braces is $p$ times the variance of its squared loadings, calculated with divisor $p$. A column whose squared entries are all equal contributes zero. Separating the larger and smaller squared loadings further in that column increases its contribution. All six communalities are positive here, so the original row lengths can be used to normalize the loadings and to restore their scales after rotation.
To update all factor columns together, write $x$ for the normalized loading matrix, $T$ for the current orthogonal transformation and $z=xT$. For column $k$, set $s_k=\sum_j z_{jk}^2$. Differentiating its contribution to $C$ with respect to $z_{jk}$ gives $4z_{jk}^3-4z_{jk}s_k/p$. Since a change in $T$ changes $z$ by $x\,dT$, the gradient with respect to $T$ is $4B$, where the cube below is taken entry by entry. For a candidate orthogonal matrix $W$, maximizing the linear term in the change of criterion amounts to maximizing $\operatorname{tr}(W^\top B)$. Write the singular value decomposition as $B=UDV^\top$. Then
\[B=x^\top\left\{z^{\circ3}-\frac{1}{p}z\,\operatorname{diag}(s_1,\ldots,s_q)\right\}, \qquad \operatorname{tr}(W^\top B)=\sum_{k=1}^q D_{kk}(U^\top W V)_{kk}.\]The diagonal entries of the orthogonal matrix $U^\top W V$ are at most one. The singular values $D_{kk}$ are nonnegative, so taking $W=UV^\top$ attains the largest possible trace, their sum. This gives the next rotation. The following functions evaluate the criterion and apply these updates to the loading matrix.
1
2
3
4
5
6
varimax_criterion <- function(loadings, normalize = TRUE) {
h <- if (normalize) sqrt(rowSums(loadings^2)) else rep(1, nrow(loadings))
h[h == 0] <- 1
A <- loadings / h
sum(colSums(A^4) - colSums(A^2)^2 / nrow(A))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
rotate_varimax <- function(loadings, normalize = TRUE, eps = 1e-5) {
stopifnot(is.matrix(loadings), all(is.finite(loadings)), ncol(loadings) >= 2L, eps > 0)
x <- loadings
row_length <- function(i) sqrt(sum(x[i, ]^2))
lengths <- if (normalize) vapply(seq_len(nrow(x)), row_length, 0) else NULL
if (normalize) x <- x / lengths
p <- nrow(x); ones <- rep(1, p)
transform <- diag(ncol(x))
total <- 0; history <- numeric(); update <- 0L
repeat {
update <- update + 1L
z <- x %*% transform
cube <- z^3
shrinkage <- z %*% diag(drop(ones %*% z^2))
# Compare successive sums of singular values.
previous <- total
# Maximize the linear term over orthogonal transformations.
decomposition <- La.svd(t(x) %*% (cube - shrinkage / p))
total <- sum(decomposition$d)
transform <- decomposition$u %*% decomposition$vt
history <- c(history, total)
# Stop when the criterion no longer rises by the relative amount eps, or at 1000.
if (previous * (1 + eps) > total || update == 1000L) break
}
rotated <- x %*% transform
if (normalize) rotated <- rotated * lengths
list(loadings = rotated, transform = transform, Phi = diag(ncol(x)),
criterion = varimax_criterion(rotated, normalize), history = history, iterations = update,
converged = previous * (1 + eps) > total, normalize = normalize)
}
For the six responses, varimax_criterion() forms the two column sums of fourth powers and subtracts the correction for each column mean of squared loadings. In rotate_varimax(), the matrix passed to La.svd() is two by two, and La.svd() returns the transposed right singular vectors in vt. The function records the sum of the singular values in history. After the last update it multiplies each rotated row by its original length and evaluates the varimax criterion on the resulting loadings. The local matrix shrinkage contains $z\operatorname{diag}(s_1,\ldots,s_q)$, the column-sum term subtracted in this derivative calculation. Its name does not describe shrinkage estimation of the loadings.
The iteration starts at the identity and compares successive sums of singular values. It stops when the current sum is less than the previous sum times $1+10^{-5}$, with at most 1,000 updates. This comparison also permits stopping after a decrease in that sum; it does not directly test the change in the varimax criterion $C$.
The diagnostic function varimax_criterion() sets the divisor of a zero row to one, which leaves that row zero. The rotation function rotate_varimax() divides directly by the row lengths but does not explicitly reject zero lengths before division. Positive row lengths are therefore an input requirement for this implementation when normalization is used.
To form the starting matrix rotation_input, rotate the fitted EM loadings through $\pi/6$. For the first response, this takes the loading pair from approximately $(0.80434,0)$ to $(0.69658,-0.40217)$ while preserving its communality. In a fresh session, em_fit <- readRDS("data/derived/ch06/fits.rds")$EM loads the fitted model when the working directory is the book directory.
1
2
3
4
5
6
7
8
R30 <- matrix(c(cos(pi / 6), sin(pi / 6), -sin(pi / 6), cos(pi / 6)), 2, 2)
rotation_input <- em_fit$loadings %*% R30
varimax_fit <- rotate_varimax(rotation_input)
print(c(initial_criterion = varimax_criterion(rotation_input),
final_criterion = varimax_fit$criterion, updates = varimax_fit$iterations,
orthogonality_error = max(abs(crossprod(varimax_fit$transform) - diag(2))),
common_covariance_gap = max(abs(tcrossprod(varimax_fit$loadings) -
tcrossprod(rotation_input)))))
1
2
initial_criterion final_criterion updates orthogonality_error common_covariance_gap
7.024349e-01 2.108376e+00 2.100000e+01 5.551115e-16 4.440892e-16
After 21 updates the criterion had risen from 0.70243 to 2.10838. The last relative increase in the sum of singular values, calculated from the last two entries of history, was about $6.1\times10^{-6}$. This was the quantity tested for stopping. The largest absolute entry of $T^\top T-I$ was $5.55\times10^{-16}$. The largest change in any entry of the common covariance was $4.44\times10^{-16}$, as expected for an orthogonal transformation. The stopping rule measures progress from the chosen start and gives no guarantee of a global maximum of the varimax criterion.
Promax rotation
Varimax leaves the factors uncorrelated. Promax is an oblique rotation: it permits correlated factors while giving each factor variance one. Write $L_\ast$ for its loading matrix and $\Phi_\ast$ for its factor correlation matrix. The entries of $L_\ast$ are the pattern coefficients. Each gives the change in a response’s conditional mean per unit increase in one factor with the other factors fixed. The response-factor covariances are instead the entries of $L_\ast\Phi_\ast$, which include the association through the other, correlated factors. Dividing each row of this product by the corresponding fitted response standard deviation gives the response-factor correlations, called structure coefficients. Thus a negative pattern coefficient can accompany a positive structure coefficient.
The starting matrix $x$ is the varimax solution with its response scales restored. For a power of four, define the target matrix $H$ with entries $H_{jk}=x_{jk}\vert x_{jk}\vert ^3$. The sign of each loading is preserved, while the ratio of a smaller magnitude to a larger one is raised to the fourth power. In the first varimax row, loadings of about 0.8043 and 0.0026 yield target entries of about 0.419 and less than $10^{-10}$. To approximate the target with transformed loadings, choose $U$ to minimize the sum of squared entries of $xU-H$. Because $x$ has full column rank, its QR decomposition $x=QR$, with $Q$ containing $q$ orthonormal columns and $R$ a $q\times q$ upper triangular matrix, gives an invertible $R$. Solving $RU=Q^\top H$ gives a unique least-squares solution for each target column.
The two least-squares regressions fit the target without constraining the variances of the new factors. To give each factor variance one, let $D_s$ be diagonal with entries $\sqrt{[(U^\top U)^{-1}]_{kk}}$, assuming $U$ is invertible. The code replaces $U$ by $UD_s$ and combines it with the orthogonal varimax rotation $T$ to give $P=TUD_s$, where $U$ in this expression denotes the original least-squares solution. If $L$ denotes rotation_input, the new loadings are $L_\ast =LP$. For a person with factor vector $f$ on the input axes, the rotated factors are $f_\ast =P^{-1}f$, so $L_\ast f_\ast =Lf$. The input factors have identity covariance. Orthogonality of $T$ gives
The $k$th diagonal entry of $\Phi_\ast $ equals one because the rescaling divides the corresponding diagonal entry of $(U^\top U)^{-1}$ by that same value. Its off-diagonal entries can be nonzero.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
rotate_promax <- function(loadings, m = 4) {
stopifnot(m >= 1, ncol(loadings) >= 2L)
orthogonal <- rotate_varimax(loadings)
x <- orthogonal$loadings
target <- x * abs(x)^(m - 1)
U <- qr.coef(qr(x), target)
# Scale the factors to unit variance before computing their correlations.
d <- diag(solve(t(U) %*% U))
U <- U %*% diag(sqrt(d))
transform <- orthogonal$transform %*% U
list(loadings = x %*% U, transform = transform, Phi = solve(crossprod(transform)),
target = target, target_residual = sum((x %*% qr.coef(qr(x), target) - target)^2),
varimax = orthogonal, power = m)
}
In rotate_promax(), target uses the restored loadings and qr.coef() solves the two regressions. The field target_residual measures their combined residual sum of squares before the columns are rescaled.
The following call prints both sets of loadings in the original response units.
1
2
promax_fit <- rotate_promax(rotation_input)
print(round(cbind(varimax_fit$loadings, promax_fit$loadings), 4))
1
2
3
4
5
6
7
[,1] [,2] [,3] [,4]
[1,] 0.8043 0.0026 0.8772 -0.1927
[2,] 0.1639 0.7444 -0.0512 0.7850
[3,] 0.6919 0.2458 0.6793 0.1041
[4,] 0.0766 0.6952 -0.1312 0.7518
[5,] 0.5464 0.3019 0.5031 0.2016
[6,] 0.2355 0.6339 0.0611 0.6452
Columns one and two of the loading table give varimax factors one and two. Columns three and four give the promax pattern coefficients. For response 1 the promax pair is $(0.8772,-0.1927)$, and for response 2 it is $(-0.0512,0.7850)$. With the first factor fixed, a one-unit increase in the second decreases the conditional mean of response 1 by 0.1927 and increases that of response 2 by 0.7850, in their respective response units.
The diagonal of the returned factor covariance matrix shows the result of the column scaling. Its off-diagonal entry gives the correlation needed to reproduce the response covariances.
1
print(promax_fit$Phi)
1
2
3
[,1] [,2]
[1,] 1.0000000 0.4723545
[2,] 0.4723545 1.0000000
On the promax axes, the two factors have correlation 0.47235. Despite its negative pattern coefficient, response 1 has positive covariance with the second factor, approximately $0.8772\times0.47235-0.1927=0.222$. Dividing this value by response 1’s fitted standard deviation gives its positive structure coefficient. The positive association includes the contribution through the correlated first factor, whereas the negative pattern coefficient describes a change with that factor fixed.
In the check below, the first product uses the full $\Phi_\ast $. The second uses the identity in its place.
1
2
3
4
print(c(common_covariance_gap = max(abs(promax_fit$loadings %*% promax_fit$Phi %*%
t(promax_fit$loadings) - tcrossprod(rotation_input))),
gap_if_Phi_ignored = max(abs(tcrossprod(promax_fit$loadings) -
tcrossprod(rotation_input)))))
1
2
common_covariance_gap gap_if_Phi_ignored
2.220446e-16 3.299418e-01
Including the factor correlation reproduced the common covariance to $2.22\times10^{-16}$. Using the promax loadings alone gave a maximum absolute difference of 0.32994.
For these same two responses, let $(a,b)$ and $(c,d)$ be the first two promax loading rows, with factor correlation $\rho$. Their common covariance is the sum of two within-factor products and two products weighted by the factor correlation. In symbols,
\[(L_*\Phi_*L_*^\top)_{12}=ac+bd+\rho(ad+bc).\]Using the fitted coefficients before rounding, the within-factor products sum to $-0.19616$. The factor correlation adds 0.32994, giving 0.13378. Taking the inner product of the two varimax rows gives the same fitted covariance. The unique errors contribute zero to this off-diagonal entry. Each rotation therefore describes the same association, and the diagonal entries of the common covariance give the same six communalities. A substantive name for either factor would require evidence about what the responses with large loadings measure. The supplied rotate_varimax() is adapted from varimax() of the stats package, and rotate_promax() starts from its result (code/NOTICE.md); stats provides both rotations.
6.8 Regression and Bartlett factor scores
The two promax loadings for a response describe how its mean changes with a person’s factors. Now suppose the six responses are known for one person. What do they indicate about that person’s two factor values? A factor score predicts those values from the responses. It differs from the likelihood score vector, which contains the derivatives of the log likelihood with respect to the model parameters.
To predict the factor vector $z_i$, write $x_i=y_i-\mu=\Lambda z_i+\epsilon_i$. The factors have mean zero and covariance $\Phi$. The errors are independent of the factors and have mean zero and diagonal covariance $\Psi$. Thus $\operatorname{Var}(x_i)=\Sigma=\Lambda\Phi\Lambda^\top+\Psi$ and $\operatorname{Cov}(z_i,x_i)=\Phi\Lambda^\top$. Choose a coefficient matrix $B_R$ so that the residual $z_i-B_Rx_i$ has zero covariance with $x_i$. This gives $B_R\Sigma=\Phi\Lambda^\top$. Under the joint normal model the residual is independent of $x_i$ and has mean zero, so the regression factor score is the conditional mean given below. Substituting fitted parameters estimates that mean while treating those fitted parameters as fixed:
\[\widehat z_{R,i}=E(z_i\mid y_i)=B_Rx_i,\qquad B_R=\Phi\Lambda^\top\Sigma^{-1}.\]Under the normal model with known parameters, this conditional mean minimizes expected squared prediction error. For a given response vector, any other proposed score $a$ has conditional expected squared error equal to that at $m_i=E(z_i\mid y_i)$ plus $\Vert a-m_i\Vert^2$. The cross term vanishes because $E(z_i-m_i\mid y_i)=0$.
The Bartlett score answers another question about the same person. Which factor vector $u$ reproduces the centered responses most closely when each squared residual is weighted by the reciprocal of its unique variance? With positive unique variances, the weighted residual sum of squares is $(x_i-\Lambda u)^\top\Psi^{-1}(x_i-\Lambda u)$. Differentiating with respect to $u$ and setting the derivative to zero gives $\Lambda^\top\Psi^{-1}\Lambda u=\Lambda^\top\Psi^{-1}x_i$. If $\Lambda$ has full column rank, $\Lambda^\top\Psi^{-1}\Lambda$ is positive definite, so the minimizing factor vector is
\[\widehat z_{B,i}=B_Bx_i,\qquad B_B=(\Lambda^\top\Psi^{-1}\Lambda)^{-1}\Lambda^\top\Psi^{-1}.\]At the model parameters, $B_B\Lambda=I_q$, so the Bartlett score equals $z_i+B_B\epsilon_i$. Fixing a person’s factor vector and averaging over repeated responses gives $E(\widehat z_{B,i}\mid z_i)=z_i$. This is the sense in which Bartlett scoring is unbiased. It averages over response error at fixed factors, whereas the regression score minimizes expected squared error over the factor distribution given the responses.
Take a single response $y=2$ with mean zero, loading one, unit factor variance and unit unique variance. The total response variance is two, so the regression weight is $1/2$. The regression score is $2/2=1$. Bartlett’s criterion reduces to $(2-u)^2$, giving weight one and score two. Here the conditional mean lies halfway between the Bartlett estimate and the prior factor mean of zero. The variance of the factor about its conditional mean is $1-(1/2)\times1=0.5$. Once the response and model parameters are given, both computed scores are fixed. The variance 0.5 describes the uncertainty about the person’s factor value after observing the response.
The function fa_scores() computes either set of scores from individual responses and fitted model parameters. It also returns the conditional factor covariance $\Phi-B_R\Lambda\Phi$, obtained by expanding the covariance of $z_i-B_Rx_i$. For either method, this covariance describes uncertainty around the conditional factor mean. Conditional squared error at a Bartlett score also includes its squared distance from that mean.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
fa_scores <- function(fit, Y = fit$data$Y, method = c("regression", "Bartlett"),
loadings = fit$loadings, Phi = fit$Phi) {
method <- match.arg(method)
if (is.null(Y)) stop("Individual responses are required for factor scores")
if (is.null(fit$mean)) stop("The response centering mean is required")
stopifnot(is.matrix(Y), ncol(Y) == nrow(loadings), all(is.finite(Y)))
centered <- sweep(Y, 2, fit$mean)
Sigma <- fa_implied(loadings, fit$uniquenesses, Phi)
B <- Phi %*% t(loadings) %*% chol2inv(chol(Sigma))
# Factor uncertainty conditional on the responses, using regression weights.
conditional_covariance <- Phi - B %*% loadings %*% Phi
if (method == "Bartlett") {
stopifnot(all(fit$uniquenesses > 0), qr(loadings)$rank == ncol(loadings))
weighted <- sweep(loadings, 1, fit$uniquenesses, "/")
B <- solve(crossprod(loadings, weighted), t(weighted))
}
list(scores = centered %*% t(B), coefficients = B, method = method,
conditional_covariance = conditional_covariance,
coordinates = list(loadings = loadings, Phi = Phi, mean = fit$mean))
}
For either method, the coefficient matrix B has factors in its rows and responses in its columns. The function centers each person’s row of observations using the fitted response means. It first computes regression weights using the Cholesky factor of the implied covariance and uses those weights for conditional_covariance. For Bartlett scoring, weighted divides each loading row by its unique variance and solve() solves the weighted normal equations for B. Multiplication by t(B) puts each person’s factor scores in one row. In the notation above, B is first $B_R$ and, for Bartlett scoring, becomes $B_B$ with weighted equal to $\Psi^{-1}\Lambda$; conditional_covariance is $\Phi-B_R\Lambda\Phi$.
The one-row response matrix in scalar_fit supplies the value two to both calculations.
1
2
3
4
5
scalar_fit <- list(loadings = matrix(1, 1, 1), uniquenesses = 1,
Phi = matrix(1, 1, 1), mean = 0, data = list(Y = matrix(2, 1, 1)))
print(c(regression = fa_scores(scalar_fit)$scores,
Bartlett = fa_scores(scalar_fit, method = "Bartlett")$scores,
conditional_variance = fa_scores(scalar_fit)$conditional_covariance))
1
2
regression Bartlett conditional_variance
1.0 2.0 0.5
The first two entries give the predictions, and the third gives the conditional variance in squared factor units.
Scores for the FA6 responses
Beyond this one-response example, each of the 600 rows of Y in FA6 has six measurements. Applying both sets of weights from em_fit gives two score columns per method. To express them on the promax axes, the transformation must include both the initial 30-degree rotation R30 of the EM loadings and the subsequent promax transformation.
1
2
3
4
5
6
7
regression <- fa_scores(em_fit)
bartlett <- fa_scores(em_fit, method = "Bartlett")
total_transform <- R30 %*% promax_fit$transform
rotated_regression <- fa_scores(em_fit, loadings = promax_fit$loadings,
Phi = promax_fit$Phi)
rotated_bartlett <- fa_scores(em_fit, method = "Bartlett",
loadings = promax_fit$loadings, Phi = promax_fit$Phi)
For the first person, the first centered response is 0.18084. Its weights for factor one are about 0.55051 by regression and 0.74293 by Bartlett’s method. It therefore contributes 0.09955 and 0.13435, respectively, to that factor’s two predictions. Summing the contributions of all six responses gives the first row of regression$scores, $(0.077,0.148)$, and of bartlett$scores, $(0.082,0.189)$, to three decimal places.
For the change of axes within the EM fit, the transformation itself is known. With $T$ equal to total_transform, the rotated loadings are $\Lambda T$. The regression weights on the new axes are $T^{-1}B_R$ because the response covariance is unchanged and $\operatorname{Cov}(T^{-1}z_i,x_i)=T^{-1}\operatorname{Cov}(z_i,x_i)$. In Bartlett’s criterion, replacing $u$ by $T^{-1}u$ gives the same residual $x_i-\Lambda T(T^{-1}u)$. For each method, multiplying a person’s score vector by $T^{-1}$ gives the rotated score. Stacking people as rows gives $ZT^{-\top}$ for an original score matrix $Z$.
1
2
3
4
print(c(regression_transform_error = max(abs(rotated_regression$scores -
regression$scores %*% t(solve(total_transform)))),
Bartlett_transform_error = max(abs(rotated_bartlett$scores -
bartlett$scores %*% t(solve(total_transform))))))
1
2
regression_transform_error Bartlett_transform_error
1.776357e-15 1.776357e-15
For both methods, scoring directly with the promax loadings and factor correlation matrix agreed with transforming the original EM scores to within $1.78\times10^{-15}$.
A separate comparison fits the concentrated model to the raw responses with covariance divisor $n-1=599$. Let $X_s$ denote the $600\times6$ matrix of centered responses divided by their sample standard deviations, and let $R$ be the sample correlation matrix. For this calculation $\Lambda_c$ and $\Psi_c$ are the correlation-scale loadings and uniqueness matrix. The comparison regression scores are $X_sR^{-1}\Lambda_c$, whereas the EM regression scores use the covariance implied by the fitted model. The concentrated Bartlett scores use $B_B$ evaluated at the concentrated estimates.
The comparison uses canonical correlations. The function cancor() chooses one linear combination of score columns from each fit to maximize the correlation between the two combinations. It then repeats the calculation using the direction uncorrelated with the first combination within each fit. These correlations assess agreement after allowing the factor axes to differ.
1
2
3
4
5
6
7
8
9
data_fit <- fa_concentrated(cov.wt(Y)$cov, 2)
zz <- scale(Y, TRUE, TRUE)
conc_regression <- zz %*% solve(data_fit$correlation, data_fit$loadings)
d <- 1 / data_fit$uniquenesses
tmp <- t(data_fit$loadings * d)
conc_bartlett <- t(solve(tmp %*% data_fit$loadings, tmp %*% t(zz)))
# Compare the two score spaces for each method.
print(rbind(regression = cancor(conc_regression, regression$scores)$cor,
Bartlett = cancor(conc_bartlett, bartlett$scores)$cor))
1
2
3
[,1] [,2]
regression 1 0.9999997
Bartlett 1 0.9999997
Each row compares the two fitted models using one scoring method. The canonical correlations of 1 and 0.9999997 to the printed precision show that the linear combinations of one pair of score columns closely reproduce those of the other pair, after allowing the factor axes to differ. This does not establish equality of individual scores on the original axes or scales.
In this calculation, zz is $X_s$, and tmp is $\Lambda_c^\top\Psi_c^{-1}$. The right-hand side of solve() has 600 columns, one per person. Transposing the solution gives the $600\times2$ score matrix $X_sB_{B,c}^\top$, with $B_{B,c}$ evaluated at the concentrated estimates. The use of $R^{-1}\Lambda_c$ is the sample-covariance form of regression scoring. When the conditional loading likelihood equations are satisfied, it equals $\Sigma_c^{-1}\Lambda_c$, with $\Sigma_c=\Lambda_c\Lambda_c^\top+\Psi_c$. At numerically stopped estimates this equality need only be approximate.
The simulated data also contain the generating factor values for each person. The generating and EM loading matrices have the same lower triangular leading block with positive diagonal, so the corresponding factor columns can be compared directly. For each column, prediction_table averages the squared difference between a fitted score and the generating value over all 600 people and takes its square root, the root mean squared prediction error reported as RMSE. The diagonal of the correlation matrix pairs each score column with its own generating factor.
1
2
3
4
5
6
7
prediction_table <- do.call(rbind, lapply(c("regression", "Bartlett"), function(method) {
predicted <- fa_scores(em_fit, method = method)$scores
data.frame(method = method, factor = 1:2,
RMSE = sqrt(colMeans((predicted - FA6$truth$latent)^2)),
correlation = diag(cor(predicted, FA6$truth$latent)))
}))
print(prediction_table, row.names = FALSE)
1
2
3
4
5
method factor RMSE correlation
regression 1 0.4999800 0.8659029
regression 2 0.4807229 0.8678600
Bartlett 1 0.5803737 0.8621172
Bartlett 2 0.5768052 0.8676394
The regression scores had root mean squared errors of 0.500 and 0.481, compared with 0.580 and 0.577 for the Bartlett scores. These four observed errors use fitted parameters and the particular factor values generated for these 600 people. Across people, the Bartlett error $B_B\epsilon_i$ contributes $B_B\Psi B_B^\top$ to the score covariance in addition to the factor covariance $\Phi$. Factor scores therefore need not have the same variance as the factors they predict. Correlation is insensitive to a positive rescaling. The correlations with the generating factors were close for the two methods, 0.866 and 0.868 for regression and 0.862 and 0.868 for Bartlett, despite the differences in prediction error.
A response covariance matrix can supply information about the scoring weights. To obtain a score for a particular person, the weights must multiply that person’s centered response vector. Removing the observed response matrix from a copy of em_fit illustrates which input the calculation requires.
1
2
3
covariance_only <- em_fit
covariance_only$data$Y <- NULL
print(tryCatch(fa_scores(covariance_only), error = function(e) conditionMessage(e)))
1
[1] "Individual responses are required for factor scores"
Different sets of individual responses can have the same means and covariance. Individual scoring requires the response row. The returned conditional_covariance treats the fitted means, loadings and covariance parameters as fixed, so it excludes their estimation uncertainty. The stats package provides regression and Bartlett factor scoring.
6.9 Comparing estimation routes and existing factor analysis results
How closely does the fitted covariance for FA6 agree with a fit obtained using stats::factanal()? The comparison supplies the six-response covariance matrix S with divisor 600, specifies two factors and requests unrotated loadings. For each set of uniquenesses the package obtains the loadings analytically, then searches over the uniquenesses to maximize likelihood. Its loadings refer to standardized responses, so the calculation below restores response units before forming reference_Sigma. The objects fa6_data and em_fit contain the divisor-600 data summary and the fitted EM model. The comparison is with the EM fit. Both log likelihoods refer to the same 600 people, and both loading matrices use the leading lower triangle with positive diagonal when their entries are compared.
1
2
3
4
5
6
7
8
9
10
reference <- stats::factanal(covmat = S, n.obs = 600, factors = 2, rotation = "none")
response_sd <- sqrt(diag(S))
reference_L <- sweep(unclass(reference$loadings), 1, response_sd, "*")
reference_psi <- reference$uniquenesses * response_sd^2
reference_Sigma <- fa_implied(reference_L, reference_psi)
print(c(full_logLik = -fa_criterion(reference_Sigma, fa6_data)$nll,
EM_logLik = em_fit$logLik,
covariance_gap = max(abs(reference_Sigma - em_fit$Sigma)),
identified_loading_gap = max(abs(orient_loadings(reference_L)$loadings - em_fit$loadings)),
minimum_reference_uniqueness = min(reference$uniquenesses), bound = .005))
1
2
3
4
full_logLik EM_logLik covariance_gap
-4.505966e+03 -4.505966e+03 1.291054e-04
identified_loading_gap minimum_reference_uniqueness bound
3.577381e-04 3.394668e-01 5.000000e-03
The full_logLik entry evaluates the package covariance with fa_criterion(), and EM_logLik reads the EM endpoint. Both rounded to $-4505.966$. The largest absolute difference between fitted covariance entries was 0.000129, and the largest difference between loadings after imposing the same rotation and sign convention was 0.000358. These are comparisons at the returned estimates. EM stopped on a small change in the log likelihood while the largest absolute partial derivative of the negative log likelihood was about 0.040. The smallest package uniqueness on the correlation scale was 0.33947, well above its lower bound of 0.005.
To see why response_sd enters twice in this calculation, let $D$ be the diagonal matrix of the six input standard deviations. The package analyzes $R=D^{-1}S_nD^{-1}$. If $L_c$ and $\Psi_c$ are the unrotated loadings and diagonal unique variances for $R$, the implied covariance in response units is
Thus the loading row of response $j$ is multiplied by its standard deviation once, and its uniqueness is multiplied by it twice. The covariance comparison can proceed as soon as both matrices use these units. For an individual loading, orient_loadings() then rotates the package columns to the convention used by EM. Even the request for unrotated output does not by itself select that convention.
Matching the fits also requires a common sample size, covariance divisor, number of factors and choice of rotation. The package applies its default lower bound of 0.005 to each standardized uniqueness. The joint fit searches in response units with no such individual bounds, and the EM fit uses strictly positive unique variances. All returned unique variances are positive in response units, and those from the concentrated and package fits lie strictly between their imposed correlation-scale bounds of 0.005 and 1.
A change of divisor illustrates why agreeing on the input still matters. Multiplying $S_n$ by $c>0$ leaves $R$ unchanged. On returning to response units, loadings scale by $\sqrt c$, unique variances by $c$ and the whole fitted covariance by $c$. In the normal discrepancy the added log determinants cancel, and $\operatorname{tr}[(c\Sigma)^{-1}cS_n]=\operatorname{tr}(\Sigma^{-1}S_n)$. The discrepancy therefore survives a change of divisor, even though the fitted loadings and unique variances have changed in response units.
Two observed test batteries
Two observed test batteries distributed with R extend the comparison with factanal() beyond the simulated sample. Only their summary matrices are available: ability.cov gives six tests on 112 people, and Harman74.cor gives 24 tests on 145 children. The R dataset documentation for ability.cov notes that its source gives inconsistent covariance and correlation matrices and that neither appears in the original paper; the corresponding documentation for Harman74.cor describes its tests. The calculation treats each supplied matrix as $S_n$, uses its documented sample size, and fits two factors to the first battery and four to the second. The available matrices suffice for fitting the covariance models. Individual factor scores would also require the original response rows. Treating the supplied matrices as $S_n$ is a declared convention for comparing the criteria; it does not recover or verify the covariance divisor used in the original raw-data analyses.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
textbook_inputs <- list(ability = datasets::ability.cov, Harman = datasets::Harman74.cor)
textbook_fits <- list()
textbook_table <- do.call(rbind, lapply(names(textbook_inputs), function(name) {
input <- textbook_inputs[[name]]
q <- if (name == "ability") 2 else 4
# Declare the supplied summary as the covariance criterion's input S_n.
data <- fa_data(covariance = input$cov, n = input$n.obs, divisor = input$n.obs)
fit <- fa_em(covariance = input$cov, n = input$n.obs,
divisor = input$n.obs, factors = q)
ref <- stats::factanal(covmat = input$cov, n.obs = input$n.obs, factors = q,
rotation = "none")
sd <- sqrt(diag(input$cov))
ref_Sigma <- fa_implied(sweep(unclass(ref$loadings), 1, sd, "*"),
ref$uniquenesses * sd^2)
textbook_fits[[name]] <<- list(book = fit, reference = ref, data = data)
data.frame(dataset = name, n = input$n.obs, p = ncol(input$cov), factors = q,
discrepancy = fit$discrepancy,
reference_discrepancy = fa_criterion(ref_Sigma, data)$discrepancy,
covariance_gap_scaled = max(abs((fit$Sigma - ref_Sigma) / outer(sd, sd))),
minimum_correlation_uniqueness = fit$boundary_distance,
maximum_absolute_nll_derivative = fit$max_abs_gradient,
status = fit$optimizer$reason)
}))
print(textbook_table, row.names = FALSE)
1
2
3
4
5
6
dataset n p factors discrepancy reference_discrepancy covariance_gap_scaled
ability 112 6 2 0.05718479 0.05716022 0.0016545390
Harman 145 24 4 1.71082202 1.71082147 0.0006173934
minimum_correlation_uniqueness maximum_absolute_nll_derivative status
0.05924327 0.02290628 small_loglik_change
0.23968223 0.01745501 small_loglik_change
For the ability tests, the EM and package discrepancies were 0.05718479 and 0.05716022. For the Harman tests, they were 1.71082202 and 1.71082147. The package discrepancies were smaller at the respective endpoints by about $2.5\times10^{-5}$ and $5.5\times10^{-7}$. Dividing each covariance difference by the product of the two input standard deviations makes the gaps comparable across test pairs. The largest absolute scaled gaps were 0.00165 and 0.000617. The minimum standardized uniquenesses of 0.05924 and 0.23968 belong to the EM fits. Both stopped on the change in log likelihood, with largest absolute derivatives of the negative log likelihood of 0.0229 and 0.0175 with respect to their packed loading and log-variance parameters.
Bounded uniquenesses and rotations
A unique-variance estimate equal to an imposed bound changes what the package is being asked to reproduce. For HEYWOOD3 the population covariance is reproduced exactly with first uniqueness zero. The bounded one-factor fit and stats::factanal() use the same correlation-scale lower bound in this comparison. The bounded fit uses the concentrated likelihood and the start adapted from factanal() (code/NOTICE.md), so its agreement checks that adaptation (Section E.3); the EM fit compared above uses the conditional-moment updates in Section 6.5 rather than the concentrated search in factanal(). The table reports all three first uniquenesses in the units of the first response variance.
1
2
3
4
5
6
7
8
9
10
11
12
reference_lower <- .005
boundary_reference <- stats::factanal(covmat = boundary_S, n.obs = 100, factors = 1,
rotation = "none")
reference_sd <- sqrt(diag(boundary_S))
boundary_reference_L <- sweep(unclass(boundary_reference$loadings), 1, reference_sd, "*")
boundary_reference_psi <- boundary_reference$uniquenesses * reference_sd^2
boundary_reference_Sigma <- fa_implied(boundary_reference_L, boundary_reference_psi)
print(data.frame(case = c("exact zero", "bounded fit", "reference at its bound"),
psi1 = c(0, heywood_psi[1], boundary_reference_psi[1]),
discrepancy = c(fa_criterion(boundary_S, boundary_data)$discrepancy,
fa_criterion(heywood_Sigma, boundary_data)$discrepancy,
fa_criterion(boundary_reference_Sigma, boundary_data)$discrepancy)))
1
2
3
4
case psi1 discrepancy
1 exact zero 0.00000 1.332268e-15
2 bounded fit 0.00405 2.226983e-05
3 reference at its bound 0.00405 2.226983e-05
Both bounded fits gave 0.00405 with discrepancy $2.227\times10^{-5}$. The two remaining package uniquenesses lie strictly between 0.005 and 1. Subtracting 0.005 from each measures its distance above the bound.
1
2
3
4
5
6
7
print(c(max_abs_free_gradient = max(abs(heywood_gradient[-1])),
bound_derivative = heywood_gradient[1],
at_bound = heywood_fit$uniquenesses[1] == reference_lower,
matched_covariance_gap = max(abs(heywood_Sigma - boundary_reference_Sigma)),
same_uniquenesses = identical(unname(heywood_fit$uniquenesses),
unname(boundary_reference$uniquenesses)),
other_reference_slack = min(boundary_reference$uniquenesses[-1] - reference_lower)))
1
2
3
4
max_abs_free_gradient bound_derivative at_bound matched_covariance_gap
1.754585e-08 8.951737e-03 1.000000e+00 9.769963e-15
same_uniquenesses other_reference_slack
0.000000e+00 4.416917e-01
The smaller of these distances was 0.4417. The maximum absolute covariance difference between the bounded fits was $9.77\times10^{-15}$ in response units. The zero under same_uniquenesses records a false result from identical(), which requires exact agreement.
Rotation poses a different comparison problem. For the two-factor FA6 solution, stats::varimax() and stats::promax() receive the same rotation_input as the implemented rotations. For each comparison, both column orders and all four sign choices are examined. The selected transformation minimizes the largest absolute loading difference.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
reference_varimax <- stats::varimax(rotation_input)
reference_promax <- stats::promax(rotation_input, m = 4)
align_two_columns <- function(reference, target) {
candidates <- list()
for (order in list(1:2, 2:1)) for (s1 in c(-1, 1)) for (s2 in c(-1, 1)) {
transform <- diag(2)[, order, drop = FALSE] %*% diag(c(s1, s2))
candidates[[length(candidates) + 1L]] <- list(transform = transform,
error = max(abs(reference %*% transform - target)))
}
candidates[[which.min(vapply(candidates, function(x) x$error, 0))]]
}
varimax_alignment <- align_two_columns(unclass(reference_varimax$loadings),
varimax_fit$loadings)
promax_alignment <- align_two_columns(unclass(reference_promax$loadings),
promax_fit$loadings)
reference_Phi <- solve(crossprod(reference_promax$rotmat))
print(c(varimax_criterion_gap =
abs(varimax_criterion(unclass(reference_varimax$loadings)) - varimax_fit$criterion),
varimax_aligned_gap = varimax_alignment$error,
promax_aligned_gap = promax_alignment$error,
promax_Phi_gap = max(abs(t(promax_alignment$transform) %*% reference_Phi %*%
promax_alignment$transform - promax_fit$Phi))))
1
2
varimax_criterion_gap varimax_aligned_gap promax_aligned_gap promax_Phi_gap
0 0 0 0
The first zero measures agreement of the varimax criteria. The next two measure agreement of the varimax and promax loadings after their respective alignments. The last zero compares the promax factor correlation matrices after applying the promax column order and signs to both axes of the reference matrix. The book’s varimax rotation is adapted from varimax(), and its promax rotation starts from that varimax solution (code/NOTICE.md), so these zeros check the adaptation (Section E.3). Rotating the fitted factors can clarify which responses load together while preserving their fitted covariance and likelihood.
Work and endpoints of the three estimation routes
The same FA6 sample also permits a comparison of the numerical work and returned estimates of all three estimation routes. The function route_row() evaluates each fitted covariance on the same likelihood and discrepancy scales. It also compares derivatives after expressing each fit in the same 17 working coordinates.
1
2
3
4
5
6
7
8
9
10
11
12
13
route_row <- function(route, loadings, uniquenesses, iterations,
function_evaluations, gradient_evaluations, status) {
Sigma <- fa_implied(loadings, uniquenesses)
# Use the same working coordinates to evaluate all three gradients.
identified <- orient_loadings(loadings)$loadings
data.frame(route = route, logLik = -fa_criterion(Sigma, fa6_data)$nll,
discrepancy = fa_criterion(Sigma, fa6_data)$discrepancy,
maximum_absolute_nll_derivative =
max(abs(objective$gr(fa_pack(identified, uniquenesses)))),
iterations = iterations, function_evaluations = function_evaluations,
gradient_evaluations = gradient_evaluations,
status = status, row.names = NULL)
}
Here orient_loadings() sets the loading orientation, and fa_pack() (Section 6.1) forms a common vector of 17 coordinates. The call objective$gr(fa_pack(identified, uniquenesses)) differentiates the negative log likelihood in those 17 coordinates. The table reports the largest component in absolute value.
1
2
3
4
5
6
7
8
9
10
11
12
route_table <- rbind(
route_row("joint", joint_fit$loadings, joint_fit$uniquenesses, joint_fit$run$iterations,
joint_fit$run$evaluations[[1]], joint_fit$run$evaluations[[2]],
joint_fit$run$message),
route_row("concentrated", conc_L, conc_psi, NA,
conc_fit$counts[[1]], conc_fit$counts[[2]],
conc_fit$message),
route_row("EM", em_fit$loadings, em_fit$uniquenesses, em_fit$optimizer$iterations,
em_fit$optimizer$evaluations[["objective"]],
em_fit$optimizer$evaluations[["gradient"]],
em_fit$optimizer$reason))
print(route_table, row.names = FALSE)
1
2
3
4
5
6
7
8
route logLik discrepancy maximum_absolute_nll_derivative iterations function_evaluations
joint -4505.966 0.002000337 3.287212e-05 22 24
concentrated -4505.966 0.002000337 3.893217e-04 NA 11
EM -4505.966 0.002000500 4.009171e-02 61 62
gradient_evaluations status
23 relative convergence (4)
11 CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH
1 small_loglik_change
The joint and concentrated discrepancies rounded to 0.002000337 and the EM discrepancy to 0.002000500. All three log likelihoods rounded to $-4505.966$. The double-dogleg fit reported 22 iterations with 24 function and 23 gradient evaluations. Its function counter excludes the final reevaluation made by dogleg_minimize(). Concentration used 11 evaluations each of function and gradient over six coordinates, each requiring an eigendecomposition. Its iteration count is unavailable. The 61 EM updates account for 62 function evaluations including the start. Its one counted gradient evaluation occurred at the endpoint. Evaluations by fa_result() and route_row() fall outside those counts.
On the common coordinates the largest absolute derivatives were $3.3\times10^{-5}$, $3.9\times10^{-4}$ and 0.040, respectively. These diagnostics distinguish endpoints that look identical at the printed likelihood precision.
Estimates across repeated samples
How much do the estimates vary across samples drawn from the same model? The function factor_replication() generates one matrix of 600 response rows and fits the joint, concentrated and EM procedures to that same matrix. The replication number selects a saved random-number stream: for example, factor_replication(1, streams) uses the first stream for all three fits. For each person, the function generates two independent standard normal factors and six independent errors, scales the errors by their unique standard deviations and combines the factors and errors using the generating loadings. The returned rows record estimates and stopping information for the three procedures.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
streams <- readRDS("data/source/ch06/study-streams.rds")
factor_replication <- function(replication, streams) {
assign(".Random.seed", streams[[replication]], envir = .GlobalEnv)
L <- matrix(c(.8, 0, .2, .8, .7, .2, .1, .7, .6, .3, .3, .6), 6, 2, byrow = TRUE)
psi <- c(.36, .36, .45, .45, .50, .50)
Z <- matrix(rnorm(600 * 2), 600, 2)
errors <- sweep(matrix(rnorm(600 * 6), 600, 6), 2, sqrt(psi), "*")
Y <- Z %*% t(L) + errors
# Fit all three procedures to this response matrix.
procedures <- list(
joint = function() {
f <- fa_joint(fa_data(Y), 2)
list(par = f$run$par, optimizer = list(converged = f$run$convergence == 0L,
reason = f$run$message, iterations = f$run$iterations),
max_abs_gradient = max(abs(f$gr(f$run$par))),
Sigma = fa_implied(f$loadings, f$uniquenesses),
loadings = orient_loadings(f$loadings)$loadings, uniquenesses = f$uniquenesses)
},
concentrated = function() {
f <- fa_concentrated(fa_data(Y)$S, 2)
L <- sweep(f$loadings, 1, f$sds, "*")
psi <- f$uniquenesses * f$sds^2
list(par = f$uniquenesses,
optimizer = list(converged = f$converged, reason = f$message,
iterations = NA_integer_),
max_abs_gradient = max(abs(fa_concentrated_gradient(f$uniquenesses, f$correlation, 2))),
Sigma = fa_implied(L, psi),
loadings = orient_loadings(L)$loadings, uniquenesses = psi)
},
EM = function() fa_em(Y, factors = 2))
# Record estimates and the stopping rule for each method.
do.call(rbind, lapply(names(procedures), function(route) {
attempt <- tryCatch(procedures[[route]](), error = function(e) e)
row <- data.frame(replication = replication, route = route, converged = FALSE,
status = "error", maximum_absolute_derivative = NA_real_,
covariance12 = NA_real_, loading11 = NA_real_,
uniqueness1 = NA_real_, rms_difference_across_covariance_entries = NA_real_,
iterations = NA_integer_)
if (inherits(attempt, "error")) {
row$status <- conditionMessage(attempt)
} else if (is.null(attempt$par)) {
row$status <- "missing_parameter_vector"
} else {
row$converged <- attempt$optimizer$converged
row$status <- attempt$optimizer$reason
row$maximum_absolute_derivative <- attempt$max_abs_gradient
row$covariance12 <- attempt$Sigma[1, 2]
row$loading11 <- attempt$loadings[1, 1]
row$uniqueness1 <- attempt$uniquenesses[1]
row$rms_difference_across_covariance_entries <-
sqrt(mean((attempt$Sigma - fa_implied(L, psi))^2))
row$iterations <- attempt$optimizer$iterations
}
row
}))
}
The concentrated fit is returned to response units. Each fit with a non-null parameter vector supplies entry $(1,2)$ of its implied covariance to covariance12, whether or not its stopping rule was satisfied. A separate converged flag controls inclusion in the summary. If a fit returns no parameter vector (attempt$par is NULL), its row receives the status missing_parameter_vector and retains converged = FALSE.
In the saved results for replication 1, the joint, concentrated and EM estimates of this covariance were 0.1435055, 0.1435054 and 0.1435162. The generating covariance is $0.8\times0.2+0\times0.8=0.16$. The completed rows give the frequency of each stopping message for each method.
1
2
study_results <- read.csv("data/derived/ch06/replications.csv")
print(with(study_results, table(route, status)))
1
2
3
4
5
status
route CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH relative convergence (4) small_loglik_change
concentrated 200 0 0
EM 0 0 200
joint 0 200 0
Each method met its own stopping rule in 200 of 200 samples. The joint fit reported relative convergence, the concentrated fit a small relative function reduction, and EM a small change in log likelihood. The following selection uses the convergence flag in each of the 600 rows.
1
2
3
other_stops <- subset(study_results, !converged)
print(other_stops[, c("replication", "converged", "status",
"maximum_absolute_derivative")], row.names = FALSE)
1
2
3
[1] replication converged status
[4] maximum_absolute_derivative
<0 rows> (or 0-length row.names)
The selection contains zero rows. The meaning of maximum_absolute_derivative depends on the row’s method and stopping status. For the joint fit it is a derivative of the half-discrepancy in the 17 original-scale coordinates, for the concentrated fit a derivative of the discrepancy in the six standardized uniquenesses, and for EM a derivative of the negative log likelihood in the 17 packed coordinates.
The four summary rows per method use the converged replications for that method. Here each mean uses all 200 samples. For covariance, loading and uniqueness, the mean error is the mean estimate minus the generating value. A Monte Carlo standard error measures the sampling uncertainty of that mean error across replications. It is the sample standard deviation of the estimates divided by $\sqrt{200}$.
For the fourth row, factor_replication() first computes a distance within each sample by taking the square root of the mean squared difference across all 36 entries of the fitted and population covariance matrices. The distance is zero for an exact match to the population covariance. It is a measure of estimation error, not an estimate of a separate population parameter. In that row, the labels estimand and mean_error refer to the selected distance measure and its average; the average is not a bias estimate for a covariance entry. The following calculation reproduces the rows distributed in data/derived/ch06/study-summary.csv.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
study_summary <- do.call(rbind, lapply(unique(study_results$route), function(route) {
all <- study_results[study_results$route == route, ]
valid <- all[all$converged, ]
do.call(rbind, lapply(c("covariance12", "loading11", "uniqueness1",
"rms_difference_across_covariance_entries"), function(estimand) {
truth <- c(covariance12 = .16, loading11 = .8, uniqueness1 = .36,
rms_difference_across_covariance_entries = 0)[estimand]
estimates <- valid[[estimand]]
data.frame(route = route, estimand = estimand, attempted = nrow(all),
successful = nrow(valid),
failures = sum(!all$converged), mean = mean(estimates),
mean_error = mean(estimates) - truth,
mean_error_mcse = sd(estimates) / sqrt(length(estimates)))
}))
}))
print(study_summary, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
route estimand attempted successful failures mean mean_error
joint covariance12 200 200 0 0.15801653 -0.0019834717
joint loading11 200 200 0 0.79525425 -0.0047457492
joint uniqueness1 200 200 0 0.35987129 -0.0001287087
joint rms_difference_across_covariance_entries 200 200 0 0.04374021 0.0437402091
concentrated covariance12 200 200 0 0.15801652 -0.0019834756
concentrated loading11 200 200 0 0.79525384 -0.0047461646
concentrated uniqueness1 200 200 0 0.35987211 -0.0001278887
concentrated rms_difference_across_covariance_entries 200 200 0 0.04374023 0.0437402267
EM covariance12 200 200 0 0.15804244 -0.0019575550
EM loading11 200 200 0 0.79500383 -0.0049961692
EM uniqueness1 200 200 0 0.36026211 0.0002621141
EM rms_difference_across_covariance_entries 200 200 0 0.04373820 0.0437382026
mean_error_mcse
0.0028604312
0.0034606207
0.0040611419
0.0008550513
0.0028604322
0.0034606353
0.0040611845
0.0008550495
0.0028602374
0.0034527406
0.0040464404
0.0008551844
In joint, concentrated and EM order, the covariance mean errors were $-0.0019835$, $-0.0019835$ and $-0.0019576$, with Monte Carlo standard errors about 0.00286. The first loading had generating value 0.8 and mean errors $-0.0047457$, $-0.0047462$ and $-0.0049962$, with standard errors about 0.00346. For the first uniqueness, whose generating value was 0.36, the mean errors were $-0.00013$, $-0.00013$ and $0.00026$, with standard errors about 0.00405. Each mean error for these three parameters lies within two of its own Monte Carlo standard errors of zero. This describes the precision of the simulation averages; it does not establish that the estimators are unbiased. The average covariance distance was about 0.04374 for every method, with standard error about 0.00086.
A comparison between methods uses estimates paired by replication ID. For the first covariance, the within-sample difference is $d_r=\widehat\Sigma_{12,r}^{\rm EM}-\widehat\Sigma_{12,r}^{\rm joint}$ for sample $r$. The standard error of the mean difference is the sample standard deviation of the 200 values of $d_r$ divided by $\sqrt{200}$. For the first covariance, the mean paired difference was 0.0000259 with standard error 0.00000149.