Vector and Matrix Derivatives: Essential Tools for Optimization
Before differentiating an objective function, we identify which vector or matrix can vary and which quantities stay fixed. This reference first defines the gradient convention, then groups formulas by the variable we differentiate. Each formula applies only when its dimensions and domain conditions are satisfied.
Dimensions and Notation
For the vector and trace identities below, we use real column vectors and square matrices:
a,b,x∈Rn,A,B,X∈Rn×n. Scroll to see the full equation →
For a function that returns a scalar, the gradient has the same dimensions as the variable we differentiate. We use df=(∇af)⊤da for a vector and df=Tr((∇Af)⊤dA) for a matrix. In the matrix case, we treat the entries as independent coordinates. When a function returns a vector, we instead use its Jacobian: rows correspond to output coordinates and columns to input coordinates. All other quantities stay fixed during differentiation.
Vector Derivatives
In the first group, the vector is the variable and the other factors are fixed. Inner-product derivatives give the linear terms; quadratic expressions also require accounting for both occurrences of the vector.
∂a∂a⊤b=b, Scroll to see the full equation →
∂a∂b⊤a=b, Scroll to see the full equation →
∂a∂a⊤Aa=(A+A⊤)a, Scroll to see the full equation →
∂a∂(Aa)=A, Scroll to see the full equation →
Matrix Derivatives
We now let the matrix vary. The gradient must have the same dimensions as that matrix; this requirement helps check the factor order and transposes in the formulas below.
∂A∂a⊤Ab=ab⊤, Scroll to see the full equation →
∂A∂a⊤A⊤b=ba⊤, Scroll to see the full equation →
∂A∂a⊤A⊤Aa=2Aaa⊤, Scroll to see the full equation →
∂A∂Tr(A)=I, Scroll to see the full equation →
∂X∂Tr(A⊤X)=∂X∂Tr(X⊤A)=A, Scroll to see the full equation →
∂X∂Tr(AXB)=A⊤B⊤, Scroll to see the full equation →
∂X∂Tr(B⊤X⊤A)=AB⊤. Scroll to see the full equation →
L2 Norm Derivatives
Squared-error objectives lead to the following derivatives. For matrix residuals, we use the Frobenius norm, whose square is the sum of the squared entries; for a single-column residual, it is the Euclidean norm. In the first formula, let Y∈Rm×r, W∈Rm×n, and X∈Rn×r:
∂W∂∥Y−WX∥F2=−2(Y−WX)X⊤. Scroll to see the full equation →
In the second formula, let Y∈Rm×r, X∈Rm×n, and W∈Rn×r:
∂W∂∥Y−XW∥F2=−2X⊤(Y−XW). Scroll to see the full equation →
Other Common Derivatives
The logarithmic formulas require x⊤a>0 and det(A)>0, respectively. The determinant condition also ensures that A is invertible.
∂x∂ln(x⊤a)=x⊤aa, Scroll to see the full equation →
∂A∂ln(det(A))=(A−1)⊤, Scroll to see the full equation →
∂A∂∥A∥F2=2A, Scroll to see the full equation →
where ∥A∥F denotes the Frobenius norm of A.
Useful Resources
For a broader collection of matrix identities and derivatives, see the
Matrix Cookbook.
For additional background, see: