Calculus and Matrix Calculus for ML

Matrix Calculus Notation

A shape-first guide to matrix-calculus notation, layout conventions, differentials, and reusable vector and matrix derivative identities.

Lesson
38

Goal

Make matrix-calculus notation behave like a type system: the input and output spaces determine the derivative’s job, and its shape exposes many mistakes before any algebra is finished.

The central rule is:

Decide what linear map the derivative must represent, write its shape, and only then choose notation for it.

A Short Bridge From Computation Graphs

Before adding new notation, separate three operations that looked similar in the previous lesson.

Evaluate Local Derivatives At Local Values

If:

u=2x1,L=u3,u=2x-1, \qquad L=u^3,

then:

dLdx=Luux=3u2(2).\frac{dL}{dx} = \frac{\partial L}{\partial u} \frac{\partial u}{\partial x} =3u^2(2).

At x=2x=2, the stored intermediate value is u=3u=3, so:

dLdx=3(3)2(2)=54.\frac{dL}{dx}=3(3)^2(2)=54.

The square belongs to uu, not to the original input xx.

Differentiate The Operation That Is Actually Present

If:

L=x2+sinx,L=x^2+\sin x,

the final operation is addition. Its local derivatives are both 11, so the two paths contribute:

dLdx=2x+cosx.\frac{dL}{dx}=2x+\cos x.

Factors such as sinx\sin x and x2x^2 would appear if the final operation were multiplication. A graph prevents that accidental change of program.

Build Jacobians From Component Functions

For:

F(x,y)=[xyx+y],F(x,y)= \begin{bmatrix} x-y\\ x+y \end{bmatrix},

differentiate each output with respect to each input:

JF(x,y)=[1111].J_F(x,y)= \begin{bmatrix} 1 & -1\\ 1 & 1 \end{bmatrix}.

Do not infer the derivative from the visual presence of two variables. Read the actual addition, subtraction, multiplication, or other operation in each component.

These are the same habits matrix calculus needs: local values, actual operations, and explicit shapes.

Notation / Symbol Table

SymbolShapeMeaning
xRnx\in\mathbb R^nn×1n\times1Column-vector input.
F(x)RmF(x)\in\mathbb R^mm×1m\times1Column-vector output.
JF(x)J_F(x)m×nm\times nOutput-by-input Jacobian.
xf\nabla_x fn×1n\times1Column gradient of scalar ff with respect to xx.
dxdxn×1n\times1Small input displacement.
dfdfscalarFirst-order change in a scalar function.
XRp×qX\in\mathbb R^{p\times q}p×qp\times qMatrix input.
Xf\nabla_X fp×qp\times qMatrix gradient paired with dXdX.
tr(A)\operatorname{tr}(A)scalarSum of diagonal entries of square AA.
A,BF\langle A,B\rangle_FscalarFrobenius inner product tr(ATB)\operatorname{tr}(A^TB).

Derivatives Are Linear Maps Before They Are Arrays

Let:

F:RnRm.F:\mathbb R^n\to\mathbb R^m.

Near xx, the derivative consumes an input displacement and produces an output displacement:

dF=JF(x)dx.dF=J_F(x)\,dx.

The shapes must be:

dFm×1=JF(x)m×ndxn×1.\underbrace{dF}_{m\times1} = \underbrace{J_F(x)}_{m\times n} \underbrace{dx}_{n\times1}.

That requirement is more fundamental than the notation JFJ_F. Any notation convention must still encode this same local linear map.

For a scalar function:

f:RnR,f:\mathbb R^n\to\mathbb R,

the differential is:

df=(xf)Tdx.df=(\nabla_x f)^Tdx.

Again the shapes explain the transpose:

df1×1=(xf)T1×ndxn×1.\underbrace{df}_{1\times1} = \underbrace{(\nabla_x f)^T}_{1\times n} \underbrace{dx}_{n\times1}.

Two Layout Families

Different books arrange the same partial derivatives differently. Let F:RnRmF:\mathbb R^n\to\mathbb R^m.

Numerator Layout

Numerator layout places output coordinates in rows and input coordinates in columns:

Fx=[F1x1F1xnFmx1Fmxn]Rm×n.\frac{\partial F}{\partial x} = \begin{bmatrix} \frac{\partial F_1}{\partial x_1} & \cdots & \frac{\partial F_1}{\partial x_n}\\ \vdots & \ddots & \vdots\\ \frac{\partial F_m}{\partial x_1} & \cdots & \frac{\partial F_m}{\partial x_n} \end{bmatrix} \in\mathbb R^{m\times n}.

This is the Jacobian convention used by this course because it acts directly in:

dF=JFdx.dF=J_F\,dx.

For scalar ff, the same layout produces a 1×n1\times n row derivative.

Denominator Layout

Denominator layout transposes that array:

(Fx)denominatorRn×m.\left(\frac{\partial F}{\partial x}\right)_{\text{denominator}} \in\mathbb R^{n\times m}.

For scalar ff, this produces an n×1n\times1 column—the same shape commonly assigned to xf\nabla_x f.

The Course Convention

This course uses a practical hybrid that is common in machine learning:

The names “numerator” and “denominator” are less important than declaring the shape. When reading another source, ask:

  1. Are vectors columns or rows?
  2. What shape does it assign to a scalar-by-vector derivative?
  3. Does its chain rule multiply on the left or the right?
  4. Is its displayed object a Jacobian, a gradient, or a transpose of one?

Shape Checking As A Compiler

Suppose:

xRn,ARm×n,y=Ax+bRm.x\in\mathbb R^n, \qquad A\in\mathbb R^{m\times n}, \qquad y=Ax+b\in\mathbb R^m.

The derivative with respect to xx must map an nn-vector displacement to an mm-vector displacement, so:

Jy(x)=ARm×n.J_y(x)=A\in\mathbb R^{m\times n}.

Now let f:RmRf:\mathbb R^m\to\mathbb R. The chain rule in column-gradient form is:

x(fy)=Jy(x)Tyf=ATyf.\nabla_x(f\circ y) = J_y(x)^T\nabla_y f =A^T\nabla_y f.

The shape check is:

xfn×1=ATn×myfm×1.\underbrace{\nabla_x f}_{n\times1} = \underbrace{A^T}_{n\times m} \underbrace{\nabla_y f}_{m\times1}.

This is exactly the vector form of a backward pass.

Differentials: A Convention-Resistant Method

Differentials let us derive gradients by matching a standard shape instead of recalling a formula.

For a vector input, arrange the result as:

df=(xf)Tdx.df=(\nabla_x f)^Tdx.

Whatever multiplies dxdx as a row is (xf)T(\nabla_x f)^T.

Linear Form

Let:

f(x)=aTx.f(x)=a^Tx.

Then:

df=aTdx.df=a^Tdx.

Matching the standard form gives:

xf=a.\nabla_x f=a.

Quadratic Form

Let:

f(x)=xTAx.f(x)=x^TAx.

Apply the product rule:

df=(dx)TAx+xTA(dx).df=(dx)^TAx+x^TA(dx).

The first scalar term can be transposed without changing its value:

(dx)TAx=xTATdx.(dx)^TAx=x^TA^Tdx.

Therefore:

df=xT(AT+A)dx,df=x^T(A^T+A)dx,

so:

xf=(A+AT)x.\nabla_x f=(A+A^T)x.

If AA is symmetric, this reduces to:

xf=2Ax.\nabla_x f=2Ax.

The familiar 2Ax2Ax formula requires symmetry. Shape checking alone cannot supply that assumption; it must be stated.

A Core ML Identity: Squared Error

Let:

r=Axb,L(x)=r2=rTr.r=Ax-b, \qquad L(x)=\lVert r\rVert^2=r^Tr.

First differentiate the residual:

dr=Adx.dr=A\,dx.

Then differentiate the loss:

dL=2rTdr.dL=2r^Tdr.

Substitute the local differential:

dL=2rTAdx.dL=2r^TA\,dx.

Match dL=(xL)TdxdL=(\nabla_xL)^Tdx:

xL=2ATr=2AT(Axb).\nabla_xL=2A^Tr=2A^T(Ax-b).

The transpose is not a memorized decoration. It is forced when the row 2rTA2r^TA is converted into a column gradient.

Gradients With Respect To Matrices

Suppose a scalar function depends on a matrix:

f:Rp×qR.f:\mathbb R^{p\times q}\to\mathbb R.

We define Xf\nabla_X f to have the same shape as XX and pair it with dXdX using the Frobenius inner product:

df=Xf,dXF=tr((Xf)TdX).df = \langle \nabla_X f,dX\rangle_F = \operatorname{tr}\left((\nabla_X f)^T dX\right).

This is the matrix analogue of df=(xf)Tdxdf=(\nabla_x f)^Tdx.

Trace Linear Form

Let:

f(X)=tr(ATX),f(X)=\operatorname{tr}(A^TX),

where AA and XX have the same shape. Then:

df=tr(ATdX).df=\operatorname{tr}(A^T dX).

Matching the standard matrix differential gives:

Xf=A.\nabla_X f=A.

The trace turns an entrywise sum into compact linear-algebra notation:

tr(ATX)=i,jAijXij.\operatorname{tr}(A^TX)=\sum_{i,j}A_{ij}X_{ij}.

Derivative Identity Ledger

These identities should be reconstructible from differentials and shapes:

FunctionGradient or JacobianRequired assumptions
y=Ax+by=Ax+bJy=AJ_y=AAA is constant.
f=aTxf=a^Txxf=a\nabla_x f=aaa is constant.
f=xTAxf=x^TAxxf=(A+AT)x\nabla_x f=(A+A^T)xAA is constant.
f=xTAxf=x^TAxxf=2Ax\nabla_x f=2AxAA is constant and symmetric.
L=Axb2L=\lVert Ax-b\rVert^2xL=2AT(Axb)\nabla_xL=2A^T(Ax-b)AA and bb are constant.
f(X)=tr(ATX)f(X)=\operatorname{tr}(A^TX)Xf=A\nabla_Xf=AAA is constant and has the same shape as XX.

Use this table as a checksum, not as a substitute for the derivations.

Reading A Paper Without Inheriting Its Convention Blindly

Suppose a paper writes:

Lx=g.\frac{\partial L}{\partial x}=g.

That line alone does not reveal whether gg is a row or column. Recover its meaning from use:

The invariant is the linear map and the scalar pairing, not the typography.

Connection To Programming

A lightweight shape ledger makes the convention explicit in code review:

type Shape = readonly [rows: number, columns: number];

type TypedValue = Readonly<{
  name: string;
  shape: Shape;
}>;

const canMultiply = (
  left: TypedValue,
  right: TypedValue,
): boolean => left.shape[1] === right.shape[0];

const jacobian: TypedValue = { name: 'J_F', shape: [3, 2] };
const displacement: TypedValue = { name: 'dx', shape: [2, 1] };

console.assert(canMultiply(jacobian, displacement));

Real tensor libraries carry richer shape information, but the mathematical habit is the same: reject incompatible compositions early.

Common Mistakes

Calling Every Derivative A Gradient

A gradient is naturally associated with a scalar output. A vector-valued function has a Jacobian or another explicitly declared derivative map.

Copying A Formula Without Its Convention

Two sources may display transposed arrays while representing the same derivative. Record vector orientation and expected shape before comparing formulas.

Losing A Transpose In A Backward Pass

Forward displacements use dF=JFdxdF=J_Fdx. Backward column gradients use xL=JFTFL\nabla_xL=J_F^T\nabla_FL.

Using The Symmetric Quadratic Identity Without Symmetry

x(xTAx)=2Ax\nabla_x(x^TAx)=2Ax only when A=ATA=A^T. The general result is (A+AT)x(A+A^T)x.

Treating Shape Checking As A Complete Proof

Several wrong formulas can have the right shape. Shape checking rejects many errors, but component definitions, local values, and algebra still matter.

Exercises

  1. Let F:R4R2F:\mathbb R^4\to\mathbb R^2. State the shape of its numerator-layout Jacobian and denominator-layout derivative. Which one acts directly on a 4×14\times1 displacement from the left?

  2. Let f:R3Rf:\mathbb R^3\to\mathbb R. Write the shapes of JfJ_f, f\nabla f, and dfdf. Explain the transpose relation between the first two.

  3. For y=Ax+by=Ax+b with AR5×3A\in\mathbb R^{5\times3}, write the forward differential and the reverse column-gradient rule. Annotate every factor with its shape.

  4. Derive x(aTx)\nabla_x(a^Tx) using differentials rather than componentwise partial derivatives.

  5. Derive x(xTAx)\nabla_x(x^TAx) for a general constant AA. Then state the extra assumption needed to simplify the result to 2Ax2Ax.

  6. Let L(x)=Axb2L(x)=\lVert Ax-b\rVert^2 with ARm×nA\in\mathbb R^{m\times n}. Derive the gradient and verify that its final shape matches xx.

  7. For f(X)=tr(ATX)f(X)=\operatorname{tr}(A^TX), expand the trace into an entrywise sum and use it to verify Xf=A\nabla_Xf=A.

  8. A source defines a scalar-by-vector derivative as a row but another writes the gradient as a column. Show how both encode the same differential dfdf.

  9. Diagnose the error in the claim x(xTAx)=2Ax\nabla_x(x^TAx)=2Ax for every square AA. Give a 2×22\times2 nonsymmetric example and compare the claimed and correct gradients at a point of your choice.

  10. Write a TypeScript function that accepts two matrix shapes and either returns the product shape or a descriptive incompatibility result. Use it to type-check JGJFJ_GJ_F for F:R4R3F:\mathbb R^4\to\mathbb R^3 and G:R3R2G:\mathbb R^3\to\mathbb R^2.

Summary

Next Lesson

Lesson 39 develops Taylor series and local approximation. It will connect the gradient to the best first-order model and the Hessian to the second-order correction.