Post

Matrix differentiation

A parameter can enter several positions of a covariance matrix, so changing it affects more than one term in a normal likelihood. The derivative must account for these changes together. Matrix differentiation provides the identities needed to follow the effect of a parameter through a mean vector or covariance matrix. This appendix is a reference for those derivations, with a normal likelihood showing how the matrix expressions relate to the observed scores.

A.1 Differentials of log determinants and matrix inverses

Let $A$ be a symmetric positive definite $p\times p$ covariance matrix of a person’s vector of test scores. To specify which entries change together, choose a symmetric matrix $H$ of the same size and form $A(t)=A+tH$. The scalar $t$ measures how far the covariance moves in that direction. For example, a change in the covariance of two test scores appears in both symmetric positions of $H$. For a differentiable function $f$ of the covariance, varying $t$ now determines the change in $f$. Its differential at $A$, applied to $H$, is the slope

\[df_A[H]=\left.\frac{d}{dt}f(A+tH)\right|_{t=0}.\]

This definition applies entry by entry when $f$ returns a matrix. For the inverse to exist along the path near zero, it suffices that $A$ be nonsingular. Its determinant is then nonzero and, by continuity, remains nonzero for sufficiently small $\vert t\vert $.

Write $P(t)=A(t)^{-1}$ and $P=P(0)$. What change in the inverse compensates for the change in $A(t)$? Their product equals the identity matrix $I_p$ whenever $A(t)$ is nonsingular, so its derivative is zero. The product rule at zero gives

\[HP+A P'(0)=0,\qquad P'(0)=-A^{-1}HA^{-1}.\]

The first term differentiates the covariance with the inverse fixed at its initial value. To isolate the derivative of the inverse in the second term, multiply on the left by $A^{-1}$. This leaves one inverse on each side of $H$. In differential notation, $d(A^{-1})=-A^{-1}(dA)A^{-1}$. For a covariance, choose symmetric $H$ and a symmetric positive definite $A$. The smallest eigenvalue of $A$ is positive, so a sufficiently short step in either direction gives another positive definite covariance. A central difference for a covariance likelihood requires positive definite matrices at both evaluation points.

Along this positive definite path, the determinant is positive, so its real logarithm is defined. Factor out $A$ and put $M=A^{-1}H$. Then $\det(A+tH)=\det(A)\det(I_p+tM)$. To find the slope at zero, expand the second determinant by linearity in each column. The constant term is one. A term of first order in $t$ takes column $j$ from $M$ and every other column from $I_p$. Its coefficient is $M_{jj}$ because the other identity columns already occupy all rows except row $j$. Summing over the possible choices of column gives the trace, $\operatorname{tr}(M)$. All terms that select two or more columns from $M$ have zero derivative at the origin. Since $\det(I_p)=1$, taking the logarithm gives

\[\left.\frac{d}{dt}\log\det(A+tH)\right|_{t=0} =\operatorname{tr}(A^{-1}H).\]

For the two test scores, let $y$ be the observed pair, $\mu$ its model mean, and $r=y-\mu=(1,-0.5)^\top$ the residual in this example. With $\mu$ fixed, this person’s negative log likelihood under a bivariate normal model is

\[-\ell(A;r)=\tfrac12\{2\log(2\pi)+\log\det A+r^\top A^{-1}r\}.\]

The log determinant contributes the trace term $\operatorname{tr}(A^{-1}H)$ to the derivative. The residual remains the same on both sides of the quadratic form, so only the inverse inside it changes. Write $u=A^{-1}r$. By symmetry, $r^\top A^{-1}=u^\top$, and the derivative of the quadratic form is $-u^\top H u$. For a scalar covariance parameter $\theta$, take $H=\partial A/\partial\theta$ at the parameter value of interest. Combining the terms gives

\[\frac{\partial(-\ell)}{\partial\theta} =\tfrac12\{\operatorname{tr}(A^{-1}H)-u^\top H u\}.\]

Reversing the sign gives the derivative of this person’s log likelihood.

Run the displayed code in order in one R session, as in code/examples/appendix-matrix.R. Suppose the two variances are 2 and 1 and the covariance is 0.3. In the direction $H$, named D in R, a small positive $t$ raises the variances by $0.2t$ and $0.1t$ and lowers their covariance by $0.4t$. For any covariance S along this path, chol(S) gives an upper triangular matrix $U$ satisfying $U^\top U=S$. Its diagonal entries therefore give $\log\det S=2\sum_j\log U_{jj}$. Here S is symmetric and positive definite.

1
2
3
4
5
6
7
8
9
A <- matrix(c(2,.3,.3,1),2)
D <- matrix(c(.2,-.4,-.4,.1),2)
residual <- c(1,-.5)
logdet <- function(S) 2*sum(log(diag(chol(S))))
normal_nll <- function(S,r) (length(r)*log(2*pi)+logdet(S)+sum(r*solve(S,r)))/2
quadratic_derivative <- function(S,r,D) {
  u <- solve(S,r)
  -sum(u*(D%*%u))
}

In normal_nll(), solve(S,r) gives the vector $u$ at S. Multiplying its entries by the corresponding residuals and summing gives the quadratic form $r^\top S^{-1}r$, which measures squared distance using the inverse covariance. The function quadratic_derivative() computes the change in that distance per unit step along D.

Compare the analytic derivatives of the log determinant, one entry of the inverse and the negative log likelihood with central differences along this same covariance direction. Varying the step size shows how the numerical approximation approaches each derivative.

1
2
3
4
5
6
7
8
9
exact <- c(logdet=sum(diag(solve(A,D))),
  # Take entry (1, 2) of the derivative of the precision matrix.
  inverse_12=(-solve(A)%*%D%*%solve(A))[1,2],
  nll=(sum(diag(solve(A,D)))+quadratic_derivative(A,residual,D))/2)
quantities <- function(S) c(logdet=logdet(S),inverse_12=solve(S)[1,2],
  nll=normal_nll(S,residual))
print(do.call(rbind,lapply(10^-(1:7),function(h)
  data.frame(quantity=names(exact),step=h,analytic=exact,
    numerical=(quantities(A+h*D)-quantities(A-h*D))/(2*h)))))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
              quantity  step    analytic   numerical
logdet          logdet 1e-01  0.33507853  0.33545009
inverse_12  inverse_12 1e-01  0.26205422  0.26258033
nll                nll 1e-01 -0.05579617 -0.05614183
logdet1         logdet 1e-02  0.33507853  0.33508224
inverse_121 inverse_12 1e-02  0.26205422  0.26205947
nll1               nll 1e-02 -0.05579617 -0.05579961
logdet2         logdet 1e-03  0.33507853  0.33507857
inverse_122 inverse_12 1e-03  0.26205422  0.26205427
nll2               nll 1e-03 -0.05579617 -0.05579620
logdet3         logdet 1e-04  0.33507853  0.33507853
inverse_123 inverse_12 1e-04  0.26205422  0.26205422
nll3               nll 1e-04 -0.05579617 -0.05579617
logdet4         logdet 1e-05  0.33507853  0.33507853
inverse_124 inverse_12 1e-05  0.26205422  0.26205422
nll4               nll 1e-05 -0.05579617 -0.05579617
logdet5         logdet 1e-06  0.33507853  0.33507853
inverse_125 inverse_12 1e-06  0.26205422  0.26205422
nll5               nll 1e-06 -0.05579617 -0.05579617
logdet6         logdet 1e-07  0.33507853  0.33507853
inverse_126 inverse_12 1e-07  0.26205422  0.26205422
nll6               nll 1e-07 -0.05579617 -0.05579617

In exact, solve(A,D) supplies $A^{-1}H$ for the trace, and [1,2] selects entry $(1,2)$ of the derivative of the precision matrix $A^{-1}$. These formula values fill the analytic column. For each step $h$, quantities() evaluates the three original functions at $A+hH$ and $A-hH$. Subtracting the second set of values from the first and dividing by $2h$ gives the numerical column. The label nll in the quantity column identifies the derivative of the negative log likelihood.

At $h=10^{-1}$, the central differences for the log determinant and the inverse entry are both above their analytic derivatives, and the one for the negative log likelihood is more negative. At $h=10^{-4}$, the three pairs agree to the displayed precision. The log determinant increases along this path. The squared distance falls fast enough to outweigh that increase. The derivative $-0.05579617$ means that a sufficiently small positive step along $D$ raises the likelihood of this person’s scores. Now consider a separate covariance matrix with all four entries equal to one.

1
print(tryCatch(logdet(matrix(1,2,2)),error=conditionMessage))
1
[1] "the leading minor of order 2 is not positive"

With unit variances and covariance one, the two centered scores would have to coincide. The covariance matrix has two identical rows, and the remaining diagonal quantity in the second Cholesky step is $1-1^2=0$. Its determinant is zero, so neither a finite log determinant nor a precision matrix exists for this singular covariance. The base package provides the Cholesky decomposition and the linear system solves used in this calculation.

A.2 Trace identities and derivatives of quadratic forms

When a covariance parameter changes several entries of a matrix, how do their contributions combine in one derivative of the negative log likelihood? A trace expresses that scalar derivative as a sum. To see how the matrices in a product can be rearranged inside a trace, let $A$ have $p$ rows and $q$ columns and let $B$ have $q$ rows and $p$ columns. Diagonal entry $i$ of $AB$ is the sum across row $i$ of $A$ paired with column $i$ of $B$. Taking the trace gives

\[\operatorname{tr}(AB) =\sum_{i=1}^{p}\sum_{j=1}^{q}a_{ij}b_{ji} =\sum_{j=1}^{q}\sum_{i=1}^{p}b_{ji}a_{ij} =\operatorname{tr}(BA).\]

There are $p$ diagonal entries in $AB$ and $q$ in $BA$, but summing either diagonal counts each product $a_{ij}b_{ji}$ once. With three matrices whose dimensions permit the products, treating $BC$ as one matrix gives $\operatorname{tr}(ABC)=\operatorname{tr}(BCA)$. Repeating the rotation gives $\operatorname{tr}(CAB)$. Their cyclic order is preserved throughout. Interchanging just $B$ and $C$ would require a separate justification.

A quadratic form $x^\top Bx$ is itself a scalar. Here $x$ is a real column vector and $B$ is a square matrix with one row for each entry of $x$. Suppose both depend on a parameter. Differentiating the left copy of $x$, then $B$, then the right copy of $x$ gives

\[d(x^\top Bx)=(dx)^\top Bx+x^\top(dB)x+x^\top B\,dx =(dx)^\top(B+B^\top)x+x^\top(dB)x .\]

The last term of the first expression is a scalar, so taking its transpose puts $dx$ on the left and changes $B$ to $B^\top$. For the two test scores, set $x=r$, the person’s residual vector, and take $B=A^{-1}$, where $A$ is again the test-score covariance matrix. At fixed $r$, only the middle matrix changes. Substituting $d(A^{-1})=-A^{-1}(dA)A^{-1}$ gives $-u^\top(dA)u$ with $u=A^{-1}r$. This is the term that quadratic_derivative() computes for the covariance direction passed to it.

With the observed scores fixed, change their model means by $tv$ as their covariance changes from $A$ to $A+tD$. The residual at $t=0$ is $r=(1,-0.5)^\top$, so the new residual is $r-tv$. The two vector terms change the quadratic form by $-2v^\top u$ per unit of $t$ at zero. The normal negative log likelihood multiplies the quadratic form by one half, and its log determinant depends only on the covariance. The derivative for the joint change is therefore

\[\left.\frac{d}{dt}\{-\ell(A+tD;r-tv)\}\right|_{t=0} =-v^\top u+\tfrac12\{\operatorname{tr}(A^{-1}D)-u^\top D u\}.\]

The calculation reuses A, D, residual and normal_nll() defined in Section A.1, in the same R session, with $v=(0.25,-0.1)^\top$. At the positive endpoint of the central difference, normal_nll() receives residual-h*v. At the negative endpoint it receives residual+h*v because the mean has moved in the opposite direction.

1
2
3
4
5
6
7
8
v <- c(.25,-.1)
u <- solve(A,residual)
mean_term <- -sum(v*u)
covariance_term <- (sum(diag(solve(A,D)))-sum(u*(D%*%u)))/2
h <- 1e-5
print(c(from_mean=mean_term,from_covariance=covariance_term,sum=mean_term+covariance_term,
  symmetric_difference=(normal_nll(A+h*D,residual-h*v)-
    normal_nll(A-h*D,residual+h*v))/(2*h)))
1
2
           from_mean      from_covariance                  sum symmetric_difference 
         -0.21858639          -0.05579617          -0.27438256          -0.27438256 

The from_mean entry is $-0.21858639$ as the two means move toward the observed scores. The from_covariance entry is $-0.05579617$ for the change in the covariance matrix at fixed means. Both changes therefore increase this person’s likelihood locally. At $h=10^{-5}$, the central difference along the joint path gives the same negative log likelihood derivative as their sum, $-0.27438256$, to the printed precision.

For fixed symmetric $B$, the gradient with respect to $x$ is $2Bx$. What happens if the matrix in the quadratic form is nonsymmetric? Fix $B=\left(\begin{smallmatrix}1&-1\cr 2&3\end{smallmatrix}\right)$ and evaluate the derivative with respect to $x$ at the same residual vector. The coefficient of $dx$ in the differential gives the column gradient $(B+B^\top)x$. Its first component can also be read from the polynomial $x^\top Bx=x_1^2+x_1x_2+3x_2^2$. The two off-diagonal entries contribute $-1$ and $2$ to the coefficient of $x_1x_2$, so the first partial derivative is $2x_1+x_2$.

1
2
B <- matrix(c(1,2,-1,3),2)
print(cbind(correct=drop((B+t(B))%*%residual),twice_Bx=2*drop(B%*%residual)))
1
2
3
     correct twice_Bx
[1,]     1.5        3
[2,]    -2.0        1

At $x_1=1$ and $x_2=-0.5$, that partial derivative is $1.5$. The second partial derivative, $x_1+6x_2$, is $-2$. These are the entries of correct. For this vector, $Bx=(1.5,0.5)^\top$ and $B^\top x=(0,-2.5)^\top$. The column twice_Bx doubles the first vector and gives $(3,1)^\top$.

Return to the symmetric test-score covariance $A$ and fix the mean and both variances. A change in the single free covariance $a=A_{12}=A_{21}$ moves two matrix entries. To find its coefficient, write the quadratic term in the covariance differential as $u^\top(dA)u=\operatorname{tr}(uu^\top dA)$ by cyclic rotation. The full differential at this person’s residual is then

\[d(-\ell)=\operatorname{tr}(G^\top dA),\qquad G=\tfrac12(A^{-1}-uu^\top).\]

The trace pairs each entry of $dA$ with the corresponding entry of the symmetric matrix $G$. Per unit change in $a$, off_diagonal has ones in positions $(1,2)$ and $(2,1)$ and zeros on the diagonal. The coefficient of $da$ is consequently $G_{12}+G_{21}=2G_{12}$, since $G$ is symmetric.

1
2
3
off_diagonal <- matrix(c(0,1,1,0),2)
print(c(free_covariance_derivative=(sum(diag(solve(A,off_diagonal)))+
  quadratic_derivative(A,residual,off_diagonal))/2))
1
2
free_covariance_derivative 
                 0.2527343 

The derivative of the negative log likelihood with respect to the free covariance is $0.2527343$. For the log likelihood the derivative is $-0.2527343$, so increasing the covariance alone makes this pair of scores less likely at the specified point.

In a confirmatory factor model, a free covariance between two factors likewise changes two entries of the factor covariance matrix. Each loading in $\Lambda$ gives the change in the conditional mean of its score per unit of the corresponding factor, with the other factors fixed. The unique variance measures the remaining variation in a score at fixed factor values, in squared score units. With these loadings and unique variances fixed, a change $d\Phi$ in the factor covariance gives $dA=\Lambda(d\Phi)\Lambda^\top$. Both symmetric entries of $d\Phi$ therefore enter the derivative of the negative log likelihood with respect to that one parameter. The matrix products and transposes in this calculation are available in the base package.

A.3 Vectorization and Kronecker products

One factor covariance can affect both the variance of a test score and its covariance with another score. To collect the derivatives of those quantities in a matrix, each output entry needs a row index. Vectorization assigns that index by stacking the columns of a matrix in order. For a rectangular example, let

\[X=\begin{pmatrix}1&3&5\\2&4&6\end{pmatrix}, \qquad \operatorname{vec}(X)=(1,2,3,4,5,6)^\top .\]

The first two positions contain the first column. Position three returns to row one for the start of the second column. In general, for a matrix with $m$ rows, the entry in row $i$ and column $j$ takes position $i+(j-1)m$, because each preceding column supplies $m$ entries. In R, c(X) returns the entries of X in this column order.

How does multiplying $X$ on both sides change the stacked vector? Use the two-by-two test-score covariance $A$ and a new three-by-two matrix $B$ with entries $b_{jk}$. Write $x_j$ for column $j$ of $X$. The first column of $AXB$ is $b_{11}Ax_1+b_{21}Ax_2+b_{31}Ax_3$. A block row with blocks $b_{11}A$, $b_{21}A$ and $b_{31}A$ produces that column when multiplied by $\operatorname{vec}(X)$. The next block row uses the second column of $B$ in the same way. These two block rows form the Kronecker product $B^\top\otimes A$, which replaces each entry of $B^\top$ by that entry times $A$. Stacking the resulting columns gives

\[\operatorname{vec}(AXB)=(B^\top\otimes A)\operatorname{vec}(X).\]

Here the matrix on the right has four rows and six columns. The calculation below uses A from the likelihood example in Section A.1 and specifies both X and B.

1
2
3
4
5
6
X <- matrix(1:6,2,3)
B <- matrix(c(1,0,-1,2,1,.5),3,2)
direct <- A%*%X%*%B
vectorized <- kronecker(t(B),A)%*%c(X)
print(data.frame(index=seq_along(direct),row=c(row(direct)),column=c(col(direct)),
  matrix_product=c(direct),kronecker=c(vectorized)))
1
2
3
4
5
  index row column matrix_product kronecker
1     1   1      1          -9.20     -9.20
2     2   2      1          -5.20     -5.20
3     3   1      2          18.30     18.30
4     4   2      2          13.25     13.25

The first column of B is $(1,0,-1)^\top$, so $X$ times that column gives $x_1-x_3=(-4,-4)^\top$. Row two of $A$ then gives $0.3(-4)+1(-4)=-5.20$. The two columns of computed values therefore agree at index two, which represents row two, column one of $AXB$. The last two entries come from the second column of $AXB$.

For a symmetric two-by-two matrix $K$, column stacking uses four positions although there are only three distinct entries. Let $\operatorname{vech}(K)=(k_{11},k_{21},k_{22})^\top$ list the lower triangle, reading down each column. The duplication matrix $D_2$ maps this three-element vector to $\operatorname{vec}(K)$. Its middle column places $k_{21}$ in positions two and three, since $k_{12}=k_{21}$. The elimination matrix $L_2$ selects positions one, two and four from the stacked vector to recover the lower triangle. In the code, duplication is the four-by-three matrix $D_2$, and elimination selects three rows of the four-dimensional identity matrix to form $L_2$.

1
2
3
duplication <- rbind(c(1,0,0),c(0,1,0),c(0,1,0),c(0,0,1))
elimination <- diag(4)[c(1,2,4),,drop=FALSE]
print(elimination%*%duplication)
1
2
3
4
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1

The printed product $L_2D_2$ acts on the three distinct entries. Its middle diagonal one shows what happens to a covariance that was copied into two positions. Selecting the lower triangle returns its original value once. This identity does not make $D_2L_2$ the four-dimensional identity: duplicating a selected lower triangle recovers the original full matrix only when that matrix is symmetric.

Now let $\Phi$ be the covariance matrix of two factors and let the rows of $\Lambda$ give their loadings for two observed scores. The common-factor part of the test-score covariance matrix is $C=\Lambda\Phi\Lambda^\top$. With fixed loadings, a change $d\Phi$ gives $dC=\Lambda(d\Phi)\Lambda^\top$. Suppose the first factor variance and the covariance between factors are free, and collect them in $\eta=(\phi_{11},\phi_{21})^\top$. Here $\phi_{11}$ measures variation in the first factor across people, in squared factor units; $\phi_{21}$ measures how the two factors vary together, in the product of their units. Their values must satisfy the positive definiteness constraint on $\Phi$ along the path considered here.

The second factor variance is fixed. Its change is zero even when its value is positive. The matrix $S$ inserts the two free changes into the lower triangle in the order $(11,21,22)$, so $\operatorname{vech}(d\Phi)=S\,d\eta$. Duplication and the product identity then give

\[S=\begin{pmatrix}1&0\\0&1\\0&0\end{pmatrix}, \qquad d\operatorname{vec}(C)=J\,d\eta,\qquad J=(\Lambda\otimes\Lambda)D_2 S .\]

The Jacobian $J$ has four rows for the stacked entries of the test-score covariance and two columns for the free parameters. Its first column gives their derivatives with respect to $\phi_{11}$, and its second column gives their derivatives with respect to the single parameter shared by $\phi_{21}$ and $\phi_{12}$.

Consider a path along which the first factor variance increases at rate $0.2$ and the factor covariance decreases at rate $0.4$. The matrix perturbation specifies this direction, with diagonal entries $0.2$ and zero and off-diagonal entries $-0.4$. It need not be positive definite. Adding this direction to a positive definite factor covariance preserves positive definiteness when its multiplier is sufficiently small, with either sign. The first score has loadings $(0.8,0)$ and the second has loadings $(0.5,0.7)$. In J_times_change, the two free changes multiply the corresponding columns of the Jacobian. The direct column calculates the change in matrix form and stacks the result for comparison.

1
2
3
4
5
6
7
8
# Select changes in the first factor variance and the shared factor covariance.
selection <- diag(3)[,1:2,drop=FALSE]
change <- c(.2,-.4)
perturbation <- matrix(duplication%*%selection%*%change,2,2)
Lambda <- matrix(c(.8,0,.5,.7),2,2,byrow=TRUE)
jacobian <- kronecker(Lambda,Lambda)%*%duplication%*%selection
print(cbind(J_times_change=drop(jacobian%*%change),
  direct=c(Lambda%*%perturbation%*%t(Lambda))))
1
2
3
4
5
     J_times_change direct
[1,]          0.128  0.128
[2,]         -0.144 -0.144
[3,]         -0.144 -0.144
[4,]         -0.230 -0.230

Only the first factor contributes to the first score, so its variance changes by $0.8^2(0.2)=0.128$ per unit step. For the covariance between scores, the change is $0.8[0.5(0.2)+0.7(-0.4)]=-0.144$. Rows two and three give this same change for entries $(2,1)$ and $(1,2)$ of the test-score covariance matrix. For the second score, the variance contribution from the first factor increases by $0.5^2(0.2)=0.050$. The cross term changes by $2(0.5)(0.7)(-0.4)=-0.280$. These sum to the fourth entry, $-0.230$. Thus the variance of the second score decreases along this path even though the variance of the second factor is fixed. With unique variances fixed, these are also the changes in the full test-score covariance matrix.

For $p$ observed scores and $q$ factors, $\Lambda$ has $p$ rows and $q$ columns. Forming $\Lambda\otimes\Lambda$ explicitly requires a matrix with $p^2$ rows and $q^2$ columns, or $p^2q^2$ entries. The Jacobian is useful when a separate column is needed for each free parameter. For one specified direction, the direct calculation first forms the $p$-by-$q$ matrix $\Lambda\,d\Phi$ and then multiplies by $\Lambda^\top$. The resulting $p$-by-$p$ matrix already contains the changes in all score variances and covariances. For one person’s residual $r$, the matrix $G=(A^{-1}-uu^\top)/2$ uses the full model covariance $A$ and $u=A^{-1}r$. At fixed means and unique variances, $dA=dC$, so the corresponding negative log likelihood differential is $\operatorname{tr}(G^\top dC)$. The base package provides the Kronecker product, and matrixcalc provides duplication and elimination matrices.

This post is licensed under CC BY-NC 4.0 by the author.