AI Wiki中文/EN

Matrix calculus

矩阵微积分

Derive a matrix-shaped gradient and check its finite-step remainder.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Which entries should a weight matrix change?

A model predicts two measurements from two input features. Its four weights sit in a matrix. Training still needs one answer: how should each weight move to lower the total error? Matrix calculus packages those four partial derivatives without hiding which input controls which output.

Start with the shape of the answer. A scalar loss has one derivative for every adjustable entry, so its gradient has the same shape as the weight matrix. A plausible-looking transpose is not harmless: it can assign an update to the wrong coordinate, and square examples may fail to expose the mistake.

This chapter derives a multiple-output least-squares gradient, then checks a complete movement of the weights using exact fractions. Read matrix multiplication and partial derivatives first if the indices feel unfamiliar.

Use the differential to keep the dimensions visible

All quantities here are real. Let X have n rows of observations and d feature columns, W have d rows and p output columns, and Y contain n by p targets. X and Y are fixed; n is positive. The loss averages over observations, not over all np output entries:

L(W)=12n∥XW−Y∥F2,X∈Rn×d,W∈Rd×p,Y∈Rn×p.L(W)=\frac{1}{2n}\|XW-Y\|_F^2,\qquad X\in\mathbb R^{n\times d},\quad W\in\mathbb R^{d\times p},\quad Y\in\mathbb R^{n\times p}.

The Frobenius norm squared means the sum of the squares of every entry. Put E=XW−Y. A small change dW produces dE=X dW because the data are held fixed. The differential dL is the first-order part of the change, not the whole finite change. Using the trace, which adds diagonal entries, gives:

dL=1ntr⁡(ET dE)=1ntr⁡(ETX dW)=tr⁡(GT dW),G=XT(XW−Y)n.dL=\frac{1}{n}\operatorname{tr}(E^T\,dE) =\frac{1}{n}\operatorname{tr}(E^T X\,dW) =\operatorname{tr}(G^T\,dW),\qquad G=\frac{X^T(XW-Y)}{n}.

The last identity defines our gradient convention: the Frobenius inner product of G and dW is the first-order loss change. Its shape is d by p. Equivalently, entry (k,j) is the sum over observations of feature k times output-j residual, divided by n. This coordinate interpretation explains the transpose without relying on a mnemonic. The CS229 reference, §4 develops gradients and least squares; the Matrix Cookbook, §2.5 collects the trace identities used in this notation.

For a direction H of the same shape as W, direct expansion gives an exact identity for every real h:

L(W+hH)=L(W)+h⟨G,H⟩F+h22n∥XH∥F2,⟨G,H⟩F=∑k,jGkjHkj.L(W+hH)=L(W)+h\langle G,H\rangle_F+\frac{h^2}{2n}\|XH\|_F^2,\qquad \langle G,H\rangle_F=\sum_{k,j}G_{kj}H_{kj}.

Divide the change by h and let h approach zero to obtain the directional derivative. The quadratic term explains why multiplying a gradient by a large step does not predict the full loss change. Along H=−G, the first-order slope is negative whenever G is nonzero, but a sufficiently large step can still increase loss.

The Hessian can be applied to a direction as XᵀXH/n. It is positive semidefinite because its directional curvature is the nonnegative quantity ||XH||²/n. Full column rank of X makes this quadratic strictly convex in W; a rank-deficient X can have flat directions. Neither rank condition is needed to compute the gradient. Do not introduce an inverse just to differentiate.

Check the slope and the finite change separately

Run the following complete program with Python 3.12. It uses only the standard library. Nonempty rectangular lists or tuples of integers and Fraction values are accepted; floating-point values are deliberately excluded so this demonstration has exact arithmetic. Matrix sizes are intended to be small.

For this fixture the residual rows are [2,−2] and [1,2], whose squared entries sum to 13. The denominator is 4. Taking H=diag(1,−1) gives directional derivative 2 and quadratic coefficient 3/2. At h=1/2, the linear prediction alone is 17/4, while the actual loss is 37/8: the missing 3/8 is exactly the quadratic term.

from fractions import Fraction as F


def matrix(rows):
    if not isinstance(rows, (list, tuple)) or not rows:
        raise ValueError('nonempty rectangular matrix required')
    if any(not isinstance(r, (list, tuple)) or not r for r in rows):
        raise ValueError('nonempty rows required')
    if any(len(r) != len(rows[0]) for r in rows):
        raise ValueError('ragged matrix')
    if any(type(v) not in (int, F) for r in rows for v in r):
        raise ValueError('integer or Fraction entries required')
    return [[F(v) for v in r] for r in rows]


def loss_gradient(x, w, y):
    x, w, y = map(matrix, (x, w, y))
    n, d, p = len(x), len(x[0]), len(w[0])
    if len(w) != d or len(y) != n or len(y[0]) != p:
        raise ValueError('expected X(n,d), W(d,p), Y(n,p)')
    residual = [[sum(x[i][k]*w[k][j] for k in range(d))-y[i][j]
                 for j in range(p)] for i in range(n)]
    loss = sum(v*v for row in residual for v in row)/(2*n)
    gradient = [[sum(x[i][k]*residual[i][j] for i in range(n))/n
                 for j in range(p)] for k in range(d)]
    return loss, gradient


if __name__ == '__main__':
    x, w, y = [[1,2],[0,1]], [[1,-1],[2,0]], [[3,1],[1,-2]]
    loss, gradient = loss_gradient(x,w,y)
    h, direction = F(1,2), [[1,0],[0,-1]]
    moved = [[w[i][j]+h*direction[i][j] for j in range(2)] for i in range(2)]
    slope = sum(gradient[i][j]*direction[i][j] for i in range(2) for j in range(2))
    moved_loss, _ = loss_gradient(x,moved,y)
    assert (loss,slope,moved_loss) == (F(13,4),F(2),F(37,8))
    print('loss:',loss)
    print('gradient:',[[str(v) for v in row] for row in gradient])
    print('directional derivative:',slope)
    print('loss at h=1/2:',moved_loss)

Output:

loss: 13/4
gradient: [['1', '-1'], ['5/2', '-1']]
directional derivative: 2
loss at h=1/2: 37/8

The ordinary dense computation takes O(ndp) arithmetic operations for prediction and gradient, with O(np+dp) extra storage for residual and gradient, excluding inputs and validation copies. Fraction numerator sizes can grow, so an arithmetic-operation count does not describe bit-level cost. Production implementations normally use floating-point matrix multiplication; compare with vectorization and gradient checking.

A correct derivative still depends on the stated objective

A library’s mean-squared-error loss may divide by np rather than n. That changes the gradient by a factor of p. Adding λ||W||²/2 contributes λW; excluding some parameters from regularization changes only those entries. State these choices before comparing results.

This is the gradient of a scalar function of a matrix. The derivative of the matrix-valued prediction XW is a linear map from perturbations to perturbations; flattening it produces a Jacobian whose arrangement depends on the flattening convention. Calling both objects “the matrix derivative” without shapes invites confusion.

Complex parameters, symmetric constraints and nondifferentiable losses require their own conventions. Exact rational evaluation of this polynomial does not validate a different model or prove a floating-point implementation stable. The derivation gives the general identity; numerical examples catch selected implementation mistakes.

Use shape, scale and direction as checks

  1. If X is 7×3 and Y is 7×2, what shapes must W and its gradient have?

Answer 1: Both are 3×2. Xᵀ is 3×7 and the residual is 7×2, so their product has the required shape.

  1. Why does the example’s loss equal 13/4 rather than 13/8?

Answer 2: The definition divides by 2n with n=2. Averaging over output coordinates as well would introduce another factor p=2 and define a different objective.

  1. For the example’s direction H, does a slope of 2 mean that a step h=1/2 raises the loss by exactly 1?

Answer 3: No. The increase is 1+3/8=11/8. The slope describes the derivative at zero; the quadratic remainder matters at a finite step.

  1. If X has a nonzero null vector v, choose any nonzero row aᵀ and let H=vaᵀ. What changes along W+hH?

Answer 4: XH=0, so predictions and loss stay unchanged for every h. The gradient has zero inner product with this direction, and the Hessian action on it is zero.

From hand derivatives to automatic differentiation

Trace notation is useful when checking a new objective: it exposes the inner product and where the gradient lives. Coordinate differentiation gives an independent route. For large computational graphs, automatic differentiation propagates these local derivative operations without constructing every global Jacobian entry.

Use the CS229 notes to practice quadratic forms, and the Matrix Cookbook as an identity reference whose assumptions still need checking. As a follow-up, add a diagonal weight per observation, derive XᵀDE/n, and verify the result against a coordinate calculation. This changes the actual objective and provides a better test of understanding than memorizing XᵀE.

Make a prediction, then check

What shape has the gradient when W is d by p?

Choose one answer

Learning objectives

  • Derive Xᵀ(XW−Y)/n with explicit shapes.
  • Separate a directional derivative from a finite step.

Prerequisites & connections

Explore related knowledge →

References

  1. Linear Algebra Review and Reference — September 30, 2015
    Zico Kolter; updated by Chuong Do · 2015
  2. The Matrix Cookbook — November 15, 2012
    Kaare Brandt Petersen; Michael Syskind Pedersen · 2012

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: primary-source locations, derivations, literal or exact computational checks, real runtime experiments where stated, and bilingual review; not independent human or second-agent peer review.

  • Four tests passed against literal rational gradients, a complete directional polynomial, a rectangular fixture and null direction. Three matching formulas and four answers render.
  • Single-agent authored technical review, with primary-source locations, stated assumptions and matching bilingual examples/exercises. Not independent human or second-agent review. Final publication navigation and repository checks are separate.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.