Skip to content
Portrait of Saeed Taghavi

Saeed Taghavi

Postdoctoral Researcher in Computational Neuroscience
Zapata-Briceño Institute of Neuroscience, Madrid

Derivatives of vectors and matrices

Training a model means minimising a function of many parameters, and minimising means differentiating. The derivative of a function of one variable is a number. As soon as the variables are vectors and matrices, the derivative becomes a vector, a matrix or something larger, and there are two competing conventions for how to arrange it. This post sorts that out: what the objects are, what shape they have, the identities that come up again and again, and how to check a result when in doubt.

This is a companion to the machine learning notes. Part 2 needed four identities to derive linear regression and gave them without much comment. Here is the full set, with the reasoning. The post on gradient descent and its difficulties puts the gradient and the Hessian to work in optimisation.

Notation: scalars are plain letters, \(x\). Vectors are bold lower case, \(\mathbf{x}\), and are columns unless they carry a transpose. Matrices are bold upper case, \(\mathbf{X}\).

From the derivative to the gradient

The derivative of a function \(f(x)\) of one variable is the slope of its graph: the rate at which \(f\) changes when \(x\) changes,

\[ \frac{df}{dx} = \lim_{h\to 0}\frac{f(x + h) - f(x)}{h}. \]

A function of several variables, \(f(x_1, \dots, x_n)\), has one such rate for each variable, taken while the others are held fixed. These are the partial derivatives \(\partial f/\partial x_i\). Collected in a vector they form the gradient:

\[ \nabla f(\mathbf{x}) = \left(\frac{\partial f}{\partial x_1}, \frac{\partial f}{\partial x_2}, \dots, \frac{\partial f}{\partial x_n}\right)^{\!\top}. \]

The gradient is more than a list. It is the object that answers every question about the first-order behaviour of \(f\). For a small step \(\boldsymbol{\delta}\),

\[ f(\mathbf{x} + \boldsymbol{\delta}) \approx f(\mathbf{x}) + \nabla f(\mathbf{x})^\top\boldsymbol{\delta}. \]

Take a step of unit length in a direction \(\mathbf{u}\). The rate of change of \(f\) in that direction, the directional derivative, is the product \(\nabla f^\top\mathbf{u} = \lVert\nabla f\rVert\cos\varphi\), where \(\varphi\) is the angle between the step and the gradient. Three facts follow at once.

  • The rate is largest for \(\varphi = 0\). The gradient points in the direction of steepest ascent, and its length is the slope in that direction.
  • The rate is most negative for \(\varphi = 180°\). The negative gradient is the direction of steepest descent, which is the whole idea of gradient descent.
  • The rate is zero for \(\varphi = 90°\). Perpendicular to the gradient the function does not change, so the gradient is perpendicular to the contour lines.
Contours of a function of two variables with its gradient drawn as arrows at a grid of points, and the rate of change of the function at one point as a function of the direction of the step
Left: contours of a bowl-shaped function with its gradient at a grid of points, in blue. The arrows cross the contours at right angles and grow with the slope. At the red point the gradient is (1.96, 2.44), and the dashed line is the tangent of the contour there. Right: the rate of change of f at that point for a step in every direction. It is a cosine with its maximum, 3.13, along the gradient, its minimum against it, and zeros along the contour.

At a minimum there is no direction of descent left, so the gradient must vanish: \(\nabla f = \mathbf{0}\). That equation is how the minimum of a loss is found on paper, and the reason gradients have to be computed at all.

Nine kinds of derivative, six that fit in a matrix

Both the thing being differentiated and the variable can be a scalar, a vector or a matrix. That gives nine combinations.

Scalar \(y\) Vector \(\mathbf{y}\), \(m\) entries Matrix \(\mathbf{Y}\), \(r \times s\)
by a scalar \(x\) \(\partial y/\partial x\): one number \(\partial\mathbf{y}/\partial x\): \(m\) numbers \(\partial\mathbf{Y}/\partial x\): \(r \times s\) numbers
by a vector \(\mathbf{x}\), \(n\) entries \(\partial y/\partial\mathbf{x}\): \(n\) numbers, the gradient \(\partial\mathbf{y}/\partial\mathbf{x}\): \(m \times n\) numbers, the Jacobian \(\partial Y_{ij}/\partial x_k\): \(r \times s \times n\) numbers, three indices
by a matrix \(\mathbf{X}\), \(p \times q\) \(\partial y/\partial\mathbf{X}\): \(p \times q\) numbers \(\partial y_i/\partial X_{jk}\): \(m \times p \times q\) numbers, three indices \(\partial Y_{ij}/\partial X_{kl}\): \(r \times s \times p \times q\) numbers, four indices

In every case the derivative contains one number for each pair of an output entry and an input entry. An index is the subscript that picks out one entry: a vector needs one, as in \(x_k\), and a matrix needs two, as in \(X_{ij}\). The derivative needs the indices of the output and those of the input together. The Jacobian, for example, has the entries \(\partial y_i/\partial x_j\): two indices, so it fits in a table of rows and columns.

Six of the nine have at most two indices and can be written as a matrix. The other three need more. The derivative of a vector by a matrix has one number \(\partial y_i/\partial X_{jk}\) for every choice of \(i\), \(j\) and \(k\). Three indices do not fit in rows and columns: the numbers fill a block, a stack of \(m\) matrices of size \(p \times q\), one for each entry of \(\mathbf{y}\). With four indices it is a stack of such blocks. These objects exist, and they are called tensors, but they are almost never written out. In machine learning the loss is a scalar, so the first column is the one that matters most: a scalar differentiated by a vector or by a matrix.

Two layouts

Take the derivative of a scalar by a vector. It has \(n\) entries, and nothing in mathematics says whether to write them as a row or as a column. Two conventions are in use.

  • In the numerator layout the result takes its shape from the numerator and the transpose of the denominator. A scalar by a column vector gives a row.
  • In the denominator layout the result takes its shape from the denominator and the transpose of the numerator. A scalar by a column vector gives a column.

The six cases written out

The letters are those of the table above: \(\mathbf{y}\) has \(m\) entries, \(\mathbf{x}\) has \(n\), \(\mathbf{Y}\) is \(r \times s\) and \(\mathbf{X}\) is \(p \times q\).

By a scalar. The derivative of a scalar by a scalar is one number, and the two layouts agree. A vector differentiated by a scalar is a column in one layout and a row in the other:

\[ \frac{\partial\mathbf{y}}{\partial x} = \underbrace{\begin{pmatrix} \dfrac{\partial y_1}{\partial x}\\ \vdots\\ \dfrac{\partial y_m}{\partial x} \end{pmatrix}}_{\text{numerator layout, } m \times 1} \qquad\qquad \frac{\partial\mathbf{y}}{\partial x} = \underbrace{\begin{pmatrix} \dfrac{\partial y_1}{\partial x} & \cdots & \dfrac{\partial y_m}{\partial x} \end{pmatrix}}_{\text{denominator layout, } 1 \times m} \]

A matrix differentiated by a scalar is, in the numerator layout, a matrix of the same shape with the derivative of every entry in its own place:

\[ \frac{\partial\mathbf{Y}}{\partial x} = \begin{pmatrix} \dfrac{\partial Y_{11}}{\partial x} & \cdots & \dfrac{\partial Y_{1s}}{\partial x}\\ \vdots & \ddots & \vdots\\ \dfrac{\partial Y_{r1}}{\partial x} & \cdots & \dfrac{\partial Y_{rs}}{\partial x} \end{pmatrix}. \]

The denominator layout would give the transpose of this matrix. It is rarely used for this case.

By a vector. A scalar differentiated by a vector is a row in the numerator layout and a column in the denominator layout. The column is the gradient.

\[ \frac{\partial y}{\partial\mathbf{x}} = \underbrace{\begin{pmatrix} \dfrac{\partial y}{\partial x_1} & \cdots & \dfrac{\partial y}{\partial x_n} \end{pmatrix}}_{\text{numerator layout, } 1 \times n} \qquad\qquad \frac{\partial y}{\partial\mathbf{x}} = \underbrace{\begin{pmatrix} \dfrac{\partial y}{\partial x_1}\\ \vdots\\ \dfrac{\partial y}{\partial x_n} \end{pmatrix}}_{\text{denominator layout, } n \times 1} \]

A vector differentiated by a vector is a matrix in both. The numerator layout has one row for each entry of \(\mathbf{y}\), and the denominator layout has one column for each:

\[ \frac{\partial\mathbf{y}}{\partial\mathbf{x}} = \underbrace{\begin{pmatrix} \dfrac{\partial y_1}{\partial x_1} & \cdots & \dfrac{\partial y_1}{\partial x_n}\\ \vdots & \ddots & \vdots\\ \dfrac{\partial y_m}{\partial x_1} & \cdots & \dfrac{\partial y_m}{\partial x_n} \end{pmatrix}}_{\text{numerator layout, } m \times n} \qquad \frac{\partial\mathbf{y}}{\partial\mathbf{x}} = \underbrace{\begin{pmatrix} \dfrac{\partial y_1}{\partial x_1} & \cdots & \dfrac{\partial y_m}{\partial x_1}\\ \vdots & \ddots & \vdots\\ \dfrac{\partial y_1}{\partial x_n} & \cdots & \dfrac{\partial y_m}{\partial x_n} \end{pmatrix}}_{\text{denominator layout, } n \times m} \]

The first of the two is the Jacobian, which has its own section below.

By a matrix. A scalar differentiated by a matrix has one entry for each entry of \(\mathbf{X}\). The denominator layout puts \(\partial y/\partial X_{ij}\) in row \(i\) and column \(j\), where \(X_{ij}\) itself stands. The numerator layout puts it in row \(j\) and column \(i\):

\[ \frac{\partial y}{\partial\mathbf{X}} = \underbrace{\begin{pmatrix} \dfrac{\partial y}{\partial X_{11}} & \cdots & \dfrac{\partial y}{\partial X_{p1}}\\ \vdots & \ddots & \vdots\\ \dfrac{\partial y}{\partial X_{1q}} & \cdots & \dfrac{\partial y}{\partial X_{pq}} \end{pmatrix}}_{\text{numerator layout, } q \times p} \qquad \frac{\partial y}{\partial\mathbf{X}} = \underbrace{\begin{pmatrix} \dfrac{\partial y}{\partial X_{11}} & \cdots & \dfrac{\partial y}{\partial X_{1q}}\\ \vdots & \ddots & \vdots\\ \dfrac{\partial y}{\partial X_{p1}} & \cdots & \dfrac{\partial y}{\partial X_{pq}} \end{pmatrix}}_{\text{denominator layout, } p \times q} \]

Some texts remove the doubt by writing the transpose into the symbol. The part that carries the transpose is laid out along the rows:

  • \(\partial\mathbf{y}/\partial\mathbf{x}^\top\) is the \(m \times n\) matrix of the numerator layout, and \(\partial y/\partial\mathbf{x}^\top\) is the row.
  • \(\partial\mathbf{y}^\top/\partial\mathbf{x}\) is the \(n \times m\) matrix of the denominator layout, and \(\partial\mathbf{y}^\top/\partial x\) is the row of the derivatives of \(\mathbf{y}\) by a scalar.
  • \(\partial y/\partial\mathbf{X}^\top\) is the \(q \times p\) matrix of the numerator layout, and a plain \(\partial y/\partial\mathbf{X}\) then means the \(p \times q\) one.

The shapes at a glance

The six derivatives that fit in a matrix, each drawn as a grid of cells with one cell per entry, in the numerator layout and in the denominator layout
The six cases as shapes, with one cell for each entry. Top: what is differentiated, over what it is differentiated by. Here m = 3, n = 4, Y is 2 × 3 and X is 4 × 2. Below: the shape of the result in each layout. Every shape in the bottom row is the transpose of the one above it. Filled in red: the arrangement used in this post.
Derivative Numerator layout Denominator layout
vector \(\mathbf{y}\) (\(m\)) by scalar \(x\) column, \(m \times 1\) row, \(1 \times m\)
matrix \(\mathbf{Y}\) (\(r \times s\)) by scalar \(x\) \(r \times s\) rarely used
scalar \(y\) by vector \(\mathbf{x}\) (\(n\)) row, \(1 \times n\) column, \(n \times 1\): the gradient
vector \(\mathbf{y}\) (\(m\)) by vector \(\mathbf{x}\) (\(n\)) \(m \times n\): the Jacobian \(n \times m\): its transpose
scalar \(y\) by matrix \(\mathbf{X}\) (\(p \times q\)) \(q \times p\) \(p \times q\): the shape of \(\mathbf{X}\)

Which layout to use

The two layouts contain the same numbers and differ by a transpose. Neither is wrong. What goes wrong is mixing them: a formula copied from a table in one layout into a calculation in the other gives products whose shapes do not match, or, worse, shapes that happen to match and a wrong result.

Each layout has one thing it does best, and most of the machine learning literature therefore uses a mixture, which is also what this post and the notes do:

  • Gradients in denominator layout. The gradient \(\nabla f\) of a scalar is a column with the shape of \(\mathbf{x}\), and \(\partial f/\partial\mathbf{X}\) has the shape of \(\mathbf{X}\). Then the update \(\mathbf{w} \leftarrow \mathbf{w} - \eta\nabla J\) subtracts two things of the same shape.
  • Jacobians in numerator layout. The Jacobian of a vector function is \(m \times n\), one row per output. Then the chain rule is a product of matrices in the natural order.

With this choice the gradient of a scalar function is the transpose of its Jacobian, \(\nabla f = (\partial f/\partial\mathbf{x})^\top\). When reading any other text, the first thing to find out is which layout it uses. A quick test: look up the derivative of \(\mathbf{a}^\top\mathbf{x}\). If it says \(\mathbf{a}^\top\), the text uses the numerator layout. If it says \(\mathbf{a}\), the denominator layout.

The Jacobian

A function \(\mathbf{f}\) that takes a vector with \(n\) entries and returns a vector with \(m\) entries has \(m \times n\) partial derivatives. The Jacobian arranges them with one row per output and one column per input:

\[ \mathbf{J} = \frac{\partial\mathbf{f}}{\partial\mathbf{x}} = \begin{pmatrix} \dfrac{\partial f_1}{\partial x_1} & \cdots & \dfrac{\partial f_1}{\partial x_n}\\ \vdots & \ddots & \vdots\\ \dfrac{\partial f_m}{\partial x_1} & \cdots & \dfrac{\partial f_m}{\partial x_n} \end{pmatrix}. \]

Row \(i\) is the gradient of the output \(f_i\), written as a row. The Jacobian is the best linear approximation of the function near a point:

\[ \mathbf{f}(\mathbf{x} + \boldsymbol{\delta}) \approx \mathbf{f}(\mathbf{x}) + \mathbf{J}\,\boldsymbol{\delta}. \]

This is the direct generalisation of \(f(x + h) \approx f(x) + f'(x)\,h\), with a matrix in the place of the number \(f'(x)\). Two examples cover most of what is needed. For a linear function \(\mathbf{f}(\mathbf{x}) = \mathbf{A}\mathbf{x}\) the approximation is exact, and the Jacobian is \(\mathbf{A}\). For a function applied to each entry separately, such as \(\mathbf{f}(\mathbf{x}) = \tanh(\mathbf{x})\), output \(i\) depends only on input \(i\), and the Jacobian is diagonal with the entries \(1 - \tanh^2(x_i)\).

A table of identities

Throughout, \(a\), \(\mathbf{a}\), \(\mathbf{b}\) and \(\mathbf{A}\) are constants that do not depend on \(\mathbf{x}\). The middle column is the numerator layout, in which these identities are usually printed. The right column is the same result in denominator layout: the gradient where the function is a scalar, and the transposed Jacobian where it is a vector.

Function of \(\mathbf{x}\) Numerator layout Denominator layout
a constant \(a\) \(\mathbf{0}^\top\) \(\mathbf{0}\)
\(\mathbf{x}\) \(\mathbf{I}\) \(\mathbf{I}\)
\(\mathbf{a}^\top\mathbf{x} = \mathbf{x}^\top\mathbf{a}\) \(\mathbf{a}^\top\) \(\mathbf{a}\)
\(\mathbf{x}^\top\mathbf{x}\) \(2\mathbf{x}^\top\) \(2\mathbf{x}\)
\((\mathbf{x}^\top\mathbf{a})^2\) \(2\,\mathbf{x}^\top\mathbf{a}\,\mathbf{a}^\top\) \(2\,(\mathbf{a}^\top\mathbf{x})\,\mathbf{a}\)
\(\mathbf{A}\mathbf{x}\), a vector \(\mathbf{A}\) \(\mathbf{A}^\top\)
\(\mathbf{x}^\top\mathbf{A}\), a row vector \(\mathbf{A}^\top\) \(\mathbf{A}\)
\(\mathbf{x}^\top\mathbf{A}\mathbf{x}\) \(\mathbf{x}^\top(\mathbf{A} + \mathbf{A}^\top)\) \((\mathbf{A} + \mathbf{A}^\top)\,\mathbf{x}\)
\(\lVert\mathbf{A}\mathbf{x} - \mathbf{b}\rVert^2\) \(2\,(\mathbf{A}\mathbf{x} - \mathbf{b})^\top\mathbf{A}\) \(2\,\mathbf{A}^\top(\mathbf{A}\mathbf{x} - \mathbf{b})\)

Every row is the vector version of something familiar: \(\tfrac{d}{dx}(ax) = a\), \(\tfrac{d}{dx}x^2 = 2x\), \(\tfrac{d}{dx}(ax^2) = 2ax\). When \(\mathbf{A}\) is symmetric, the row for the quadratic form reads \(2\mathbf{A}\mathbf{x}\), which is the form met most often.

Where they come from

None of these has to be believed or memorised. Each follows by writing the function as a sum and differentiating with respect to one component. Two examples show the method.

The linear form. \(f = \mathbf{a}^\top\mathbf{x} = \sum_i a_i x_i\). Only one term of the sum contains \(x_k\), so

\[ \frac{\partial f}{\partial x_k} = a_k, \qquad\text{and therefore}\qquad \nabla f = \mathbf{a}. \]

The quadratic form. \(f = \mathbf{x}^\top\mathbf{A}\mathbf{x} = \sum_i\sum_j x_i A_{ij} x_j\). The variable \(x_k\) appears twice, once as the left factor, where \(i = k\), and once as the right factor, where \(j = k\). The product rule gives one term for each:

\[ \frac{\partial f}{\partial x_k} = \sum_j A_{kj}\,x_j + \sum_i x_i\,A_{ik} = (\mathbf{A}\mathbf{x})_k + (\mathbf{A}^\top\mathbf{x})_k . \]

So \(\nabla f = (\mathbf{A} + \mathbf{A}^\top)\,\mathbf{x}\). The two terms are the same when \(\mathbf{A}\) is symmetric, and the familiar factor of 2 appears.

The recipe is always the same: write the function with indices, differentiate with respect to \(x_k\), and recognise the result as component \(k\) of a matrix expression.

The rules of calculation

The rules for sums, products and compositions carry over from ordinary calculus. For scalar functions \(u\) and \(v\) of a scalar \(x\):

\[ \frac{\partial(u + v)}{\partial x} = \frac{\partial u}{\partial x} + \frac{\partial v}{\partial x}, \qquad \frac{\partial(uv)}{\partial x} = u\,\frac{\partial v}{\partial x} + v\,\frac{\partial u}{\partial x}, \qquad \frac{\partial g(u)}{\partial x} = \frac{\partial g}{\partial u}\,\frac{\partial u}{\partial x}. \]

The last one is the chain rule, and it extends to any number of nested functions: \(\partial f(g(u))/\partial x = (\partial f/\partial g)(\partial g/\partial u)(\partial u/\partial x)\).

For vector functions \(\mathbf{u}\) and \(\mathbf{v}\), with a constant \(a\) and a constant matrix \(\mathbf{A}\), in numerator layout:

\[ \frac{\partial(a\mathbf{u})}{\partial x} = a\,\frac{\partial\mathbf{u}}{\partial x}, \qquad \frac{\partial(\mathbf{A}\mathbf{u})}{\partial x} = \mathbf{A}\,\frac{\partial\mathbf{u}}{\partial x}, \qquad \frac{\partial\mathbf{u}^\top}{\partial x} = \left(\frac{\partial\mathbf{u}}{\partial x}\right)^{\!\top}, \qquad \frac{\partial(\mathbf{u} + \mathbf{v})}{\partial x} = \frac{\partial\mathbf{u}}{\partial x} + \frac{\partial\mathbf{v}}{\partial x}. \]

Constants come out in front, on the side where they stood, because matrices do not commute. A transpose and a derivative can be exchanged.

The chain rule

The chain rule is the one that matters most, because every model is a composition of simple steps. If \(\mathbf{x}\) is turned into \(\mathbf{u}\), then \(\mathbf{u}\) into \(\mathbf{g}\), and \(\mathbf{g}\) into \(\mathbf{f}\), the Jacobian of the whole is the product of the Jacobians of the parts:

\[ \frac{\partial\mathbf{f}}{\partial\mathbf{x}} = \frac{\partial\mathbf{f}}{\partial\mathbf{g}}\;\frac{\partial\mathbf{g}}{\partial\mathbf{u}}\;\frac{\partial\mathbf{u}}{\partial\mathbf{x}} . \]

In numerator layout the matrices stand in the same order as the functions are nested, outermost on the left, and their shapes fit: if \(\mathbf{x}\), \(\mathbf{u}\), \(\mathbf{g}\), \(\mathbf{f}\) have \(n\), \(p\), \(q\), \(m\) entries, the three factors are \(m \times q\), \(q \times p\) and \(p \times n\). In denominator layout every factor is transposed and the order is reversed. This is the main practical reason for writing Jacobians in numerator layout.

For a scalar at the end of the chain, which is the case of a loss, transposing the product gives the gradient:

\[ \nabla_{\mathbf{x}}\,f(\mathbf{g}(\mathbf{x})) = \mathbf{J}_{\mathbf{g}}(\mathbf{x})^\top\,\nabla_{\mathbf{g}} f . \]

Read from right to left: start with the gradient of the loss with respect to the last quantity, and multiply by the transposed Jacobian of each step on the way back to the input. That sentence is the backpropagation algorithm. Reverse-mode automatic differentiation, which is what PyTorch and JAX do when asked for a gradient, is this formula applied mechanically, step by step, without ever forming the Jacobians in full.

An example. Let \(f(\mathbf{x}) = \sum_i \tanh\bigl((\mathbf{B}\mathbf{x})_i\bigr)\): a linear map followed by a function applied entry by entry and a sum. With \(\mathbf{u} = \mathbf{B}\mathbf{x}\), the Jacobian of the inner step is \(\mathbf{B}\), and the gradient of the outer step with respect to \(\mathbf{u}\) has the entries \(1 - \tanh^2(u_i)\). So

\[ \nabla f(\mathbf{x}) = \mathbf{B}^\top\bigl(1 - \tanh^2(\mathbf{B}\mathbf{x})\bigr). \]

This is one layer of a neural network, differentiated in one line.

Second derivatives: the Hessian

The gradient is itself a vector function of \(\mathbf{x}\), so it has a Jacobian. That matrix is the Hessian, the matrix of all second partial derivatives:

\[ \mathbf{H} = \nabla^2 f, \qquad H_{ij} = \frac{\partial^2 f}{\partial x_i\,\partial x_j}. \]

For any function whose second derivatives are continuous, the order of differentiation does not matter, so the Hessian is symmetric. It has \(n^2\) entries, of which \(n(n+1)/2\) are different.

The Hessian adds the next term of the Taylor expansion:

\[ f(\mathbf{x} + \boldsymbol{\delta}) \approx f(\mathbf{x}) + \nabla f(\mathbf{x})^\top\boldsymbol{\delta} + \tfrac12\,\boldsymbol{\delta}^\top\mathbf{H}(\mathbf{x})\,\boldsymbol{\delta}. \]

The gradient describes the slope and the Hessian describes the curvature. For a unit direction \(\mathbf{u}\), the number \(\mathbf{u}^\top\mathbf{H}\mathbf{u}\) is the second derivative of \(f\) along that direction: positive if the function curves upwards there, negative if it curves downwards. The eigenvectors of \(\mathbf{H}\) are the directions of extreme curvature, and its eigenvalues are the curvatures along them.

At a stationary point the gradient is zero, the linear term drops out, and the quadratic term decides what kind of point it is:

Eigenvalues of \(\mathbf{H}\) The point is The matrix is called
all positive a minimum positive definite
all negative a maximum negative definite
some positive, some negative a saddle point indefinite
some zero, none negative undecided at this order positive semidefinite
Contours and gradient fields of three functions around a stationary point: a minimum, a saddle point and a maximum
The three kinds of stationary point, with the gradient in blue and the eigenvalues of the Hessian in the titles. Around a minimum every arrow points away, because every direction is uphill. Around a maximum every arrow points inwards. Around a saddle point the arrows point away along one axis and inwards along the other.

Two Hessians come up constantly. From the table of identities, the gradient of the quadratic form \(\mathbf{x}^\top\mathbf{A}\mathbf{x}\) is \((\mathbf{A} + \mathbf{A}^\top)\mathbf{x}\), a linear function, whose Jacobian is the constant matrix

\[ \nabla^2\bigl(\mathbf{x}^\top\mathbf{A}\mathbf{x}\bigr) = \mathbf{A} + \mathbf{A}^\top . \]

And the gradient of the least-squares loss \(\tfrac12\lVert\mathbf{A}\mathbf{x} - \mathbf{b}\rVert^2\) is \(\mathbf{A}^\top(\mathbf{A}\mathbf{x} - \mathbf{b})\), so

\[ \nabla^2\,\tfrac12\lVert\mathbf{A}\mathbf{x} - \mathbf{b}\rVert^2 = \mathbf{A}^\top\mathbf{A}. \]

For any vector \(\mathbf{v}\), \(\mathbf{v}^\top\mathbf{A}^\top\mathbf{A}\mathbf{v} = \lVert\mathbf{A}\mathbf{v}\rVert^2 \ge 0\), so this Hessian has no negative eigenvalue anywhere. A function with that property is convex, and every stationary point of it is a global minimum. That one line is why linear regression has no local minima.

Higher derivatives

Nothing stops at two. The third derivatives \(\partial^3 f/\partial x_i\,\partial x_j\,\partial x_k\) have three indices and form a tensor with \(n^3\) entries, symmetric in all its indices. It supplies the next term of the Taylor expansion,

\[ \frac{1}{6}\sum_{i,j,k}\frac{\partial^3 f}{\partial x_i\,\partial x_j\,\partial x_k}\,\delta_i\,\delta_j\,\delta_k, \]

and the derivative of order \(k\) is a tensor with \(k\) indices and \(n^k\) entries, which contributes a term with the factor \(1/k!\).

In practice these are almost never formed, and the reason is in the counts. A model with a million parameters has a gradient with \(10^6\) entries, a Hessian with \(10^{12}\), and a third derivative with \(10^{18}\). The gradient is cheap, the Hessian is already out of reach for large models, and everything beyond it is hopeless. Optimisation in machine learning therefore lives almost entirely on first derivatives, with second derivatives used when the model is small or when only their effect on a vector is needed. That effect, the product \(\mathbf{H}\mathbf{v}\), can be had without the Hessian itself, from two gradients:

\[ \mathbf{H}\mathbf{v} \approx \frac{\nabla f(\mathbf{x} + \epsilon\mathbf{v}) - \nabla f(\mathbf{x} - \epsilon\mathbf{v})}{2\epsilon}. \]

Derivatives with respect to a matrix

When the parameters of a model form a matrix, a weight matrix \(\mathbf{W}\) for instance, the loss is a scalar function of a matrix. Its derivative, in denominator layout, is the matrix of the same shape with the entries

\[ \left(\frac{\partial f}{\partial\mathbf{X}}\right)_{ij} = \frac{\partial f}{\partial X_{ij}} . \]

It is the gradient with its entries arranged like \(\mathbf{X}\), and gradient descent on a matrix is \(\mathbf{W} \leftarrow \mathbf{W} - \eta\,\partial J/\partial\mathbf{W}\), entry by entry. The identities that are used most:

Function of \(\mathbf{X}\) \(\partial f/\partial\mathbf{X}\)
\(\mathbf{a}^\top\mathbf{X}\mathbf{b}\) \(\mathbf{a}\mathbf{b}^\top\)
\(\operatorname{tr}(\mathbf{A}\mathbf{X})\) \(\mathbf{A}^\top\)
\(\operatorname{tr}(\mathbf{X}^\top\mathbf{A}\mathbf{X})\) \((\mathbf{A} + \mathbf{A}^\top)\,\mathbf{X}\)
\(\lVert\mathbf{X}\rVert_F^2 = \sum_{ij}X_{ij}^2\) \(2\mathbf{X}\)
\(\ln\det\mathbf{X}\) \((\mathbf{X}^{-1})^\top\)
\(\lVert\mathbf{A}\mathbf{X} - \mathbf{B}\rVert_F^2\) \(2\,\mathbf{A}^\top(\mathbf{A}\mathbf{X} - \mathbf{B})\)

The first one can be seen directly: \(\mathbf{a}^\top\mathbf{X}\mathbf{b} = \sum_{ij}a_i X_{ij} b_j\), and its derivative with respect to \(X_{ij}\) is \(a_i b_j\), which is the entry \(ij\) of \(\mathbf{a}\mathbf{b}^\top\).

The method of differentials

For anything more complicated, indices become tedious, and there is a cleaner route. Change \(\mathbf{X}\) by a small \(d\mathbf{X}\) and work out the change \(df\) to first order, using rules that look like those for ordinary numbers as long as the order of the factors is kept:

\[ \begin{aligned} d(\mathbf{X}\mathbf{Y}) &= d\mathbf{X}\,\mathbf{Y} + \mathbf{X}\,d\mathbf{Y}, & d(\mathbf{X}^{-1}) &= -\mathbf{X}^{-1}\,d\mathbf{X}\,\mathbf{X}^{-1},\\ d\operatorname{tr}(\mathbf{X}) &= \operatorname{tr}(d\mathbf{X}), & d\ln\det\mathbf{X} &= \operatorname{tr}(\mathbf{X}^{-1}d\mathbf{X}). \end{aligned} \]

Then bring the result into the form

\[ df = \operatorname{tr}\bigl(\mathbf{G}^\top d\mathbf{X}\bigr) = \sum_{ij}G_{ij}\,dX_{ij}, \]

and read off the derivative: \(\partial f/\partial\mathbf{X} = \mathbf{G}\). The only tools needed for the rearranging are that a trace does not change under a transpose or under a cyclic shift of its factors, \(\operatorname{tr}(\mathbf{A}\mathbf{B}\mathbf{C}) = \operatorname{tr}(\mathbf{C}\mathbf{A}\mathbf{B})\).

As an example, take the last row of the table. With \(\mathbf{R} = \mathbf{A}\mathbf{X} - \mathbf{B}\), the function is \(f = \operatorname{tr}(\mathbf{R}^\top\mathbf{R})\) and \(d\mathbf{R} = \mathbf{A}\,d\mathbf{X}\). So

\[ df = \operatorname{tr}\bigl(d\mathbf{R}^\top\mathbf{R} + \mathbf{R}^\top d\mathbf{R}\bigr) = 2\operatorname{tr}\bigl(\mathbf{R}^\top\mathbf{A}\,d\mathbf{X}\bigr) = \operatorname{tr}\Bigl(\bigl(2\mathbf{A}^\top\mathbf{R}\bigr)^{\!\top} d\mathbf{X}\Bigr), \]

and therefore \(\partial f/\partial\mathbf{X} = 2\mathbf{A}^\top(\mathbf{A}\mathbf{X} - \mathbf{B})\). With a single column in place of the matrices this is the gradient of least squares, from which the normal equations of linear regression follow by setting it to zero.

Checking a derivative numerically

A derivative worked out by hand is a claim, and it can be tested. The definition at the top of this post suggests how: change one entry of the input by a small \(h\) and see how much the output changes. The symmetric version is much more accurate than the one-sided one:

\[ \frac{\partial f}{\partial x_i} \approx \frac{f(\mathbf{x} + h\,\mathbf{e}_i) - f(\mathbf{x} - h\,\mathbf{e}_i)}{2h}, \]

where \(\mathbf{e}_i\) is the vector with a one in place \(i\) and zeros elsewhere. In code, for a vector or a matrix:

import numpy as np


def numerical_gradient(f, x, h=1e-5):
    """Central differences. Works for a vector or a matrix x and a scalar f."""
    g = np.zeros_like(x, dtype=float)
    for i in range(x.size):
        e = np.zeros_like(x, dtype=float)
        e.flat[i] = h
        g.flat[i] = (f(x + e) - f(x - e)) / (2.0 * h)
    return g


rng = np.random.default_rng(0)
x = rng.standard_normal(5)
A = rng.standard_normal((5, 5))

by_hand = (A + A.T) @ x                             # the claim
by_machine = numerical_gradient(lambda z: z @ A @ z, x)
print(np.abs(by_hand - by_machine).max())           # 5.3e-12

The two agree to eleven decimal places. A wrong formula, a missing transpose or a factor of 2, shows up as a deviation of the order of one. I ran this check on every identity in the two tables above, on the Jacobians, and on the chain-rule example, with random vectors and matrices. The largest deviation among all of them is \(3 \times 10^{-9}\).

This costs two evaluations of the function for every entry of \(\mathbf{x}\), so it is far too slow to train a model with. It is a test, to be run once on a small example. It is also the first thing to do when gradient descent does not descend.

How small should the step be?

Not as small as possible. A finite difference has two sources of error that pull in opposite directions. The truncation error comes from the formula being an approximation, and it shrinks with \(h\): in proportion to \(h\) for the one-sided difference and to \(h^2\) for the central one. The rounding error comes from subtracting two nearly equal numbers that the computer stores with about 16 digits, and it grows as \(1/h\).

The error of a forward and of a central difference for the derivative of the exponential function against the step, on logarithmic axes: both fall and then rise
The error of two finite-difference formulas for the derivative of eˣ at x = 1. On the right the truncation error dominates and falls with h, twice as steeply for the central difference. On the left the rounding error dominates and grows as h shrinks. The forward difference is best near h = 10⁻⁸, with an error of about 10⁻⁸. The central difference is best near h = 10⁻⁵ to 10⁻⁶, with an error of about 10⁻¹².

The best step is where the two meet: near the square root of the machine precision, about \(10^{-8}\), for the forward difference, and near its cube root, about \(10^{-5}\), for the central one. That is why the code above uses \(h = 10^{-5}\). With a step of \(10^{-12}\), chosen in the belief that smaller is better, the result has four correct digits instead of eleven.

Summary

Object What is differentiated Shape used here What it says
Derivative scalar by scalar a number the slope
Gradient \(\nabla f\) scalar by vector (\(n\)) column, \(n \times 1\) direction and rate of steepest ascent
Jacobian \(\mathbf{J}\) vector (\(m\)) by vector (\(n\)) \(m \times n\) the best linear approximation
Hessian \(\mathbf{H}\) scalar by vector, twice \(n \times n\), symmetric the curvature in every direction
\(\partial f/\partial\mathbf{X}\) scalar by matrix (\(p \times q\)) \(p \times q\) the gradient, arranged like \(\mathbf{X}\)

Four habits prevent most mistakes. Decide on a layout before starting, and find out which one a table uses before copying from it. Check the shapes of every line: a gradient must have the shape of the variable. When in doubt, write the function with indices and differentiate one component. And test the result against a finite difference before building on it.

Code

The figures and the numerical checks come from scripts/ml_matrix_derivatives.py in this site's repository:

pip install -r scripts/requirements.txt
python scripts/ml_matrix_derivatives.py
python scripts/ml_matrix_derivatives.py --only check

Further reading

  • K. B. Petersen and M. S. Pedersen, The Matrix Cookbook. Hundreds of identities without derivations. It uses the denominator layout for derivatives by a vector or a matrix.
  • T. Parr and J. Howard, "The matrix calculus you need for deep learning" (2018). A slow and careful introduction, written for programmers. arXiv:1802.01528
  • J. R. Magnus and H. Neudecker, Matrix Differential Calculus with Applications in Statistics and Econometrics (3rd edition, Wiley, 2019). The standard text on the method of differentials.
  • M. P. Deisenroth, A. A. Faisal and C. S. Ong, Mathematics for Machine Learning (Cambridge University Press, 2020), chapter 5. Vector calculus, including the chain rule and automatic differentiation, free to download.
  • The Wikipedia article on matrix calculus has long tables of identities in both layouts side by side, which is the quickest way to translate between them.