The Little Book of Matrix Calculus
Version 0.1.0
Part 1. Foundations
Chapter 1. Why Matrix Calculus Matters in Machine Learning
1.1 Motivation from Optimization and Backpropagation
Matrix calculus is the language of modern machine learning. At the heart of training any model—linear regression, logistic regression, or deep neural networks—lies a single repeated operation: optimize parameters by following the gradient of a loss function. To compute these gradients efficiently and correctly, we rely on matrix calculus.
Gradients in Optimization
In machine learning, we usually define a loss function \(L(\theta)\) that measures how well parameters \(\theta\) fit the data. For example:
- In linear regression, \(\theta\) represents weights \(w\) and bias \(b\), and \(L\) is the mean squared error.
- In logistic regression, \(\theta\) includes weights that determine probabilities, and \(L\) is cross-entropy loss.
- In deep learning, \(\theta\) contains millions of parameters across many layers, and \(L\) is often some combination of task-specific loss and regularization.
To minimize \(L\), we update parameters using gradient descent:
\[ \theta \leftarrow \theta - \eta \nabla_\theta L(\theta), \]
where \(\eta\) is the learning rate and \(\nabla_\theta L(\theta)\) is the gradient. Computing \(\nabla_\theta L(\theta)\) correctly is the job of matrix calculus.
Why Not Just Scalar Calculus?
Scalar calculus gives us rules like:
\[ \frac{d}{dx}(x^2) = 2x. \]
But in machine learning, we often deal with vectors (many parameters at once) and matrices (weights of linear transformations). For example:
Neural network layer:
\[ y = Wx + b, \]
where \(W\) is a weight matrix, \(x\) is an input vector, and \(b\) is a bias vector.
Loss function on a dataset:
\[ L(W, b) = \frac{1}{n} \sum_{i=1}^n \| Wx_i + b - y_i \|^2. \]
To differentiate \(L\) with respect to \(W\) and \(b\), scalar calculus is insufficient—we need matrix calculus.
Backpropagation as Matrix Calculus in Action
Backpropagation, the algorithm that powers deep learning, is essentially repeated application of:
- The chain rule (extended to matrices).
- Matrix derivative identities (gradients of quadratic forms, norms, softmax, etc.).
For example, consider one hidden layer:
\[ h = \sigma(Wx + b), \]
with sigmoid activation \(\sigma\). The gradient \(\nabla_W L\) involves both the derivative of the loss with respect to \(h\) and the derivative of \(\sigma\). This nesting of derivatives is why matrix calculus is indispensable: it keeps track of shapes, dependencies, and compositions systematically.
Key Takeaways
- Machine learning training = optimization via gradients.
- Gradients require derivatives with respect to vectors and matrices, not just scalars.
- Matrix calculus generalizes familiar scalar calculus rules.
- Backpropagation is a structured application of these rules.
Example
Linear regression with squared error:
Given data points \((x_i, y_i)\), prediction is
\[ \hat{y}_i = w^\top x_i + b. \]
Loss function:
\[ L(w, b) = \frac{1}{n}\sum_{i=1}^n (w^\top x_i + b - y_i)^2. \]
Gradient with respect to \(w\):
\[ \nabla_w L = \frac{2}{n} \sum_{i=1}^n (w^\top x_i + b - y_i) x_i. \]
This formula comes directly from matrix calculus. Without it, we would have to expand each term manually, which becomes infeasible for large models.
Exercises
- Warm-up: For scalar \(x\), compute \(\frac{d}{dx}(3x^2 + 5x)\).
- Vector gradient: Let \(f(w) = \|w\|^2 = w^\top w\). Compute \(\nabla_w f(w)\).
- Matrix gradient (linear form): Let \(f(W) = w^\top Wx\) where \(w, x\) are fixed vectors. Find \(\nabla_W f(W)\).
- Chain rule: Suppose \(f(u) = \sigma(u)\) where \(\sigma(u) = 1/(1+e^{-u})\). If \(u = w^\top x\), compute \(\nabla_w f(u)\).
- Applied: Show that for mean squared error in linear regression, the gradient with respect to \(b\) is \(\nabla_b L = \frac{2}{n} \sum_{i=1}^n (w^\top x_i + b - y_i)\).
Here’s the draft for Section 1.2 of The Little Book of Matrix Calculus for Machine Learning, continuing from 1.1. I’ve kept the same structured style: explanation → examples → exercises.
1.2 Scalars, Vectors, Matrices, and Tensors in ML
To use matrix calculus effectively, we must be precise about the objects we differentiate. Machine learning models work with scalars, vectors, matrices, and, increasingly, higher-order tensors. Each has its own notational conventions and derivative rules.
Scalars
A scalar is a single number. We usually denote scalars with lowercase letters:
\[ x \in \mathbb{R}. \]
Examples in ML:
- A learning rate \(\eta\).
- A single parameter value in a model.
- A loss function value \(L\).
Derivative: For \(f(x) = x^2\),
\[ \frac{df}{dx} = 2x. \]
Vectors
A vector is an ordered list of scalars. We write vectors as bold lowercase letters:
\[ \mathbf{w} = \begin{bmatrix} w_1 \\ w_2 \\ \vdots \\ w_d \end{bmatrix} \in \mathbb{R}^d. \]
Examples in ML:
- Weight vector \(\mathbf{w}\) in linear regression.
- Input feature vector \(\mathbf{x}\).
Derivative: For \(f(\mathbf{w}) = \mathbf{w}^\top \mathbf{w}\),
\[ \nabla_{\mathbf{w}} f = 2\mathbf{w}. \]
Matrices
A matrix is a rectangular array of numbers. We use uppercase letters:
\[ W = \begin{bmatrix} w_{11} & w_{12} & \cdots & w_{1d} \\ w_{21} & w_{22} & \cdots & w_{2d} \\ \vdots & \vdots & \ddots & \vdots \\ w_{m1} & w_{m2} & \cdots & w_{md} \end{bmatrix} \in \mathbb{R}^{m \times d}. \]
Examples in ML:
- Weight matrix in a fully connected layer.
- Design matrix of training data (rows = samples, columns = features).
Derivative: For \(f(W) = \mathrm{tr}(W^\top W)\),
\[ \nabla_W f = 2W. \]
Tensors
A tensor generalizes scalars (0th-order), vectors (1st-order), and matrices (2nd-order) to higher dimensions.
- Order 0: scalar
- Order 1: vector
- Order 2: matrix
- Order 3+: tensor
Examples in ML:
- 3D tensors for color images: height \(\times\) width \(\times\) channels.
- 4D tensors in convolutional layers: batch \(\times\) height \(\times\) width \(\times\) channels.
Although much of matrix calculus focuses on vectors and matrices, the same rules extend naturally to tensors.
Shapes and Dimensions
In ML, keeping track of shapes is crucial. Derivatives always have the same shape as the variable they are taken with respect to:
- If \(x \in \mathbb{R}\), then \(\frac{df}{dx} \in \mathbb{R}\).
- If \(\mathbf{w} \in \mathbb{R}^d\), then \(\nabla_{\mathbf{w}} f \in \mathbb{R}^d\).
- If \(W \in \mathbb{R}^{m \times d}\), then \(\nabla_W f \in \mathbb{R}^{m \times d}\).
This rule avoids confusion and ensures results align with model parameters.
Example
Suppose we have a simple neural network layer:
\[ \mathbf{y} = W\mathbf{x} + \mathbf{b}. \]
- \(\mathbf{x} \in \mathbb{R}^d\) (input vector).
- \(W \in \mathbb{R}^{m \times d}\) (weight matrix).
- \(\mathbf{b} \in \mathbb{R}^m\) (bias vector).
- \(\mathbf{y} \in \mathbb{R}^m\) (output vector).
If we compute the gradient of a loss function \(L(\mathbf{y})\) with respect to \(W\), we expect \(\nabla_W L \in \mathbb{R}^{m \times d}\)—the same shape as \(W\). This consistency is one of the powerful features of matrix calculus.
Key Takeaways
- Scalars = single numbers, vectors = ordered lists, matrices = 2D arrays, tensors = higher-order generalizations.
- Shapes must match: the derivative has the same shape as the variable.
- Machine learning models rely on all these structures: scalars for hyperparameters, vectors for features, matrices for layers, tensors for data like images and sequences.
Exercises
- Warm-up: Write a vector of dimension 3 with entries \((2, -1, 4)\). Compute its squared norm \(\|\mathbf{v}\|^2\).
- Matrix shape check: If \(W \in \mathbb{R}^{4 \times 3}\) and \(\mathbf{x} \in \mathbb{R}^3\), what is the shape of \(W\mathbf{x}\)?
- Gradient rule: Let \(f(\mathbf{w}) = \mathbf{a}^\top \mathbf{w}\), where \(\mathbf{a} \in \mathbb{R}^d\). Find \(\nabla_{\mathbf{w}} f\).
- Matrix derivative: Let \(f(W) = \mathrm{tr}(AW)\), where \(A \in \mathbb{R}^{m \times d}\). Compute \(\nabla_W f\).
- Tensor intuition: An RGB image of size \(32 \times 32\) has 3 channels. Represent its shape as a tensor and explain why it is not a simple matrix.
1.3 Notational Conventions
Before diving into matrix calculus rules, it is essential to establish a clear and consistent notation. In machine learning, confusion often arises not from the mathematics itself but from differences in symbols and conventions. This section fixes the notation we will use throughout the book.
Scalars, Vectors, Matrices, and Tensors
- Scalars: lowercase italic letters, e.g. \(x, y, \eta, L\).
- Vectors: bold lowercase letters, e.g. \(\mathbf{x}, \mathbf{w}, \mathbf{b}\).
- Matrices: bold uppercase letters, e.g. \(W, A, X\).
- Tensors (order 3+): calligraphic or bold script, e.g. \(\mathcal{T}, \mathcal{X}\).
Example:
\[ y = \mathbf{w}^\top \mathbf{x} + b, \qquad \mathbf{w} \in \mathbb{R}^d, \ \mathbf{x} \in \mathbb{R}^d, \ b \in \mathbb{R}. \]
Indices
- Vector entries: \(x_i\) is the \(i\)-th element of \(\mathbf{x}\).
- Matrix entries: \(W_{ij}\) is the element in row \(i\), column \(j\).
- Tensors: multi-index notation, e.g. \(\mathcal{X}_{ijk}\).
Example: If \(W \in \mathbb{R}^{m \times d}\), then
\[ (W\mathbf{x})_i = \sum_{j=1}^d W_{ij} x_j. \]
Derivatives and Gradients
We adopt the “numerator layout” convention, which is standard in machine learning:
Gradient of a scalar with respect to a vector:
\[ \nabla_{\mathbf{x}} f(\mathbf{x}) = \begin{bmatrix} \frac{\partial f}{\partial x_1} \\ \frac{\partial f}{\partial x_2} \\ \vdots \\ \frac{\partial f}{\partial x_d} \end{bmatrix} \in \mathbb{R}^d. \]
Jacobian of a vector function \(\mathbf{f}:\mathbb{R}^d \to \mathbb{R}^m\):
\[ J = \frac{\partial \mathbf{f}}{\partial \mathbf{x}^\top} = \begin{bmatrix} \frac{\partial f_1}{\partial x_1} & \cdots & \frac{\partial f_1}{\partial x_d} \\ \vdots & \ddots & \vdots \\ \frac{\partial f_m}{\partial x_1} & \cdots & \frac{\partial f_m}{\partial x_d} \end{bmatrix} \in \mathbb{R}^{m \times d}. \]
Gradient with respect to a matrix: \(\nabla_W f(W)\) has the same shape as \(W\). Each entry is
\[ \left(\nabla_W f\right)_{ij} = \frac{\partial f}{\partial W_{ij}}. \]
Special Operators
Transpose: \(A^\top\).
Trace: \(\mathrm{tr}(A) = \sum_i A_{ii}\).
Determinant: \(\det(A)\).
Norms:
- Vector \(L^2\)-norm: \(\|\mathbf{x}\| = \sqrt{\mathbf{x}^\top \mathbf{x}}\).
- Frobenius norm: \(\|A\|_F = \sqrt{\mathrm{tr}(A^\top A)}\).
These operators frequently appear in optimization and regularization.
Example
Let
\[ f(W) = \|W\mathbf{x} - \mathbf{y}\|^2. \]
- Variables: \(W \in \mathbb{R}^{m \times d}, \ \mathbf{x} \in \mathbb{R}^d, \ \mathbf{y} \in \mathbb{R}^m\).
- By convention, \(\nabla_W f(W)\) will also be \(m \times d\).
- Each element:
\[ \frac{\partial f}{\partial W_{ij}} = 2(W\mathbf{x} - \mathbf{y})_i \cdot x_j. \]
This consistency in shape and notation makes derivations compact and unambiguous.
Key Takeaways
- Always distinguish scalars, vectors, matrices, tensors with clear symbols.
- Gradients and Jacobians follow the numerator layout convention.
- Derivatives always have the same shape as the variable they are taken with respect to.
- Trace and norm operators are powerful tools for expressing compact gradient formulas.
Exercises
- Shape check: If \(f(\mathbf{x}) = \mathbf{a}^\top \mathbf{x}\) with \(\mathbf{a}, \mathbf{x} \in \mathbb{R}^d\), what is the shape of \(\nabla_{\mathbf{x}} f\)?
- Jacobian practice: Let \(\mathbf{f}(\mathbf{x}) = A\mathbf{x}\), where \(A \in \mathbb{R}^{m \times d}\). Write down the Jacobian.
- Matrix derivative: For \(f(W) = \mathrm{tr}(AW)\), what is \(\nabla_W f\)?
- Norm notation: Show that \(\|A\|_F^2 = \mathrm{tr}(A^\top A)\).
- Backprop shape check: In a layer \(\mathbf{y} = W\mathbf{x} + \mathbf{b}\), identify the shapes of \(\nabla_W L, \nabla_{\mathbf{b}} L, \nabla_{\mathbf{x}} L\).
Chapter 2. Review of Linear Algebra Essentials
2.1 Vectors and Dot Products
Vectors are the backbone of machine learning. Almost every model represents data, parameters, or gradients as vectors. To work with them, we need the dot product—a simple operation that connects geometry and algebra, and forms the basis of many derivative rules.
Vectors Recap
A vector in \(\mathbb{R}^d\) is an ordered list of \(d\) real numbers:
\[ \mathbf{x} = \begin{bmatrix} x_1 \\ x_2 \\ \vdots \\ x_d \end{bmatrix}. \]
- The dimension of \(\mathbf{x}\) is \(d\).
- Each entry \(x_i\) is a scalar.
- Examples in ML: feature vectors, embedding vectors, parameter vectors.
The Dot Product
The dot product (also called inner product) of two vectors \(\mathbf{x}, \mathbf{y} \in \mathbb{R}^d\) is:
\[ \mathbf{x}^\top \mathbf{y} = \sum_{i=1}^d x_i y_i. \]
Interpretations:
Algebraic: Weighted sum of corresponding entries.
Geometric:
\[ \mathbf{x}^\top \mathbf{y} = \|\mathbf{x}\| \, \|\mathbf{y}\| \cos \theta, \]
where \(\theta\) is the angle between vectors.
Computational: A single number summarizing similarity between vectors.
Examples in Machine Learning
Linear regression prediction:
\[ \hat{y} = \mathbf{w}^\top \mathbf{x} + b. \]
Here, the dot product \(\mathbf{w}^\top \mathbf{x}\) is the model’s weighted sum of features.
Cosine similarity (in NLP, recommender systems):
\[ \cos(\theta) = \frac{\mathbf{x}^\top \mathbf{y}}{\|\mathbf{x}\|\|\mathbf{y}\|}. \]
Used to measure similarity between embeddings.
Gradient expressions: Many derivatives (like quadratic forms) reduce to dot products.
Norms and Lengths
The Euclidean norm (length) of a vector is defined via the dot product:
\[ \|\mathbf{x}\| = \sqrt{\mathbf{x}^\top \mathbf{x}}. \]
This norm measures the magnitude of a vector, which is important for regularization (e.g. L2 penalty in ML).
Derivatives Involving Dot Products
Dot products are especially nice because their derivatives are simple:
For \(f(\mathbf{x}) = \mathbf{a}^\top \mathbf{x}\):
\[ \nabla_{\mathbf{x}} f = \mathbf{a}. \]
For \(f(\mathbf{x}) = \mathbf{x}^\top \mathbf{x}\):
\[ \nabla_{\mathbf{x}} f = 2\mathbf{x}. \]
These results will be used repeatedly when deriving gradients of loss functions.
Key Takeaways
- The dot product combines two vectors into a scalar, encoding both algebraic and geometric meaning.
- Many ML models are linear in nature, relying on dot products between weights and features.
- Norms, distances, and similarity measures come directly from dot products.
- Gradients of dot products are simple but powerful building blocks in matrix calculus.
Exercises
Compute the dot product of \(\mathbf{x} = [2, -1, 3]^\top\) and \(\mathbf{y} = [4, 0, -2]^\top\).
Show that \(\mathbf{x}^\top \mathbf{y} = \mathbf{y}^\top \mathbf{x}\) for any vectors.
For \(f(\mathbf{x}) = \mathbf{a}^\top \mathbf{x} + c\), compute \(\nabla_{\mathbf{x}} f\).
If \(\mathbf{x} = (1, 2)\) and \(\mathbf{y} = (2, 2)\), compute their cosine similarity.
Prove that the Euclidean distance \(\|\mathbf{x} - \mathbf{y}\|^2\) expands to:
\[ \|\mathbf{x}\|^2 + \|\mathbf{y}\|^2 - 2\mathbf{x}^\top \mathbf{y}. \]
2.2 Matrix Multiplication and Linear Maps
Matrix multiplication is the engine of machine learning models. It provides a compact way to represent linear maps—functions that preserve addition and scalar multiplication. Understanding this operation is essential before we can differentiate with respect to matrices.
Linear Maps
A function \(T: \mathbb{R}^d \to \mathbb{R}^m\) is linear if:
- \(T(\mathbf{x} + \mathbf{y}) = T(\mathbf{x}) + T(\mathbf{y})\).
- \(T(c\mathbf{x}) = cT(\mathbf{x})\) for any scalar \(c\).
Every linear map can be written as matrix multiplication:
\[ T(\mathbf{x}) = W\mathbf{x}, \quad W \in \mathbb{R}^{m \times d}. \]
Matrix Multiplication Definition
If \(W \in \mathbb{R}^{m \times d}\) and \(\mathbf{x} \in \mathbb{R}^d\), then:
\[ (W\mathbf{x})_i = \sum_{j=1}^d W_{ij} x_j. \]
This produces a vector in \(\mathbb{R}^m\).
More generally, if \(A \in \mathbb{R}^{m \times d}\) and \(B \in \mathbb{R}^{d \times n}\), their product \(C = AB \in \mathbb{R}^{m \times n}\) has entries:
\[ C_{ij} = \sum_{k=1}^d A_{ik} B_{kj}. \]
Examples in Machine Learning
Fully connected layer in a neural network:
\[ \mathbf{y} = W\mathbf{x} + \mathbf{b}, \quad W \in \mathbb{R}^{m \times d}. \]
Batch of inputs: If \(X \in \mathbb{R}^{d \times n}\) contains \(n\) column vectors, then
\[ Y = WX \in \mathbb{R}^{m \times n} \]
gives all outputs at once.
Data as a design matrix: Rows of \(X \in \mathbb{R}^{n \times d}\) hold samples, and
\[ Xw \in \mathbb{R}^n \]
produces predictions for all samples simultaneously.
Geometric Meaning
Matrix multiplication transforms space:
- Stretching, rotating, or shearing vectors.
- Mapping \(\mathbb{R}^d\) into \(\mathbb{R}^m\).
Each row of \(W\) defines one output coordinate as a linear combination of input coordinates.
Derivatives and Gradients
Matrix multiplication appears in nearly every gradient calculation. Useful facts:
For \(f(W) = W\mathbf{x}\),
\[ \frac{\partial f}{\partial W_{ij}} = x_j. \]
For a scalar function \(f(\mathbf{y})\) where \(\mathbf{y} = W\mathbf{x}\):
\[ \nabla_W f = \nabla_\mathbf{y} f \cdot \mathbf{x}^\top. \]
This is the foundation of backpropagation in linear layers.
Example
Let
\[ f(W) = \|W\mathbf{x} - \mathbf{y}\|^2. \]
Step 1: Expand:
\[ f(W) = (W\mathbf{x} - \mathbf{y})^\top (W\mathbf{x} - \mathbf{y}). \]
Step 2: Differentiate using chain rule:
\[ \nabla_W f = 2(W\mathbf{x} - \mathbf{y}) \mathbf{x}^\top. \]
This formula is ubiquitous in machine learning—essentially the gradient of squared error with respect to weights.
Key Takeaways
- Linear maps are represented by matrices; matrix multiplication implements them.
- Each row of a matrix defines a linear equation for the output.
- In ML, matrix multiplication is used for layers, batches, and data transformations.
- Gradients involving \(W\mathbf{x}\) reduce neatly to outer products, forming the basis of backpropagation.
Exercises
Compute \(C = AB\) where
\[ A = \begin{bmatrix}1 & 2 \\ 0 & -1 \end{bmatrix}, \quad B = \begin{bmatrix} 2 & 0 \\ 1 & 3 \end{bmatrix}. \]
If \(W \in \mathbb{R}^{2 \times 3}\) and \(\mathbf{x} \in \mathbb{R}^3\), what is the shape of \(W\mathbf{x}\)?
Show that the composition of two linear maps is another linear map, and identify its matrix.
Let \(f(W) = \mathbf{a}^\top W\mathbf{x}\). Find \(\nabla_W f\).
Derive the gradient of \(f(W) = \|WX - Y\|_F^2\), where \(X, Y\) are given matrices.
2.3 Transpose, Trace, and Determinant
Beyond multiplication, three matrix operations—transpose, trace, and determinant—play a central role in machine learning and matrix calculus. They provide compact ways to express derivatives and appear in optimization, regularization, and probabilistic models.
The Transpose
For a matrix \(A \in \mathbb{R}^{m \times n}\), the transpose \(A^\top \in \mathbb{R}^{n \times m}\) is defined by:
\[ (A^\top)_{ij} = A_{ji}. \]
Properties:
- \((A^\top)^\top = A\).
- \((AB)^\top = B^\top A^\top\).
- \((\mathbf{x}^\top \mathbf{y})^\top = \mathbf{y}^\top \mathbf{x}\) (dot product symmetry).
Example in ML: In least squares,
\[ \hat{\mathbf{w}} = (X^\top X)^{-1} X^\top \mathbf{y}. \]
The transpose moves between feature space and sample space.
The Trace
For \(A \in \mathbb{R}^{n \times n}\), the trace is the sum of diagonal elements:
\[ \mathrm{tr}(A) = \sum_{i=1}^n A_{ii}. \]
Key properties:
- \(\mathrm{tr}(A^\top) = \mathrm{tr}(A)\).
- \(\mathrm{tr}(AB) = \mathrm{tr}(BA)\) (cyclic property).
- \(\mathrm{tr}(\mathbf{x}\mathbf{y}^\top) = \mathbf{y}^\top \mathbf{x}\).
Why useful? Many matrix derivatives simplify to trace form:
\[ \nabla_X \, \mathrm{tr}(AX) = A^\top. \]
Example in ML: Regularization terms, like Frobenius norm:
\[ \|W\|_F^2 = \mathrm{tr}(W^\top W). \]
The Determinant
For \(A \in \mathbb{R}^{n \times n}\), the determinant is a scalar denoted \(\det(A)\). Geometrically, it represents the volume scaling factor of the linear map \(A\).
Properties:
- \(\det(AB) = \det(A)\det(B)\).
- \(\det(A^\top) = \det(A)\).
- \(A\) invertible \(\iff \det(A) \neq 0\).
Derivatives:
Gradient of \(\det(A)\):
\[ \nabla_A \det(A) = \det(A) (A^{-1})^\top. \]
Gradient of \(\log \det(A)\):
\[ \nabla_A \log \det(A) = (A^{-1})^\top. \]
Example in ML: In probabilistic models, Gaussian log-likelihood includes:
\[ -\tfrac{1}{2} \log \det(\Sigma). \]
This is why \(\log \det\) derivatives are fundamental.
Example
Consider a Gaussian distribution with covariance matrix \(\Sigma\):
\[ \log p(\mathbf{x}) = -\tfrac{1}{2} \left[ (\mathbf{x}-\mu)^\top \Sigma^{-1} (\mathbf{x}-\mu) + \log \det(\Sigma) + d\log(2\pi) \right]. \]
- The quadratic term uses transpose.
- The log determinant term uses determinant derivative.
- Matrix calculus makes both differentiable with respect to \(\Sigma\).
Key Takeaways
- Transpose flips dimensions and is essential in dot products and adjoints.
- Trace compactly encodes sums of diagonals, and is powerful in expressing derivatives.
- Determinant connects linear maps to geometry and probabilistic modeling.
- Derivatives involving these operations are standard building blocks for ML.
Exercises
- Show that \(\mathrm{tr}(AB) = \mathrm{tr}(BA)\) when \(A \in \mathbb{R}^{m \times n}\), \(B \in \mathbb{R}^{n \times m}\).
- Compute \(\nabla_X \, \mathrm{tr}(AX^\top)\), where \(A\) is fixed.
- For \(f(W) = \|W\|_F^2\), show that \(\nabla_W f = 2W\).
- If \(A = \begin{bmatrix} 2 & 1 \\ 0 & 3 \end{bmatrix}\), compute \(\det(A)\) and \(\nabla_A \log \det(A)\).
- Explain why \(\log \det(\Sigma)\) appears in the Gaussian log-likelihood.
2.4 Norms and Inner Products
Norms measure the size of vectors and matrices, while inner products measure their similarity. Both are fundamental in optimization, regularization, and gradient-based learning.
Vector Norms
The most common norm is the \(L^2\) norm (Euclidean norm):
\[ \|\mathbf{x}\|_2 = \sqrt{\mathbf{x}^\top \mathbf{x}}. \]
Other norms:
- \(L^1\) norm: \(\|\mathbf{x}\|_1 = \sum_i |x_i|\).
- \(L^\infty\) norm: \(\|\mathbf{x}\|_\infty = \max_i |x_i|\).
Why important in ML?
- \(L^2\) is used in ridge regression (weight decay).
- \(L^1\) is used in LASSO for sparsity.
Matrix Norms
The most common is the Frobenius norm:
\[ \|W\|_F = \sqrt{\sum_{i,j} W_{ij}^2} = \sqrt{\mathrm{tr}(W^\top W)}. \]
Other useful matrix norms:
- Spectral norm: largest singular value of \(W\).
- Nuclear norm: sum of singular values (used in low-rank approximations).
Example in ML: Regularizing neural networks often involves penalties like
\[ \lambda \|W\|_F^2. \]
Inner Products
The dot product is a special case of an inner product. In general:
For vectors:
\[ \langle \mathbf{x}, \mathbf{y} \rangle = \mathbf{x}^\top \mathbf{y}. \]
For matrices (Frobenius inner product):
\[ \langle A, B \rangle = \mathrm{tr}(A^\top B) = \sum_{i,j} A_{ij} B_{ij}. \]
This generalizes the idea of similarity to higher dimensions.
Derivatives of Norms
Norms are differentiable (except at singular points like \(\mathbf{x} = 0\) for \(L^1\)):
For \(f(\mathbf{x}) = \|\mathbf{x}\|_2^2 = \mathbf{x}^\top \mathbf{x}\):
\[ \nabla_{\mathbf{x}} f = 2\mathbf{x}. \]
For \(f(W) = \|W\|_F^2 = \mathrm{tr}(W^\top W)\):
\[ \nabla_W f = 2W. \]
These formulas are widely used in gradient descent with regularization.
Examples in Machine Learning
Regularization in regression: Ridge regression minimizes:
\[ L(w) = \|Xw - y\|^2 + \lambda \|w\|^2. \]
Weight decay in deep learning: Neural network loss functions often add \(\lambda \|W\|_F^2\) to discourage overfitting.
Similarity search:
- Cosine similarity = normalized inner product.
- Euclidean distance = norm difference.
Key Takeaways
- Norms measure size; inner products measure similarity.
- \(L^2\) norm is the default in ML, but \(L^1\) encourages sparsity.
- Frobenius norm is the natural extension of the Euclidean norm to matrices.
- Gradients of norms are simple and form the basis of many regularizers.
Exercises
- Compute \(\|\mathbf{x}\|_1, \|\mathbf{x}\|_2, \|\mathbf{x}\|_\infty\) for \(\mathbf{x} = (3, -4, 0)\).
- Show that \(\|W\|_F^2 = \mathrm{tr}(W^\top W)\) for any \(W\).
- Compute \(\nabla_{\mathbf{x}} \|\mathbf{x}\|_2^2\).
- For \(L(w) = \|Xw - y\|^2 + \lambda \|w\|^2\), derive \(\nabla_w L\).
- Explain why \(L^1\) regularization tends to produce sparse solutions, while \(L^2\) does not.
Chapter 3. Limits and Differentiation Basics
3.1 From Scalar Calculus to Vector Calculus
Calculus begins with scalar functions of a scalar variable. In machine learning, we extend these ideas to vector-valued variables and matrix-valued functions. The key is to see differentiation as a generalization of linear approximation.
Scalar Functions
For \(f:\mathbb{R} \to \mathbb{R}\), the derivative at \(x\) is:
\[ f'(x) = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h}. \]
This gives the slope of the tangent line and the rate of change of \(f\).
From Scalars to Vectors
For \(f:\mathbb{R}^d \to \mathbb{R}\), the derivative is no longer a single number but a gradient vector:
\[ \nabla_{\mathbf{x}} f(\mathbf{x}) = \begin{bmatrix} \frac{\partial f}{\partial x_1} \\ \frac{\partial f}{\partial x_2} \\ \vdots \\ \frac{\partial f}{\partial x_d} \end{bmatrix}. \]
The gradient points in the direction of steepest ascent.
Example: If \(f(\mathbf{x}) = \mathbf{a}^\top \mathbf{x}\), then
\[ \nabla_{\mathbf{x}} f = \mathbf{a}. \]
Vector-Valued Functions
For \(\mathbf{f}:\mathbb{R}^d \to \mathbb{R}^m\), the derivative is the Jacobian matrix:
\[ J = \frac{\partial \mathbf{f}}{\partial \mathbf{x}^\top} = \begin{bmatrix} \frac{\partial f_1}{\partial x_1} & \cdots & \frac{\partial f_1}{\partial x_d} \\ \vdots & \ddots & \vdots \\ \frac{\partial f_m}{\partial x_1} & \cdots & \frac{\partial f_m}{\partial x_d} \end{bmatrix}. \]
Each row gives the gradient of one output with respect to the inputs.
Example: If \(\mathbf{f}(\mathbf{x}) = A\mathbf{x}\), with \(A \in \mathbb{R}^{m \times d}\), then
\[ J = A. \]
Linear Approximation Viewpoint
Differentiation means approximating a function locally by a linear map:
\[ f(\mathbf{x} + \Delta \mathbf{x}) \approx f(\mathbf{x}) + \nabla f(\mathbf{x})^\top \Delta \mathbf{x}. \]
For vector functions:
\[ \mathbf{f}(\mathbf{x} + \Delta \mathbf{x}) \approx \mathbf{f}(\mathbf{x}) + J \Delta \mathbf{x}. \]
This perspective makes gradients and Jacobians natural generalizations of the derivative.
Key Takeaways
- Derivatives generalize from slopes of lines to gradients and Jacobians.
- A scalar function’s derivative becomes a gradient vector.
- A vector function’s derivative becomes a Jacobian matrix.
- Linear approximation unifies scalar and vector calculus.
Exercises
Compute \(\nabla_{\mathbf{x}} (\mathbf{a}^\top \mathbf{x})\).
Let \(f(\mathbf{x}) = \|\mathbf{x}\|^2\). Find \(\nabla_{\mathbf{x}} f\).
If \(\mathbf{f}(\mathbf{x}) = A\mathbf{x}\), show that its Jacobian is \(A\).
Verify the linear approximation: for \(f(x) = x^2\), check that
\[ f(x+h) \approx f(x) + f'(x)h \]
when \(h\) is small.
For \(\mathbf{f}(\mathbf{x}) = (x_1^2, x_1x_2, e^{x_2})^\top\), compute the Jacobian.
3.2 Derivatives as Linear Maps
The most general way to think about derivatives is as linear maps. A derivative is not just a number or a vector; it is the best linear approximation of how a function changes with its input.
Scalar Case
For \(f:\mathbb{R} \to \mathbb{R}\), the derivative at \(x\) is a scalar \(f'(x)\). The approximation is:
\[ f(x+h) \approx f(x) + f'(x)h. \]
Here, the derivative is a linear map \(h \mapsto f'(x)h\).
Vector-to-Scalar Case
For \(f:\mathbb{R}^d \to \mathbb{R}\), the derivative is the gradient vector:
\[ \nabla f(\mathbf{x}) = \begin{bmatrix} \frac{\partial f}{\partial x_1} \\ \vdots \\ \frac{\partial f}{\partial x_d} \end{bmatrix}. \]
The linear approximation is:
\[ f(\mathbf{x} + \Delta \mathbf{x}) \approx f(\mathbf{x}) + \nabla f(\mathbf{x})^\top \Delta \mathbf{x}. \]
Thus the gradient represents a linear functional on perturbations \(\Delta \mathbf{x}\).
Vector-to-Vector Case
For \(\mathbf{f}:\mathbb{R}^d \to \mathbb{R}^m\), the derivative is the Jacobian matrix \(J\):
\[ \mathbf{f}(\mathbf{x} + \Delta \mathbf{x}) \approx \mathbf{f}(\mathbf{x}) + J \Delta \mathbf{x}. \]
Here, \(J\) is the linear map that approximates how small changes in input affect the output vector.
Example: If \(\mathbf{f}(\mathbf{x}) = A\mathbf{x}\), then the Jacobian is exactly \(A\).
Matrix-to-Scalar Case
For \(f:\mathbb{R}^{m \times n} \to \mathbb{R}\), the derivative is a matrix of the same shape:
\[ \nabla_W f = \left[ \frac{\partial f}{\partial W_{ij}} \right]. \]
The approximation is:
\[ f(W + \Delta W) \approx f(W) + \langle \nabla_W f, \Delta W \rangle, \]
where \(\langle A, B \rangle = \mathrm{tr}(A^\top B)\) is the Frobenius inner product.
Matrix-to-Matrix Case
For \(F:\mathbb{R}^{m \times n} \to \mathbb{R}^{p \times q}\), the derivative is a linear operator mapping \(\Delta W\) to \(\Delta F\). This operator can be represented by a large block matrix, but in practice we use compact rules (chain rule, product rule) instead.
Key Takeaways
- Derivatives generalize as linear maps: slope → gradient → Jacobian → operator.
- Gradients are linear functionals, Jacobians are linear operators.
- Approximations use inner products: vector dot product or Frobenius inner product.
- This perspective makes matrix calculus systematic and unifying.
Exercises
Show that \(f(\mathbf{x}) = \mathbf{a}^\top \mathbf{x}\) satisfies
\[ f(\mathbf{x} + \Delta \mathbf{x}) = f(\mathbf{x}) + \mathbf{a}^\top \Delta \mathbf{x}. \]
Verify that for \(f(W) = \mathrm{tr}(AW)\), the linear approximation is
\[ f(W+\Delta W) = f(W) + \mathrm{tr}(A^\top \Delta W). \]
Compute the Jacobian of \(\mathbf{f}(x_1, x_2) = (x_1^2, \sin(x_2))^\top\).
For \(f(W) = \|W\|_F^2\), show that
\[ f(W + \Delta W) \approx f(W) + \langle 2W, \Delta W \rangle. \]
Explain why viewing derivatives as linear maps helps unify scalar, vector, and matrix calculus.
3.3 Gradients and Jacobians
Gradients and Jacobians are the two most common derivative structures in machine learning. They capture how functions change with respect to vectors and are the building blocks of backpropagation.
Gradient
For a scalar function \(f:\mathbb{R}^d \to \mathbb{R}\), the derivative is the gradient vector:
\[ \nabla_{\mathbf{x}} f(\mathbf{x}) = \begin{bmatrix} \frac{\partial f}{\partial x_1} \\ \frac{\partial f}{\partial x_2} \\ \vdots \\ \frac{\partial f}{\partial x_d} \end{bmatrix}. \]
Properties:
- Shape: same dimension as \(\mathbf{x}\).
- Direction: points to steepest ascent of \(f\).
- Magnitude: equals rate of change in that direction.
Example: If \(f(\mathbf{x}) = \|\mathbf{x}\|^2\), then \(\nabla f = 2\mathbf{x}\).
Jacobian
For a vector function \(\mathbf{f}:\mathbb{R}^d \to \mathbb{R}^m\), the derivative is the Jacobian matrix:
\[ J = \frac{\partial \mathbf{f}}{\partial \mathbf{x}^\top} = \begin{bmatrix} \frac{\partial f_1}{\partial x_1} & \cdots & \frac{\partial f_1}{\partial x_d} \\ \vdots & \ddots & \vdots \\ \frac{\partial f_m}{\partial x_1} & \cdots & \frac{\partial f_m}{\partial x_d} \end{bmatrix}. \]
- Each row is the gradient of one component function \(f_i\).
- Shape: \(m \times d\).
Example: If \(\mathbf{f}(\mathbf{x}) = A\mathbf{x}\), with \(A \in \mathbb{R}^{m \times d}\), then
\[ J = A. \]
Relationship Between Gradient and Jacobian
- A gradient is a special case of a Jacobian when \(m=1\).
- Gradient: column vector in \(\mathbb{R}^d\).
- Jacobian: full matrix in \(\mathbb{R}^{m \times d}\).
Thus, the Jacobian generalizes the gradient to vector outputs.
Chain Rule with Jacobians
If \(\mathbf{y} = \mathbf{f}(\mathbf{x})\) and \(\mathbf{z} = \mathbf{g}(\mathbf{y})\), then:
\[ \frac{\partial \mathbf{z}}{\partial \mathbf{x}^\top} = \frac{\partial \mathbf{z}}{\partial \mathbf{y}^\top} \cdot \frac{\partial \mathbf{y}}{\partial \mathbf{x}^\top}. \]
This chain rule underlies backpropagation in neural networks.
Example
Let \(\mathbf{f}:\mathbb{R}^2 \to \mathbb{R}^2\) be defined by:
\[ \mathbf{f}(x_1, x_2) = \begin{bmatrix} x_1^2 + x_2 \\ \sin(x_1) + e^{x_2} \end{bmatrix}. \]
The Jacobian is:
\[ J = \begin{bmatrix} 2x_1 & 1 \\ \cos(x_1) & e^{x_2} \end{bmatrix}. \]
Key Takeaways
- Gradients: derivatives of scalar-valued functions.
- Jacobians: derivatives of vector-valued functions.
- Gradients are special cases of Jacobians.
- Chain rule with Jacobians is the basis of backpropagation.
Exercises
- Compute \(\nabla f(\mathbf{x})\) for \(f(\mathbf{x}) = \mathbf{a}^\top \mathbf{x} + b\).
- For \(f(\mathbf{x}) = \|\mathbf{x}\|^2\), verify that the gradient is \(2\mathbf{x}\).
- Let \(\mathbf{f}(x_1, x_2) = (x_1x_2, \, x_1 + x_2^2)^\top\). Find the Jacobian.
- Show that the Jacobian of \(\mathbf{f}(\mathbf{x}) = A\mathbf{x}\) is \(A\).
- Use the chain rule to compute \(\nabla f(\mathbf{x})\) for \(f(\mathbf{x}) = \sigma(\mathbf{a}^\top \mathbf{x})\), where \(\sigma(u) = 1/(1+e^{-u})\).
3.4 Higher-Order Derivatives (Hessians)
First-order derivatives (gradients and Jacobians) capture local rates of change. Second-order derivatives capture curvature, which is essential for understanding optimization landscapes in machine learning. The most important object here is the Hessian matrix.
Second Derivatives in One Dimension
For \(f:\mathbb{R} \to \mathbb{R}\), the second derivative is:
\[ f''(x) = \frac{d^2 f}{dx^2}. \]
It measures curvature:
- \(f''(x) > 0\): convex (curves upward).
- \(f''(x) < 0\): concave (curves downward).
The Hessian Matrix
For \(f:\mathbb{R}^d \to \mathbb{R}\), the Hessian is the square matrix of second partial derivatives:
\[ H(f)(\mathbf{x}) = \begin{bmatrix} \frac{\partial^2 f}{\partial x_1^2} & \frac{\partial^2 f}{\partial x_1 \partial x_2} & \cdots & \frac{\partial^2 f}{\partial x_1 \partial x_d} \\ \frac{\partial^2 f}{\partial x_2 \partial x_1} & \frac{\partial^2 f}{\partial x_2^2} & \cdots & \frac{\partial^2 f}{\partial x_2 \partial x_d} \\ \vdots & \vdots & \ddots & \vdots \\ \frac{\partial^2 f}{\partial x_d \partial x_1} & \frac{\partial^2 f}{\partial x_d \partial x_2} & \cdots & \frac{\partial^2 f}{\partial x_d^2} \end{bmatrix}. \]
Properties:
- Shape: \(d \times d\).
- Symmetric if \(f\) has continuous second derivatives (Clairaut’s theorem).
- Encodes local curvature in all directions.
Quadratic Approximation
The Hessian enables a second-order Taylor expansion:
\[ f(\mathbf{x} + \Delta \mathbf{x}) \approx f(\mathbf{x}) + \nabla f(\mathbf{x})^\top \Delta \mathbf{x} + \tfrac{1}{2} \Delta \mathbf{x}^\top H(f)(\mathbf{x}) \, \Delta \mathbf{x}. \]
- First term: value.
- Second term: slope (linear approximation).
- Third term: curvature correction.
Example
Let \(f(\mathbf{x}) = \tfrac{1}{2}\mathbf{x}^\top Q \mathbf{x}\), where \(Q\) is symmetric.
- Gradient: \(\nabla f = Q\mathbf{x}\).
- Hessian: \(H = Q\).
Thus quadratic forms have constant Hessians.
Role in Optimization
- The Hessian indicates whether a stationary point is a minimum, maximum, or saddle point.
- Positive definite Hessian → local minimum.
- Negative definite Hessian → local maximum.
- Mixed eigenvalues → saddle point.
In ML, this analysis explains why loss surfaces can have flat regions and saddle points.
Key Takeaways
- Hessians are second-order generalizations of derivatives.
- They measure curvature and guide optimization algorithms.
- Quadratic approximation connects gradients and Hessians.
- In ML, Hessians appear in Newton’s method, natural gradient methods, and curvature-aware optimizers.
Exercises
- Compute the Hessian of \(f(x) = x^3\).
- For \(f(\mathbf{x}) = x_1^2 + 3x_1x_2 + 2x_2^2\), compute the gradient and Hessian.
- Show that if \(f(\mathbf{x}) = \tfrac{1}{2}\mathbf{x}^\top Q \mathbf{x}\), then the Hessian is \(Q\).
- Explain why the Hessian of a linear function \(f(\mathbf{x}) = \mathbf{a}^\top \mathbf{x}\) is zero.
- Consider \(f(\mathbf{x}) = \log(1 + e^{\mathbf{a}^\top \mathbf{x}})\). Compute its gradient and Hessian.
Part II. Matrix Calculus
Chapter 4. Gradients with Respect to Vectors
4.1 Gradient of Linear Functions
The simplest and most fundamental objects in matrix calculus are linear functions. They are building blocks for more complex models, and their derivatives are straightforward yet essential for optimization in machine learning.
Scalar Linear Function
For \(f:\mathbb{R}^d \to \mathbb{R}\),
\[ f(\mathbf{x}) = \mathbf{a}^\top \mathbf{x} + b, \]
where \(\mathbf{a} \in \mathbb{R}^d\) and \(b \in \mathbb{R}\).
Gradient:
\[ \nabla_{\mathbf{x}} f = \mathbf{a}. \]
The derivative is simply the coefficient vector.
Vector Linear Function
For \(\mathbf{f}:\mathbb{R}^d \to \mathbb{R}^m\),
\[ \mathbf{f}(\mathbf{x}) = A\mathbf{x} + \mathbf{b}, \]
where \(A \in \mathbb{R}^{m \times d}\) and \(\mathbf{b} \in \mathbb{R}^m\).
Jacobian:
\[ \frac{\partial \mathbf{f}}{\partial \mathbf{x}^\top} = A. \]
Each row of \(A\) gives the gradient of one component of \(\mathbf{f}\).
Matrix-By-Vector Case
For a scalar function of a matrix,
\[ f(W) = \mathbf{a}^\top W\mathbf{x}, \]
with \(\mathbf{a} \in \mathbb{R}^m\), \(\mathbf{x} \in \mathbb{R}^d\), and \(W \in \mathbb{R}^{m \times d}\).
Gradient with respect to \(W\):
\[ \nabla_W f = \mathbf{a}\mathbf{x}^\top. \]
This is an outer product of two vectors.
Example in Machine Learning
In linear regression,
\[ \hat{y} = \mathbf{w}^\top \mathbf{x} + b, \]
the gradient with respect to \(\mathbf{w}\) is:
\[ \nabla_{\mathbf{w}} \hat{y} = \mathbf{x}. \]
In matrix form, for a batch \(X \in \mathbb{R}^{n \times d}\),
\[ \hat{\mathbf{y}} = X\mathbf{w}, \qquad \nabla_{\mathbf{w}} \hat{\mathbf{y}} = X^\top. \]
Key Takeaways
- Linear functions have constant derivatives.
- Gradient of a dot product is the coefficient vector.
- Gradients with respect to matrices often reduce to outer products.
- These results are used repeatedly in regression and neural network layers.
Exercises
- Compute \(\nabla_{\mathbf{x}} (\mathbf{c}^\top \mathbf{x})\).
- For \(\mathbf{f}(\mathbf{x}) = A\mathbf{x}\), find the Jacobian.
- Show that if \(f(W) = \mathbf{a}^\top W\mathbf{x}\), then \(\nabla_W f = \mathbf{a}\mathbf{x}^\top\).
- In linear regression, derive \(\nabla_{\mathbf{w}} (y - \mathbf{w}^\top \mathbf{x})^2\).
- For \(f(\mathbf{x}) = \mathbf{1}^\top \mathbf{x}\), what is \(\nabla_{\mathbf{x}} f\)?
4.2 Gradient of Quadratic Forms
Quadratic functions are fundamental in optimization. They combine linear terms with squared terms and capture curvature. Their gradients form the basis of least squares, ridge regression, and many loss functions in machine learning.
Scalar Quadratic Form
For \(f:\mathbb{R}^d \to \mathbb{R}\),
\[ f(\mathbf{x}) = \mathbf{x}^\top A \mathbf{x}, \]
where \(A \in \mathbb{R}^{d \times d}\).
Gradient:
\[ \nabla_{\mathbf{x}} f = (A + A^\top)\mathbf{x}. \]
- If \(A\) is symmetric: \(\nabla f = 2A\mathbf{x}\).
- If \(A = I\): \(\nabla f = 2\mathbf{x}\), the standard Euclidean gradient.
Adding Linear and Constant Terms
General quadratic function:
\[ f(\mathbf{x}) = \tfrac{1}{2}\mathbf{x}^\top Q \mathbf{x} + \mathbf{b}^\top \mathbf{x} + c, \]
with \(Q \in \mathbb{R}^{d \times d}\) symmetric.
Gradient:
\[ \nabla_{\mathbf{x}} f = Q\mathbf{x} + \mathbf{b}. \]
Hessian:
\[ H(f) = Q. \]
Matrix Form with Trace
Quadratics can be written compactly using the trace operator:
\[ f(\mathbf{x}) = \mathbf{x}^\top A \mathbf{x} = \mathrm{tr}(\mathbf{x}^\top A \mathbf{x}) = \mathrm{tr}(A \mathbf{x}\mathbf{x}^\top). \]
This makes differentiation with respect to \(A\) easier.
Gradient with respect to \(A\):
\[ \nabla_A f = \mathbf{x}\mathbf{x}^\top. \]
Example in Machine Learning
In ridge regression, the loss is:
\[ L(\mathbf{w}) = \|X\mathbf{w} - \mathbf{y}\|^2 + \lambda \|\mathbf{w}\|^2. \]
Expanding:
\[ L(\mathbf{w}) = \mathbf{w}^\top (X^\top X + \lambda I)\mathbf{w} - 2\mathbf{y}^\top X\mathbf{w} + \|\mathbf{y}\|^2. \]
Gradient:
\[ \nabla_{\mathbf{w}} L = 2(X^\top X + \lambda I)\mathbf{w} - 2X^\top \mathbf{y}. \]
This quadratic gradient drives the update in ridge regression.
Key Takeaways
- Quadratic forms generalize squaring to higher dimensions.
- Gradient is \((A + A^\top)\mathbf{x}\), simplifying to \(2A\mathbf{x}\) if \(A\) is symmetric.
- Trace form is useful for differentiating with respect to matrices.
- Many ML loss functions (least squares, ridge regression) are quadratic.
Exercises
- For \(f(\mathbf{x}) = \mathbf{x}^\top \mathbf{x}\), compute the gradient.
- Show that \(\nabla_{\mathbf{x}} (\mathbf{x}^\top A \mathbf{x}) = (A + A^\top)\mathbf{x}\).
- If \(f(\mathbf{x}) = \tfrac{1}{2}\mathbf{x}^\top Q \mathbf{x} + \mathbf{b}^\top \mathbf{x}\), find \(\nabla_{\mathbf{x}} f\).
- Compute \(\nabla_A (\mathbf{x}^\top A \mathbf{x})\).
- Derive the gradient of ridge regression loss \(L(\mathbf{w})\).
4.3 Gradient of Norms
Norms measure the size of vectors and matrices. Their gradients are widely used in machine learning, especially in regularization (L1, L2, Frobenius). Understanding these gradients provides the tools to control complexity and avoid overfitting.
Squared \(L^2\) Norm
For a vector \(\mathbf{x} \in \mathbb{R}^d\):
\[ f(\mathbf{x}) = \|\mathbf{x}\|_2^2 = \mathbf{x}^\top \mathbf{x}. \]
Gradient:
\[ \nabla_{\mathbf{x}} f = 2\mathbf{x}. \]
This is the most common norm gradient in optimization.
\(L^2\) Norm
For
\[ f(\mathbf{x}) = \|\mathbf{x}\|_2 = \sqrt{\mathbf{x}^\top \mathbf{x}}, \]
gradient:
\[ \nabla_{\mathbf{x}} f = \frac{\mathbf{x}}{\|\mathbf{x}\|_2}, \quad \mathbf{x} \neq \mathbf{0}. \]
At \(\mathbf{x} = \mathbf{0}\), the derivative is undefined, but any vector with norm \(\leq 1\) is a subgradient.
\(L^1\) Norm
For
\[ f(\mathbf{x}) = \|\mathbf{x}\|_1 = \sum_i |x_i|, \]
the derivative is not unique at zero. The subgradient is:
\[ \frac{\partial f}{\partial x_i} = \begin{cases} 1 & x_i > 0, \\ -1 & x_i < 0, \\ [-1,1] & x_i = 0. \end{cases} \]
This sparsity-inducing property makes \(L^1\) regularization useful.
Frobenius Norm
For a matrix \(W \in \mathbb{R}^{m \times n}\):
\[ f(W) = \|W\|_F^2 = \mathrm{tr}(W^\top W). \]
Gradient:
\[ \nabla_W f = 2W. \]
This is directly analogous to the squared \(L^2\) norm for vectors.
Example in Machine Learning
Neural networks often use weight decay:
\[ L(W) = L_{\text{data}}(W) + \lambda \|W\|_F^2. \]
The regularization term contributes a gradient of \(2\lambda W\), shrinking weights towards zero during training.
Key Takeaways
- Gradients of norms are simple but powerful tools in optimization.
- Squared norms are smooth everywhere and preferred for regularization.
- \(L^1\) norm uses subgradients, leading to sparse solutions.
- Frobenius norm extends \(L^2\) ideas to matrices.
Exercises
- Compute \(\nabla_{\mathbf{x}} \|\mathbf{x}\|_2^2\).
- Show that \(\nabla_{\mathbf{x}} \|\mathbf{x}\|_2 = \frac{\mathbf{x}}{\|\mathbf{x}\|_2}\) for \(\mathbf{x} \neq 0\).
- For \(f(\mathbf{x}) = \|\mathbf{x}\|_1\), write the subgradient at \(\mathbf{x} = (1, 0, -2)\).
- Verify that \(\nabla_W \|W\|_F^2 = 2W\).
- Explain why squared norms are more convenient than raw norms in gradient-based optimization.
Chapter 5. Derivatives with Respect to Matrices
5.1 Matrix-by-Vector Derivatives
Derivatives with respect to matrices appear constantly in machine learning. One of the most common cases is a matrix multiplied by a vector. Understanding these derivatives is key for layers in neural networks and for linear regression.
Linear Form
Consider
\[ f(W) = W\mathbf{x}, \]
where \(W \in \mathbb{R}^{m \times d}\) and \(\mathbf{x} \in \mathbb{R}^d\).
- Output: \(\mathbf{y} \in \mathbb{R}^m\).
- Jacobian:
\[ \frac{\partial \mathbf{y}}{\partial W} = \text{a linear operator mapping }\Delta W \mapsto \Delta W \mathbf{x}. \]
In practice, when used inside a scalar function, the gradient reduces to an outer product.
Scalar Function of Matrix-Vector Product
Let
\[ f(W) = \mathbf{a}^\top W\mathbf{x}, \]
with \(\mathbf{a} \in \mathbb{R}^m\).
Gradient with respect to \(W\):
\[ \nabla_W f = \mathbf{a}\mathbf{x}^\top. \]
Shape: \(m \times d\), same as \(W\).
Quadratic Case
If
\[ f(W) = \|W\mathbf{x} - \mathbf{y}\|^2, \]
then
\[ \nabla_W f = 2(W\mathbf{x} - \mathbf{y})\mathbf{x}^\top. \]
This formula appears in linear regression with multiple features.
Trace Formulation
Matrix-vector derivatives are compactly expressed with traces. For example,
\[ \mathbf{a}^\top W\mathbf{x} = \mathrm{tr}(\mathbf{a}^\top W\mathbf{x}) = \mathrm{tr}(W\mathbf{x}\mathbf{a}^\top). \]
Differentiating with respect to \(W\) yields:
\[ \nabla_W f = \mathbf{a}\mathbf{x}^\top. \]
Example in Machine Learning
In a neural network layer:
\[ \mathbf{h} = W\mathbf{x} + \mathbf{b}, \]
the gradient of the loss \(L\) with respect to \(W\) is:
\[ \nabla_W L = \nabla_\mathbf{h} L \cdot \mathbf{x}^\top, \]
where \(\nabla_\mathbf{h} L\) is the gradient passed from the next layer. This is the backprop rule for fully connected layers.
Key Takeaways
- Gradients with respect to matrices keep the same shape as the matrix.
- Matrix-by-vector derivatives often reduce to outer products.
- Trace notation makes derivatives easier to compute.
- These results are the foundation of backpropagation in linear layers.
Exercises
- For \(f(W) = \mathbf{b}^\top W\mathbf{x}\), compute \(\nabla_W f\).
- Show that \(\nabla_W \|W\mathbf{x}\|^2 = 2W\mathbf{x}\mathbf{x}^\top\).
- For \(f(W) = \|W\mathbf{x} - \mathbf{y}\|^2\), derive the gradient step by step.
- Express \(\mathbf{a}^\top W\mathbf{x}\) using trace notation and differentiate.
- In a neural network, let \(\mathbf{h} = W\mathbf{x} + \mathbf{b}\). Show that backprop gives \(\nabla_W L = \delta \mathbf{x}^\top\), where \(\delta = \nabla_\mathbf{h} L\).
5.2 Derivatives of Trace Functions
The trace operator simplifies many matrix derivatives. Since the trace turns matrices into scalars, it allows us to express gradients in a compact, coordinate-free way. Most matrix calculus identities used in machine learning are derived through trace tricks.
Definition
For \(A \in \mathbb{R}^{n \times n}\),
\[ \mathrm{tr}(A) = \sum_{i=1}^n A_{ii}. \]
Properties:
- Linearity: \(\mathrm{tr}(A + B) = \mathrm{tr}(A) + \mathrm{tr}(B)\).
- Cyclic property: \(\mathrm{tr}(ABC) = \mathrm{tr}(BCA) = \mathrm{tr}(CAB)\).
- Symmetry: \(\mathrm{tr}(A^\top) = \mathrm{tr}(A)\).
Basic Derivatives
\(\nabla_X \, \mathrm{tr}(AX) = A^\top\).
\(\nabla_X \, \mathrm{tr}(X^\top A) = A\).
\(\nabla_X \, \mathrm{tr}(X^\top AX) = (A + A^\top)X\).
\(\nabla_X \, \mathrm{tr}(AX^\top BX) = (A + A^\top)XB^\top\).
These results generalize scalar quadratic forms to matrices.
Examples
Quadratic form as trace
\[ f(\mathbf{x}) = \mathbf{x}^\top A \mathbf{x} = \mathrm{tr}(\mathbf{x}^\top A \mathbf{x}) = \mathrm{tr}(A \mathbf{x}\mathbf{x}^\top). \]
Derivative with respect to \(A\):
\[ \nabla_A f = \mathbf{x}\mathbf{x}^\top. \]
Frobenius norm
\[ f(W) = \|W\|_F^2 = \mathrm{tr}(W^\top W). \]
Gradient:
\[ \nabla_W f = 2W. \]
Why Trace Matters in ML
- Compact way to write matrix derivatives.
- Appears in covariance matrices, regularizers, and quadratic losses.
- Used in proofs of backpropagation identities.
Example: In ridge regression,
\[ L(W) = \|WX - Y\|_F^2 = \mathrm{tr}((WX - Y)^\top (WX - Y)), \]
and differentiating with respect to \(W\) gives:
\[ \nabla_W L = 2(WXX^\top - YX^\top). \]
Key Takeaways
- The trace reduces scalar expressions involving matrices to a compact form.
- Differentiating trace expressions avoids messy index calculations.
- Many ML losses can be expressed and simplified with traces.
Exercises
- Show that \(\nabla_X \, \mathrm{tr}(AX) = A^\top\).
- Verify that \(\nabla_X \, \mathrm{tr}(X^\top AX) = (A + A^\top)X\).
- Compute \(\nabla_W \, \mathrm{tr}(BWX)\), where \(B\) and \(X\) are fixed.
- Express \(\|WX - Y\|_F^2\) as a trace and compute \(\nabla_W\).
- For covariance estimation, \(f(\Sigma) = \mathrm{tr}(\Sigma^{-1}S)\), discuss how the trace derivative appears in optimization.
5.3 Derivatives of Determinants
The determinant connects linear algebra with geometry: it measures how much a matrix scales volume. In probabilistic machine learning, determinants appear in log-likelihoods of multivariate Gaussians and variational inference. Knowing how to differentiate them is crucial.
Determinant Basics
For \(A \in \mathbb{R}^{n \times n}\), \(\det(A)\) is a scalar with properties:
- \(\det(AB) = \det(A)\det(B)\).
- \(\det(A^\top) = \det(A)\).
- \(A\) invertible \(\iff \det(A) \neq 0\).
Derivative of Determinant
For invertible \(A\):
\[ \nabla_A \det(A) = \det(A) (A^{-1})^\top. \]
Interpretation: the gradient scales with the determinant itself and involves the transpose of the inverse.
Derivative of Log Determinant
The log-determinant appears more often, since it simplifies multiplicative structure into additive:
\[ \nabla_A \log \det(A) = (A^{-1})^\top. \]
This is better behaved numerically and analytically.
Example: Quadratic + Log-Det
In Gaussian log-likelihood with covariance \(\Sigma\):
\[ \ell(\Sigma) = -\tfrac{1}{2} \left[ (\mathbf{x}-\mu)^\top \Sigma^{-1} (\mathbf{x}-\mu) + \log \det(\Sigma) + d \log(2\pi) \right]. \]
- First term: derivative involves \(\Sigma^{-1}\).
- Second term: derivative uses \((\Sigma^{-1})^\top\).
Both rely on determinant calculus.
Higher-Order Case
For \(f(A) = \det(A)^k\):
\[ \nabla_A f = k \det(A)^k (A^{-1})^\top. \]
This generalization is useful in some advanced optimization problems.
Key Takeaways
- Determinant derivatives always involve the inverse.
- Log-determinant is more stable and widely used in ML.
- Appears in Gaussian models, graphical models, and variational inference.
Exercises
- Show that \(\nabla_A \det(A) = \det(A)(A^{-1})^\top\).
- Verify that \(\nabla_A \log \det(A) = (A^{-1})^\top\).
- Compute \(\nabla_\Sigma \log \det(\Sigma)\) for a covariance matrix.
- For \(f(A) = \det(A)^2\), derive the gradient.
- Explain why log-determinants are preferred over determinants in machine learning optimization.
5.4 Matrix Calculus Identities
Matrix calculus involves a set of reusable identities that simplify complex derivatives. These identities let us avoid re-deriving results from scratch and are the backbone of efficient derivations in machine learning.
Linear Identities
- \(\nabla_{\mathbf{x}} (\mathbf{a}^\top \mathbf{x}) = \mathbf{a}\).
- \(\nabla_W (\mathbf{a}^\top W \mathbf{x}) = \mathbf{a}\mathbf{x}^\top\).
- \(\nabla_X \, \mathrm{tr}(AX) = A^\top\).
- \(\nabla_X \, \mathrm{tr}(X^\top A) = A\).
Quadratic Identities
- \(\nabla_{\mathbf{x}} (\mathbf{x}^\top A \mathbf{x}) = (A + A^\top)\mathbf{x}\).
- \(\nabla_W \, \mathrm{tr}(W^\top AW) = (A + A^\top)W\).
- \(\nabla_X \, \mathrm{tr}(X^\top A X B) = AXB^\top + A^\top X B\).
Norm Identities
- \(\nabla_{\mathbf{x}} \|\mathbf{x}\|_2^2 = 2\mathbf{x}\).
- \(\nabla_W \|W\|_F^2 = 2W\).
- \(\nabla_{\mathbf{x}} \|\mathbf{x}\|_2 = \tfrac{\mathbf{x}}{\|\mathbf{x}\|_2}, \; \mathbf{x} \neq 0\).
Determinant and Log-Det Identities
- \(\nabla_A \det(A) = \det(A)(A^{-1})^\top\).
- \(\nabla_A \log \det(A) = (A^{-1})^\top\).
Chain Rule Identities
If \(f(\mathbf{x}) = g(h(\mathbf{x}))\), then
\[ \nabla f(\mathbf{x}) = J_h(\mathbf{x})^\top \nabla g(h(\mathbf{x})). \]
For matrix functions:
\[ \nabla_X f(g(X)) = \left(\frac{\partial g}{\partial X}\right)^\top \nabla f. \]
This is the essence of backpropagation.
Useful Trace Tricks
- \(\mathbf{x}^\top A \mathbf{y} = \mathrm{tr}(\mathbf{y}\mathbf{x}^\top A)\).
- \(\|X\|_F^2 = \mathrm{tr}(X^\top X)\).
- Cyclic property: \(\mathrm{tr}(ABC) = \mathrm{tr}(BCA) = \mathrm{tr}(CAB)\).
These tricks allow converting expressions into forms that are easier to differentiate.
Example in Machine Learning
For loss function
\[ L(W) = \|WX - Y\|_F^2, \]
we write
\[ L(W) = \mathrm{tr}((WX - Y)^\top(WX - Y)). \]
Differentiate using identities:
\[ \nabla_W L = 2(WXX^\top - YX^\top). \]
This shortcut avoids tedious index-by-index differentiation.
Key Takeaways
- A small set of identities covers most ML applications.
- Trace tricks simplify derivations and make them elegant.
- Chain rule in matrix form underpins backpropagation.
Exercises
- Show that \(\nabla_X \, \mathrm{tr}(X^\top A X) = (A + A^\top)X\).
- Compute \(\nabla_W \|WX - Y\|_F^2\) using trace identities.
- Verify that \(\nabla_{\mathbf{x}} (\mathbf{x}^\top A \mathbf{y}) = A\mathbf{y}\).
- Derive \(\nabla_X \, \mathrm{tr}(AX B X^\top C)\).
- Explain how trace tricks help avoid index-heavy proofs in backpropagation.
Chapter 6. Jacobian and Hessian Structures
6.1 Jacobians in Multivariate Functions
When functions map vectors to vectors, their derivatives are expressed as Jacobians. The Jacobian generalizes the gradient and plays a central role in multivariate calculus, backpropagation, and transformations in probability.
Definition
For \(\mathbf{f}:\mathbb{R}^d \to \mathbb{R}^m\),
\[ \mathbf{f}(\mathbf{x}) = \begin{bmatrix} f_1(\mathbf{x}) \\ f_2(\mathbf{x}) \\ \vdots \\ f_m(\mathbf{x}) \end{bmatrix}, \]
the Jacobian is
\[ J(\mathbf{x}) = \frac{\partial \mathbf{f}}{\partial \mathbf{x}^\top} = \begin{bmatrix} \frac{\partial f_1}{\partial x_1} & \cdots & \frac{\partial f_1}{\partial x_d} \\ \vdots & \ddots & \vdots \\ \frac{\partial f_m}{\partial x_1} & \cdots & \frac{\partial f_m}{\partial x_d} \end{bmatrix}. \]
- Shape: \(m \times d\).
- Row \(i\) = gradient of \(f_i\).
Gradient as a Special Case
If \(m=1\), the Jacobian reduces to the gradient:
\[ J(\mathbf{x}) = \nabla_{\mathbf{x}} f(\mathbf{x})^\top. \]
Thus, gradients are just Jacobians for scalar-valued functions.
Linear Functions
If \(\mathbf{f}(\mathbf{x}) = A\mathbf{x}\) with \(A \in \mathbb{R}^{m \times d}\):
\[ J = A. \]
The Jacobian of a linear map is the matrix itself.
Nonlinear Example
Let
\[ \mathbf{f}(x_1, x_2) = \begin{bmatrix} x_1^2 + x_2 \\ \sin(x_1) + e^{x_2} \end{bmatrix}. \]
Jacobian:
\[ J = \begin{bmatrix} 2x_1 & 1 \\ \cos(x_1) & e^{x_2} \end{bmatrix}. \]
Chain Rule with Jacobians
If \(\mathbf{y} = \mathbf{f}(\mathbf{x})\), \(\mathbf{z} = \mathbf{g}(\mathbf{y})\):
\[ \frac{\partial \mathbf{z}}{\partial \mathbf{x}^\top} = \frac{\partial \mathbf{z}}{\partial \mathbf{y}^\top} \cdot \frac{\partial \mathbf{y}}{\partial \mathbf{x}^\top}. \]
This is the matrix version of the chain rule and underlies backpropagation.
Determinant of Jacobian
For transformations in probability, the Jacobian determinant gives how volume changes under mapping:
\[ p_{\mathbf{y}}(\mathbf{y}) = p_{\mathbf{x}}(\mathbf{x}) \, \big|\det J(\mathbf{x})\big|^{-1}. \]
This is used in normalizing flows and change of variables.
Key Takeaways
- Jacobians generalize gradients to vector functions.
- Linear functions have constant Jacobians.
- Chain rule with Jacobians is central to backpropagation.
- Determinants of Jacobians appear in probability density transformations.
Exercises
- Compute the Jacobian of \(\mathbf{f}(x_1, x_2) = (x_1 + x_2, x_1x_2)^\top\).
- Verify that the Jacobian of \(\mathbf{f}(\mathbf{x}) = A\mathbf{x}\) is \(A\).
- Use the chain rule to compute the Jacobian of \(\mathbf{f}(\mathbf{x}) = \sigma(A\mathbf{x})\), where \(\sigma\) is applied elementwise.
- Show how the Jacobian determinant appears when transforming a uniform random variable \(U \sim \text{Unif}(0,1)\) via \(Y = g(U)\).
- Explain why Jacobian matrices form the foundation of backpropagation in deep learning.
6.2 Hessian Matrices and Curvature
While Jacobians describe first-order changes, Hessians capture second-order structure — the curvature of scalar functions with respect to vectors. In optimization and machine learning, Hessians explain convexity, saddle points, and curvature-aware optimization methods.
Definition
For a scalar function \(f:\mathbb{R}^d \to \mathbb{R}\), the Hessian matrix is
\[ H(f)(\mathbf{x}) = \begin{bmatrix} \frac{\partial^2 f}{\partial x_1^2} & \frac{\partial^2 f}{\partial x_1 \partial x_2} & \cdots & \frac{\partial^2 f}{\partial x_1 \partial x_d} \\ \frac{\partial^2 f}{\partial x_2 \partial x_1} & \frac{\partial^2 f}{\partial x_2^2} & \cdots & \frac{\partial^2 f}{\partial x_2 \partial x_d} \\ \vdots & \vdots & \ddots & \vdots \\ \frac{\partial^2 f}{\partial x_d \partial x_1} & \frac{\partial^2 f}{\partial x_d \partial x_2} & \cdots & \frac{\partial^2 f}{\partial x_d^2} \end{bmatrix}. \]
- Shape: \(d \times d\).
- Symmetric if \(f\) is twice continuously differentiable.
Quadratic Example
For \(f(\mathbf{x}) = \tfrac{1}{2} \mathbf{x}^\top Q \mathbf{x}\),
- Gradient: \(\nabla f = Q\mathbf{x}\).
- Hessian: \(H = Q\).
If \(Q\) is positive definite, \(f\) is strictly convex.
Curvature and Optimization
- Positive definite Hessian: local minimum.
- Negative definite Hessian: local maximum.
- Indefinite Hessian: saddle point.
In machine learning, saddle points dominate high-dimensional loss surfaces.
Newton’s Method
Second-order methods use Hessians for optimization updates:
\[ \mathbf{x}_{k+1} = \mathbf{x}_k - H(f)^{-1} \nabla f(\mathbf{x}_k). \]
This converges faster than gradient descent if Hessians are well-conditioned, but can be expensive to compute in deep learning.
Generalization to Matrix Variables
For \(f:\mathbb{R}^{m \times n} \to \mathbb{R}\), the Hessian becomes a 4th-order tensor, mapping matrix perturbations to second-order effects. In practice, we use Kronecker or block-matrix structures to handle these cases.
Example in Machine Learning
In logistic regression:
\[ f(\mathbf{w}) = \sum_{i=1}^n \log(1 + e^{-y_i \mathbf{w}^\top \mathbf{x}_i}), \]
Gradient:
\[ \nabla f = -\sum_{i=1}^n \frac{y_i \mathbf{x}_i}{1 + e^{y_i \mathbf{w}^\top \mathbf{x}_i}}. \]
Hessian:
\[ H = \sum_{i=1}^n \sigma(z_i)(1 - \sigma(z_i)) \mathbf{x}_i \mathbf{x}_i^\top, \]
where \(\sigma(z) = \frac{1}{1+e^{-z}}\).
This shows curvature depends on input covariance weighted by prediction uncertainty.
Key Takeaways
- Hessians capture curvature and generalize second derivatives.
- They are central to convexity analysis and Newton’s method.
- In ML, Hessians are expensive to compute but approximate methods (e.g., Fisher information, Gauss–Newton) are common.
Exercises
- Compute the Hessian of \(f(\mathbf{x}) = \| \mathbf{x} \|^2\).
- For \(f(\mathbf{x}) = x_1^2 + 3x_1x_2 + 2x_2^2\), find the Hessian.
- Show that the Hessian of a linear function is zero.
- Derive the Hessian for logistic regression loss on a single data point.
- Explain why Hessian computation is costly in deep neural networks.
6.3 Block Matrix Derivatives
In many machine learning problems, variables are structured as blocks of vectors and matrices. Computing derivatives with respect to these blocks requires extending gradient and Hessian concepts into block-matrix form.
Block Partitioning
Suppose we partition a vector \(\mathbf{x} \in \mathbb{R}^{d}\) into blocks:
\[ \mathbf{x} = \begin{bmatrix} \mathbf{x}_1 \\ \mathbf{x}_2 \\ \vdots \\ \mathbf{x}_k \end{bmatrix}, \]
where each \(\mathbf{x}_i\) may have different dimensions.
The gradient and Hessian naturally split into corresponding blocks:
Gradient:
\[ \nabla_{\mathbf{x}} f = \begin{bmatrix} \nabla_{\mathbf{x}_1} f \\ \nabla_{\mathbf{x}_2} f \\ \vdots \\ \nabla_{\mathbf{x}_k} f \end{bmatrix}. \]
Hessian:
\[ H(f) = \begin{bmatrix} \frac{\partial^2 f}{\partial \mathbf{x}_1 \partial \mathbf{x}_1^\top} & \cdots & \frac{\partial^2 f}{\partial \mathbf{x}_1 \partial \mathbf{x}_k^\top} \\ \vdots & \ddots & \vdots \\ \frac{\partial^2 f}{\partial \mathbf{x}_k \partial \mathbf{x}_1^\top} & \cdots & \frac{\partial^2 f}{\partial \mathbf{x}_k \partial \mathbf{x}_k^\top} \end{bmatrix}. \]
Each block shows interactions between subsets of variables.
Example: Quadratic Form
Let
\[ f(\mathbf{x}_1, \mathbf{x}_2) = \tfrac{1}{2}\mathbf{x}_1^\top A \mathbf{x}_1 + \mathbf{x}_1^\top B \mathbf{x}_2 + \tfrac{1}{2}\mathbf{x}_2^\top C \mathbf{x}_2. \]
Gradient blocks:
\[ \nabla_{\mathbf{x}_1} f = A \mathbf{x}_1 + B \mathbf{x}_2, \]
\[ \nabla_{\mathbf{x}_2} f = B^\top \mathbf{x}_1 + C \mathbf{x}_2. \]
Hessian block structure:
\[ H(f) = \begin{bmatrix} A & B \\ B^\top & C \end{bmatrix}. \]
Example: Partitioned Parameters in ML
In multitask learning, model parameters may be split into task-specific blocks:
\[ \theta = \begin{bmatrix} \theta_{\text{task1}} \\ \theta_{\text{task2}} \end{bmatrix}. \]
Gradients and Hessians respect this block structure, making it easier to analyze cross-task interactions.
Block Derivatives with Matrices
For functions of multiple matrices, e.g.
\[ f(W, V) = \mathrm{tr}(W^\top A V), \]
- Gradient w.r.t. \(W\): \(\nabla_W f = A V\).
- Gradient w.r.t. \(V\): \(\nabla_V f = A^\top W\).
Together, the block derivative structure shows how changes in \(W\) and \(V\) interact.
Key Takeaways
- Block derivatives organize gradients and Hessians by variable groups.
- Quadratic forms illustrate natural block Hessian structures.
- In ML, block derivatives help analyze models with partitioned parameters (e.g., multitask, factorization).
Exercises
- Partition \(\mathbf{x} \in \mathbb{R}^4\) into two 2D blocks and compute the Hessian of \(f(\mathbf{x}) = \|\mathbf{x}\|^2\) in block form.
- For \(f(\mathbf{x}_1, \mathbf{x}_2) = \mathbf{x}_1^\top \mathbf{x}_2\), compute the block Hessian.
- Show that for quadratic functions, block Hessians remain symmetric.
- Compute block gradients of \(f(W, V) = \|WV - Y\|_F^2\).
- Explain how block matrix derivatives help in distributed or multitask learning.
Part III. Applications in Machine Learning
Chapter 7. Optimization and Loss Functions
7.1 Gradients of Mean Squared Error
The mean squared error (MSE) is one of the most widely used loss functions in regression. It measures how far predictions are from actual targets and has simple, elegant gradients.
Definition
For dataset \(\{(\mathbf{x}_i, y_i)\}_{i=1}^n\) with parameters \(\mathbf{w}\):
\[ L(\mathbf{w}) = \frac{1}{n} \sum_{i=1}^n (y_i - \mathbf{w}^\top \mathbf{x}_i)^2. \]
Matrix form:
\[ L(\mathbf{w}) = \frac{1}{n} \|X\mathbf{w} - \mathbf{y}\|^2, \]
where
- \(X \in \mathbb{R}^{n \times d}\) = design matrix (rows are samples),
- \(\mathbf{y} \in \mathbb{R}^n\) = target vector.
Gradient
Expanding:
\[ L(\mathbf{w}) = \frac{1}{n} (X\mathbf{w} - \mathbf{y})^\top (X\mathbf{w} - \mathbf{y}). \]
Differentiate:
\[ \nabla_{\mathbf{w}} L = \frac{2}{n} X^\top (X\mathbf{w} - \mathbf{y}). \]
- Shape: \(d \times 1\), same as \(\mathbf{w}\).
- Direction: points toward reducing prediction error.
Hessian
\[ H(L) = \frac{2}{n} X^\top X. \]
- Positive semidefinite (convex).
- Positive definite if \(X\) has full column rank.
This ensures MSE has a unique minimum solution.
Closed-Form Solution
Setting gradient to zero:
\[ X^\top X \mathbf{w} = X^\top \mathbf{y}. \]
Solution:
\[ \hat{\mathbf{w}} = (X^\top X)^{-1} X^\top \mathbf{y}. \]
This is the ordinary least squares estimator.
Example in ML
In regression networks:
\[ \hat{y}_i = \mathbf{w}^\top \mathbf{x}_i, \quad L = \frac{1}{n} \sum (y_i - \hat{y}_i)^2, \]
backpropagation uses:
\[ \nabla_{\mathbf{w}} L = \frac{2}{n} X^\top (X\mathbf{w} - \mathbf{y}). \]
This is exactly the same gradient as in classical statistics.
Key Takeaways
- MSE loss is convex and differentiable.
- Gradient has a simple closed form.
- Hessian gives curvature and guarantees convexity.
- Linear regression solution can be derived directly from gradients.
Exercises
- Derive \(\nabla_{\mathbf{w}} L\) for one sample \(L(\mathbf{w}) = (y - \mathbf{w}^\top \mathbf{x})^2\).
- Show that the Hessian of MSE is \(H = \tfrac{2}{n} X^\top X\).
- Prove convexity of MSE using Hessian properties.
- Verify that setting \(\nabla L = 0\) yields the normal equations.
- Explain why the closed-form solution may be unstable if \(X^\top X\) is ill-conditioned, and how regularization helps.
7.2 Gradients of Cross-Entropy Loss
The cross-entropy loss is fundamental in classification. It measures the dissimilarity between predicted probability distributions and true labels. Its gradients drive the learning of logistic regression, softmax classifiers, and neural networks.
Binary Cross-Entropy
For binary classification, with label \(y \in \{0,1\}\) and predicted probability \(\hat{y} = \sigma(z)\), where \(\sigma(z) = \frac{1}{1+e^{-z}}\):
\[ L(y, \hat{y}) = - \left[ y \log \hat{y} + (1-y)\log(1-\hat{y}) \right]. \]
Gradient with Respect to Logit
Since \(\hat{y} = \sigma(z)\):
\[ \frac{\partial L}{\partial z} = \hat{y} - y. \]
This remarkably simple form is why logistic regression is efficient.
Gradient with Respect to Weights
If \(z = \mathbf{w}^\top \mathbf{x}\):
\[ \nabla_{\mathbf{w}} L = (\hat{y} - y)\mathbf{x}. \]
Multi-Class Cross-Entropy with Softmax
For \(K\) classes, softmax probabilities:
\[ \hat{y}_k = \frac{e^{z_k}}{\sum_{j=1}^K e^{z_j}}, \quad k=1,\dots,K, \]
with logits \(\mathbf{z} = W\mathbf{x}\).
Cross-entropy loss:
\[ L(y, \hat{\mathbf{y}}) = -\sum_{k=1}^K y_k \log \hat{y}_k, \]
where \(y_k\) is a one-hot encoded label.
Gradient with Respect to Logits
\[ \frac{\partial L}{\partial z_k} = \hat{y}_k - y_k. \]
Gradient with Respect to Weights
If \(\mathbf{z} = W\mathbf{x}\):
\[ \nabla_W L = (\hat{\mathbf{y}} - \mathbf{y}) \mathbf{x}^\top. \]
This is the matrix form of the update used in softmax classifiers.
Example in ML
In a neural network with softmax output:
Forward pass: logits → softmax → probabilities → cross-entropy.
Backward pass:
\[ \delta = \hat{\mathbf{y}} - \mathbf{y}, \]
propagated to the previous layer.
This is the core of training classifiers in deep learning.
Key Takeaways
- Cross-entropy measures mismatch between predicted and true distributions.
- Gradients simplify to prediction minus label: \(\hat{y} - y\).
- In multi-class cases, the gradient is vectorized as \(\hat{\mathbf{y}} - \mathbf{y}\).
- This efficiency makes cross-entropy the dominant classification loss.
Exercises
- Derive \(\frac{\partial L}{\partial z}\) for binary cross-entropy step by step.
- Show that \(\nabla_{\mathbf{w}} L = (\hat{y} - y)\mathbf{x}\) in logistic regression.
- Compute the gradient of the multi-class cross-entropy with respect to logits.
- Verify that \(\nabla_W L = (\hat{\mathbf{y}} - \mathbf{y})\mathbf{x}^\top\).
- Explain why the form \(\hat{y} - y\) is advantageous for backpropagation.
7.3 Regularization Terms (L1, L2, etc.)
Regularization prevents overfitting by penalizing large weights. The most common penalties are based on vector and matrix norms. Their gradients are simple, but their effects on optimization are profound.
L2 Regularization (Ridge, Weight Decay)
Penalty:
\[ R(\mathbf{w}) = \lambda \|\mathbf{w}\|_2^2 = \lambda \mathbf{w}^\top \mathbf{w}. \]
Gradient:
\[ \nabla_{\mathbf{w}} R = 2\lambda \mathbf{w}. \]
Effect: shrinks all weights proportionally; does not promote sparsity.
In neural networks, weight decay implements this gradient update.
L1 Regularization (Lasso)
Penalty:
\[ R(\mathbf{w}) = \lambda \|\mathbf{w}\|_1 = \lambda \sum_i |w_i|. \]
Subgradient:
\[ \frac{\partial R}{\partial w_i} = \begin{cases} \lambda & w_i > 0, \\ -\lambda & w_i < 0, \\ [-\lambda, \lambda] & w_i = 0. \end{cases} \]
Effect: drives some weights exactly to zero, promoting sparsity.
Elastic Net
Combines L1 and L2:
\[ R(\mathbf{w}) = \lambda_1 \|\mathbf{w}\|_1 + \lambda_2 \|\mathbf{w}\|_2^2. \]
Gradient (subgradient form):
\[ \nabla_{\mathbf{w}} R = \lambda_1 \,\mathrm{sign}(\mathbf{w}) + 2\lambda_2 \mathbf{w}. \]
Effect: balances sparsity and smooth shrinkage.
Matrix Regularization
For weight matrices \(W\):
Frobenius norm:
\[ R(W) = \lambda \|W\|_F^2, \quad \nabla_W R = 2\lambda W. \]
Nuclear norm (sum of singular values): encourages low-rank solutions. Gradient is subgradient of SVD-based form.
Example in ML
In linear regression with regularization:
\[ L(\mathbf{w}) = \|X\mathbf{w} - \mathbf{y}\|^2 + \lambda \|\mathbf{w}\|_2^2, \]
gradient:
\[ \nabla_{\mathbf{w}} L = 2X^\top (X\mathbf{w} - \mathbf{y}) + 2\lambda \mathbf{w}. \]
This is the ridge regression update rule.
Key Takeaways
- L2: smooth shrinkage, keeps all weights small.
- L1: sparsity, some weights driven to zero.
- Elastic Net: combines benefits of L1 and L2.
- Frobenius and nuclear norms extend regularization to matrices.
Exercises
- Compute the gradient of \(R(\mathbf{w}) = \lambda \|\mathbf{w}\|_2^2\).
- Write the subgradient of \(R(\mathbf{w}) = \lambda \|\mathbf{w}\|_1\) at \(\mathbf{w} = (1, 0, -2)\).
- Derive the gradient of ridge regression loss.
- Explain why L1 regularization induces sparsity while L2 does not.
- Show that \(\|W\|_F^2 = \mathrm{tr}(W^\top W)\) and differentiate.
Chapter 8. Logistic Regression and Softmax
8.1 Gradient of the Sigmoid Function
The sigmoid (or logistic) function is the foundation of logistic regression and appears in neural networks. Its derivative has a particularly simple and elegant form that makes it ideal for backpropagation.
Definition
\[ \sigma(z) = \frac{1}{1 + e^{-z}}. \]
- Range: \((0,1)\).
- Shape: S-curve.
- Interpretation: probability-like output.
Derivative with Respect to Input
\[ \frac{d}{dz} \sigma(z) = \sigma(z)(1 - \sigma(z)). \]
- Simple polynomial form.
- Maximum derivative = \(0.25\) at \(z=0\).
- Derivative vanishes for large \(|z|\) (saturation).
Gradient with Respect to Parameters
If \(z = \mathbf{w}^\top \mathbf{x} + b\):
\[ \nabla_{\mathbf{w}} \sigma(z) = \sigma(z)(1 - \sigma(z)) \, \mathbf{x}. \]
\[ \frac{\partial \sigma(z)}{\partial b} = \sigma(z)(1 - \sigma(z)). \]
Example: Logistic Regression
Prediction:
\[ \hat{y} = \sigma(\mathbf{w}^\top \mathbf{x}). \]
Cross-entropy loss gradient w.r.t. \(\mathbf{w}\):
\[ \nabla_{\mathbf{w}} L = (\hat{y} - y)\mathbf{x}. \]
This combines the sigmoid derivative with the loss derivative.
Example: Backpropagation
For hidden units:
\[ h = \sigma(z), \quad z = W\mathbf{x} + b. \]
Error term:
\[ \delta = \nabla_h L \cdot \sigma(z)(1 - \sigma(z)). \]
This is how gradients flow backward through sigmoid activations.
Key Takeaways
- Sigmoid derivative simplifies to \(\sigma(z)(1-\sigma(z))\).
- Efficient to compute since it reuses the forward pass output.
- Sigmoid saturates at extremes, causing vanishing gradients.
- Still widely used in probabilistic models and binary classification.
Exercises
- Derive \(\frac{d}{dz} \sigma(z)\) step by step.
- Show that the derivative is maximized at \(z=0\).
- For \(z = \mathbf{w}^\top \mathbf{x}\), compute \(\nabla_{\mathbf{w}} \sigma(z)\).
- In logistic regression, combine the sigmoid derivative with cross-entropy to derive \(\nabla_{\mathbf{w}} L = (\hat{y} - y)\mathbf{x}\).
- Explain why sigmoid activation can cause vanishing gradients in deep networks.
8.2 Gradient of the Softmax
The softmax function converts logits into probabilities over multiple classes. It is central to multi-class classification and attention mechanisms. Its derivatives form the basis of backpropagation for categorical outputs.
Definition
For logits \(\mathbf{z} \in \mathbb{R}^K\),
\[ \hat{y}_i = \text{softmax}(\mathbf{z})_i = \frac{e^{z_i}}{\sum_{j=1}^K e^{z_j}}, \quad i=1,\dots,K. \]
- Output: probability distribution over \(K\) classes.
- Sum-to-one property: \(\sum_i \hat{y}_i = 1\).
Derivative with Respect to Logits
For \(i, k \in \{1,\dots,K\}\):
\[ \frac{\partial \hat{y}_i}{\partial z_k} = \hat{y}_i (\delta_{ik} - \hat{y}_k), \]
where \(\delta_{ik}\) is the Kronecker delta.
This shows that the Jacobian of softmax is:
\[ J = \text{diag}(\hat{\mathbf{y}}) - \hat{\mathbf{y}}\hat{\mathbf{y}}^\top. \]
Gradient with Respect to Weights
If \(\mathbf{z} = W\mathbf{x}\), with \(W \in \mathbb{R}^{K \times d}\),
\[ \nabla_W \hat{\mathbf{y}} = \left( \text{diag}(\hat{\mathbf{y}}) - \hat{\mathbf{y}}\hat{\mathbf{y}}^\top \right) \mathbf{x}^\top. \]
This Jacobian–vector product form is what’s used in practice during backpropagation.
Example: Cross-Entropy with Softmax
For one-hot label \(\mathbf{y}\):
\[ L = -\sum_{i=1}^K y_i \log \hat{y}_i. \]
Gradient with respect to logits:
\[ \nabla_{\mathbf{z}} L = \hat{\mathbf{y}} - \mathbf{y}. \]
This elegant result arises from the softmax derivative structure.
Example in ML
In a classifier:
Forward: logits → softmax → probabilities.
Loss: cross-entropy.
Backward:
\[ \delta = \hat{\mathbf{y}} - \mathbf{y}, \]
passed to previous layers.
This is the standard recipe for training multi-class models.
Key Takeaways
- Softmax Jacobian: \(J = \text{diag}(\hat{\mathbf{y}}) - \hat{\mathbf{y}}\hat{\mathbf{y}}^\top\).
- Combined with cross-entropy, gradient simplifies to \(\hat{\mathbf{y}} - \mathbf{y}\).
- This efficiency makes softmax + cross-entropy the standard in classification.
Exercises
- Derive \(\frac{\partial \hat{y}_i}{\partial z_k} = \hat{y}_i(\delta_{ik} - \hat{y}_k)\).
- Write the Jacobian matrix of softmax explicitly for \(K=3\).
- Show that rows of the Jacobian sum to zero.
- Derive \(\nabla_{\mathbf{z}} L = \hat{\mathbf{y}} - \mathbf{y}\) for cross-entropy loss.
- Explain why combining softmax with cross-entropy simplifies gradients in backpropagation.
8.2 Gradient of the Softmax
The softmax function converts logits into probabilities over multiple classes. It is central to multi-class classification and attention mechanisms. Its derivatives form the basis of backpropagation for categorical outputs.
Definition
For logits \(\mathbf{z} \in \mathbb{R}^K\),
\[ \hat{y}_i = \text{softmax}(\mathbf{z})_i = \frac{e^{z_i}}{\sum_{j=1}^K e^{z_j}}, \quad i=1,\dots,K. \]
- Output: probability distribution over \(K\) classes.
- Sum-to-one property: \(\sum_i \hat{y}_i = 1\).
Derivative with Respect to Logits
For \(i, k \in \{1,\dots,K\}\):
\[ \frac{\partial \hat{y}_i}{\partial z_k} = \hat{y}_i (\delta_{ik} - \hat{y}_k), \]
where \(\delta_{ik}\) is the Kronecker delta.
This shows that the Jacobian of softmax is:
\[ J = \text{diag}(\hat{\mathbf{y}}) - \hat{\mathbf{y}}\hat{\mathbf{y}}^\top. \]
Gradient with Respect to Weights
If \(\mathbf{z} = W\mathbf{x}\), with \(W \in \mathbb{R}^{K \times d}\),
\[ \nabla_W \hat{\mathbf{y}} = \left( \text{diag}(\hat{\mathbf{y}}) - \hat{\mathbf{y}}\hat{\mathbf{y}}^\top \right) \mathbf{x}^\top. \]
This Jacobian–vector product form is what’s used in practice during backpropagation.
Example: Cross-Entropy with Softmax
For one-hot label \(\mathbf{y}\):
\[ L = -\sum_{i=1}^K y_i \log \hat{y}_i. \]
Gradient with respect to logits:
\[ \nabla_{\mathbf{z}} L = \hat{\mathbf{y}} - \mathbf{y}. \]
This elegant result arises from the softmax derivative structure.
Example in ML
In a classifier:
Forward: logits → softmax → probabilities.
Loss: cross-entropy.
Backward:
\[ \delta = \hat{\mathbf{y}} - \mathbf{y}, \]
passed to previous layers.
This is the standard recipe for training multi-class models.
Key Takeaways
- Softmax Jacobian: \(J = \text{diag}(\hat{\mathbf{y}}) - \hat{\mathbf{y}}\hat{\mathbf{y}}^\top\).
- Combined with cross-entropy, gradient simplifies to \(\hat{\mathbf{y}} - \mathbf{y}\).
- This efficiency makes softmax + cross-entropy the standard in classification.
Exercises
- Derive \(\frac{\partial \hat{y}_i}{\partial z_k} = \hat{y}_i(\delta_{ik} - \hat{y}_k)\).
- Write the Jacobian matrix of softmax explicitly for \(K=3\).
- Show that rows of the Jacobian sum to zero.
- Derive \(\nabla_{\mathbf{z}} L = \hat{\mathbf{y}} - \mathbf{y}\) for cross-entropy loss.
- Explain why combining softmax with cross-entropy simplifies gradients in backpropagation.
8.3 Derivatives of Log-Likelihood
The log-likelihood measures how well a model explains observed data. In machine learning, maximizing log-likelihood is equivalent to minimizing cross-entropy for probabilistic models. Its gradients form the foundation of maximum likelihood estimation (MLE).
General Form
Given dataset \(\{x_i\}_{i=1}^n\) and parameters \(\theta\), the log-likelihood is
\[ \ell(\theta) = \sum_{i=1}^n \log p(x_i \mid \theta). \]
Gradient:
\[ \nabla_\theta \ell(\theta) = \sum_{i=1}^n \nabla_\theta \log p(x_i \mid \theta). \]
This is called the score function.
Logistic Regression Example
For binary classification with features \(\mathbf{x}_i\), label \(y_i \in \{0,1\}\):
\[ p(y_i \mid \mathbf{x}_i, \mathbf{w}) = \sigma(\mathbf{w}^\top \mathbf{x}_i)^{y_i} (1 - \sigma(\mathbf{w}^\top \mathbf{x}_i))^{1-y_i}. \]
Log-likelihood:
\[ \ell(\mathbf{w}) = \sum_{i=1}^n \left[ y_i \log \sigma(\mathbf{w}^\top \mathbf{x}_i) + (1-y_i)\log(1-\sigma(\mathbf{w}^\top \mathbf{x}_i)) \right]. \]
Gradient:
\[ \nabla_{\mathbf{w}} \ell(\mathbf{w}) = \sum_{i=1}^n (y_i - \sigma(\mathbf{w}^\top \mathbf{x}_i)) \mathbf{x}_i. \]
This is the logistic regression update rule.
Softmax Classifier Example
For multi-class classification with one-hot label \(\mathbf{y}_i\):
\[ p(\mathbf{y}_i \mid \mathbf{x}_i, W) = \prod_{k=1}^K \hat{y}_{ik}^{y_{ik}}, \quad \hat{\mathbf{y}}_i = \text{softmax}(W\mathbf{x}_i). \]
Log-likelihood:
\[ \ell(W) = \sum_{i=1}^n \sum_{k=1}^K y_{ik} \log \hat{y}_{ik}. \]
Gradient:
\[ \nabla_W \ell(W) = \sum_{i=1}^n (\mathbf{y}_i - \hat{\mathbf{y}}_i) \mathbf{x}_i^\top. \]
Connection to KL Divergence
Maximizing log-likelihood is equivalent to minimizing cross-entropy between empirical distribution \(p\) and model distribution \(q_\theta\):
\[ \ell(\theta) = -n \cdot H(p, q_\theta). \]
Thus, likelihood gradients underpin the training of nearly all probabilistic models.
Key Takeaways
- Gradients of log-likelihood = score function.
- Logistic regression gradient: \((y - \hat{y})\mathbf{x}\).
- Softmax log-likelihood gradient: \((\mathbf{y} - \hat{\mathbf{y}})\mathbf{x}^\top\).
- Equivalent to minimizing cross-entropy or KL divergence.
Exercises
- Derive the gradient of the binary log-likelihood step by step.
- Show that logistic regression gradient simplifies to \(\sum (y_i - \hat{y}_i)\mathbf{x}_i\).
- Compute the gradient of the multi-class log-likelihood with respect to logits.
- Explain why maximizing log-likelihood is equivalent to minimizing cross-entropy.
- Discuss how log-likelihood gradients extend to probabilistic graphical models.
Chapter 9. Neural Networks and Backpropagation
9.1 Forward and Backward Passes
Neural networks are trained by alternating between forward passes (computing predictions) and backward passes (computing gradients). Matrix calculus provides the rules that make this efficient and scalable.
Forward Pass
Given input \(\mathbf{x}\), weights \(W\), biases \(\mathbf{b}\), and activation \(\phi\):
\[ \mathbf{h} = \phi(W\mathbf{x} + \mathbf{b}). \]
For multi-layer networks:
\[ \mathbf{h}^{(l)} = \phi(W^{(l)} \mathbf{h}^{(l-1)} + \mathbf{b}^{(l)}). \]
Final prediction:
\[ \hat{\mathbf{y}} = f(\mathbf{h}^{(L)}), \]
where \(f\) is often softmax or sigmoid.
Backward Pass (Backpropagation)
Goal: compute gradients of loss \(L\) with respect to all parameters.
Step 1: Error at Output
\[ \delta^{(L)} = \nabla_{\mathbf{z}^{(L)}} L, \]
where \(\mathbf{z}^{(L)} = W^{(L)} \mathbf{h}^{(L-1)} + \mathbf{b}^{(L)}\).
Step 2: Propagate Backward
For hidden layer \(l\):
\[ \delta^{(l)} = \left((W^{(l+1)})^\top \delta^{(l+1)}\right) \odot \phi'(\mathbf{z}^{(l)}), \]
where \(\odot\) is elementwise multiplication.
Step 3: Compute Gradients
With respect to weights:
\[ \nabla_{W^{(l)}} L = \delta^{(l)} (\mathbf{h}^{(l-1)})^\top. \]
With respect to biases:
\[ \nabla_{\mathbf{b}^{(l)}} L = \delta^{(l)}. \]
Example: Two-Layer Network
Input \(\mathbf{x}\), hidden layer \(h = \sigma(W^{(1)}\mathbf{x})\), output \(\hat{y} = \text{softmax}(W^{(2)}h)\).
Forward: compute logits and softmax.
Backward:
\[ \delta^{(2)} = \hat{y} - y, \]
\[ \nabla_{W^{(2)}} L = \delta^{(2)} h^\top, \]
\[ \delta^{(1)} = (W^{(2)})^\top \delta^{(2)} \odot \sigma'(W^{(1)}\mathbf{x}), \]
\[ \nabla_{W^{(1)}} L = \delta^{(1)} \mathbf{x}^\top. \]
Computational Graph Perspective
- Each operation is a node.
- Forward pass: compute values.
- Backward pass: apply chain rule in reverse.
This forms the basis of automatic differentiation in ML libraries.
Key Takeaways
- Forward pass computes predictions; backward pass computes gradients.
- Gradients flow backward using the chain rule and Jacobians.
- Weight gradients are outer products of error signals and activations.
- Backprop is just structured application of matrix calculus.
Exercises
- Derive the backward pass for a single linear layer with MSE loss.
- Show that \(\nabla_{W^{(l)}} L = \delta^{(l)} (\mathbf{h}^{(l-1)})^\top\).
- Compute gradients for a two-layer sigmoid network.
- Draw the computational graph for \(\hat{y} = \sigma(Wx)\) and label forward and backward values.
- Explain why outer products naturally appear in weight gradients.
9.2 Chain Rule in Matrix Calculus
The chain rule is the backbone of backpropagation. It explains how derivatives of composite functions are computed by combining local derivatives. Matrix calculus provides the framework to apply it systematically in neural networks.
Scalar Chain Rule
For \(f(g(x))\):
\[ \frac{df}{dx} = \frac{df}{dg} \cdot \frac{dg}{dx}. \]
Vector Chain Rule
If \(\mathbf{y} = g(\mathbf{x}) \in \mathbb{R}^m\) and \(\mathbf{z} = f(\mathbf{y}) \in \mathbb{R}^p\):
\[ \frac{\partial \mathbf{z}}{\partial \mathbf{x}^\top} = \frac{\partial \mathbf{z}}{\partial \mathbf{y}^\top} \cdot \frac{\partial \mathbf{y}}{\partial \mathbf{x}^\top}. \]
Here each term is a Jacobian matrix.
Matrix Chain Rule
For scalar functions of matrices:
\[ f(X) = g(h(X)), \]
the gradient follows:
\[ \nabla_X f = \left( \frac{\partial h}{\partial X} \right)^\top \nabla_{h} g. \]
This expresses backpropagation as Jacobian–vector products.
Example 1: Linear Layer
\[ z = W\mathbf{x}, \quad \hat{y} = \sigma(z). \]
Local derivatives:
\[ \frac{\partial z}{\partial W} = \mathbf{x}^\top, \quad \frac{\partial \hat{y}}{\partial z} = \sigma(z)(1-\sigma(z)). \]
Combined:
\[ \nabla_W \hat{y} = \sigma(z)(1-\sigma(z)) \, \mathbf{x}^\top. \]
Example 2: Softmax + Cross-Entropy
Loss:
\[ L = -\sum_{k=1}^K y_k \log \hat{y}_k, \quad \hat{\mathbf{y}} = \text{softmax}(W\mathbf{x}). \]
Gradient w.r.t. logits:
\[ \nabla_{\mathbf{z}} L = \hat{\mathbf{y}} - \mathbf{y}. \]
Gradient w.r.t. weights:
\[ \nabla_W L = (\hat{\mathbf{y}} - \mathbf{y}) \mathbf{x}^\top. \]
This is the chain rule in action.
Computational Graph View
- Each node stores a value in the forward pass.
- In the backward pass, each node receives gradient contributions from its children:
\[ \frac{\partial L}{\partial x} = \sum_j \frac{\partial L}{\partial y_j} \frac{\partial y_j}{\partial x}. \]
This is reverse-mode automatic differentiation.
Key Takeaways
- Chain rule generalizes naturally from scalars to matrices.
- Backprop = repeated application of chain rule in reverse.
- Jacobian–vector products make chain rule efficient in high dimensions.
- Softmax + cross-entropy is a canonical example of matrix chain rule.
Exercises
- Derive the gradient of \(\hat{y} = \sigma(Wx)\) with respect to \(W\).
- Show how \(\nabla_W L = (\hat{\mathbf{y}} - \mathbf{y})x^\top\) follows from chain rule.
- Write out the computational graph for a two-layer network and apply chain rule.
- Prove that reverse-mode differentiation is efficient when outputs are scalars.
- Explain why Jacobian–vector products are central to deep learning frameworks.
9.3 Gradients for Fully Connected Layers
Fully connected (dense) layers are the fundamental building blocks of neural networks. Their gradients can be derived neatly using matrix calculus, and these formulas are the workhorses of backpropagation.
Forward Pass
For input \(\mathbf{x} \in \mathbb{R}^d\):
\[ \mathbf{h} = W\mathbf{x} + \mathbf{b}, \]
where
- \(W \in \mathbb{R}^{m \times d}\): weight matrix,
- \(\mathbf{b} \in \mathbb{R}^m\): bias vector,
- \(\mathbf{h} \in \mathbb{R}^m\): pre-activation output.
If followed by activation \(\phi\):
\[ \mathbf{z} = \phi(\mathbf{h}). \]
Backward Pass
Suppose we have the gradient of loss \(L\) with respect to output \(\mathbf{h}\):
\[ \delta = \nabla_{\mathbf{h}} L. \]
Gradient w.r.t. Weights
\[ \nabla_W L = \delta \mathbf{x}^\top. \]
- Shape: same as \(W\) (\(m \times d\)).
- Outer product of error vector \(\delta\) and input \(\mathbf{x}\).
Gradient w.r.t. Bias
\[ \nabla_{\mathbf{b}} L = \delta. \]
- Shape: \(m \times 1\).
- Error signal accumulates directly into bias updates.
Gradient w.r.t. Input
\[ \nabla_{\mathbf{x}} L = W^\top \delta. \]
- Used to propagate gradients backward to earlier layers.
Batch Form
For minibatch \(X \in \mathbb{R}^{d \times n}\) with outputs \(H = WX + \mathbf{b}\mathbf{1}^\top\):
Gradients:
\[ \nabla_W L = \delta X^\top, \quad \nabla_{\mathbf{b}} L = \delta \mathbf{1}, \]
where \(\delta \in \mathbb{R}^{m \times n}\) contains error signals for all samples.
Example in ML
In a two-layer network:
\[ \hat{y} = W^{(2)} \phi(W^{(1)}x + b^{(1)}) + b^{(2)}, \]
the fully connected layer gradients are:
\[ \nabla_{W^{(2)}} L = \delta^{(2)} (h^{(1)})^\top, \]
\[ \nabla_{W^{(1)}} L = \delta^{(1)} x^\top, \]
with error signals computed recursively by chain rule.
Key Takeaways
- Fully connected gradients are outer products of error and input.
- Bias gradients are just the error terms.
- Input gradients propagate errors backward through the network.
- Batch formulas enable efficient GPU implementations.
Exercises
- Derive \(\nabla_W L = \delta x^\top\) starting from \(h = Wx + b\).
- Show that \(\nabla_x L = W^\top \delta\).
- Extend the derivation to minibatch form with \(X \in \mathbb{R}^{d \times n}\).
- Compute gradients for a two-layer network with ReLU activation.
- Explain why the outer product structure is efficient for implementation.
9.4 Gradients for Activation Functions
Activation functions introduce nonlinearity into neural networks. Their gradients determine how signals flow backward during training. Each activation has unique derivative properties that affect optimization.
General Rule
If \(\mathbf{z} = \phi(\mathbf{h})\) elementwise, and \(\delta = \nabla_{\mathbf{z}} L\), then
\[ \nabla_{\mathbf{h}} L = \delta \odot \phi'(\mathbf{h}), \]
where \(\odot\) denotes elementwise multiplication.
Thus, activations act as gates that scale gradient flow.
Sigmoid
\[ \phi(h) = \sigma(h) = \frac{1}{1+e^{-h}}, \quad \phi'(h) = \sigma(h)(1-\sigma(h)). \]
Gradient backprop:
\[ \nabla_{\mathbf{h}} L = \delta \odot \sigma(h)(1-\sigma(h)). \]
- Saturates at large \(|h|\), causing vanishing gradients.
Hyperbolic Tangent (tanh)
\[ \phi(h) = \tanh(h), \quad \phi'(h) = 1 - \tanh^2(h). \]
Gradient:
\[ \nabla_{\mathbf{h}} L = \delta \odot (1-\tanh^2(h)). \]
- Zero-centered, but still suffers from vanishing gradients at extremes.
ReLU (Rectified Linear Unit)
\[ \phi(h) = \max(0, h), \quad \phi'(h) = \begin{cases} 1 & h > 0, \\ 0 & h \leq 0. \end{cases} \]
Gradient:
\[ \nabla_{\mathbf{h}} L = \delta \odot \mathbf{1}_{h > 0}. \]
- Efficient, avoids vanishing gradient for positive region.
- Can cause “dying ReLU” if many activations are zero.
Leaky ReLU
\[ \phi(h) = \begin{cases} h & h > 0, \\ \alpha h & h \leq 0, \end{cases} \quad \phi'(h) = \begin{cases} 1 & h > 0, \\ \alpha & h \leq 0. \end{cases} \]
Prevents units from dying by keeping small gradient in negative region.
Softmax (with Cross-Entropy)
Already simplified:
\[ \nabla_{\mathbf{z}} L = \hat{\mathbf{y}} - \mathbf{y}. \]
Here, the derivative of softmax is absorbed neatly by cross-entropy.
Example in ML
In a hidden layer:
\[ h = W x + b, \quad z = \phi(h). \]
Backward step:
\[ \delta_h = \delta_z \odot \phi'(h). \]
This rule applies universally, regardless of which activation is chosen.
Key Takeaways
- Activation gradients are simple elementwise multiplications.
- Sigmoid/tanh saturate → vanishing gradients.
- ReLU is efficient but may kill neurons.
- Leaky ReLU and variants (ELU, GELU) mitigate gradient issues.
Exercises
- Derive \(\phi'(h)\) for sigmoid, tanh, and ReLU.
- Show why sigmoid derivative is maximized at \(h=0\).
- Implement ReLU backprop step using indicator function.
- Compare gradient flow through sigmoid vs ReLU for large \(|h|\).
- Explain why softmax + cross-entropy simplifies gradient computation.
Chapter 10. Advanced Models
10.1 Gradients in Convolutional Layers
Convolutional layers are the backbone of modern deep learning models for images, speech, and signals. Their forward and backward passes extend the principles of fully connected layers, but with structured weight sharing.
Forward Pass
Given input feature map \(X \in \mathbb{R}^{H \times W \times C_{\text{in}}}\) and filters \(K \in \mathbb{R}^{k_h \times k_w \times C_{\text{in}} \times C_{\text{out}}}\):
\[ Y_{i,j,c} = \sum_{u=1}^{k_h} \sum_{v=1}^{k_w} \sum_{d=1}^{C_{\text{in}}} K_{u,v,d,c} \cdot X_{i+u-1, j+v-1, d}. \]
- \(Y\): output feature map (\(H' \times W' \times C_{\text{out}}\)).
- Convolution = local weighted sum with shared parameters.
Backward Pass
Suppose \(\delta_Y = \nabla_Y L\) is the gradient of the loss with respect to the output feature map.
Gradient w.r.t. Filters
\[ \nabla_K L = X * \delta_Y, \]
where \(*\) denotes correlation between input and output gradients. Each filter update is the weighted sum of patches of \(X\) with corresponding \(\delta_Y\).
Gradient w.r.t. Input
\[ \nabla_X L = \delta_Y * K^\text{rot}, \]
where \(K^\text{rot}\) is the 180° rotated kernel. This propagates error back to the input.
Intuition
- Gradient w.r.t. filters: “How much did each filter contribute to the output error?”
- Gradient w.r.t. input: “How much should the input pixels adjust to reduce error?”
- Weight sharing makes convolutional gradients structured but efficient.
Example in ML
For image classification with CNN:
- Forward: input image → conv filters → activations → pooling → dense layers → prediction.
- Backward: error at output layer flows through dense layers, then through convolutional layers via the formulas above.
Frameworks like PyTorch and TensorFlow implement these rules using optimized GPU kernels.
Key Takeaways
- Convolution = structured linear transformation with weight sharing.
- Gradients with respect to filters = input convolved with output error.
- Gradients with respect to inputs = output error convolved with rotated filters.
- These identities power CNN training in practice.
Exercises
- Derive the gradient w.r.t. filters for a 1D convolution with stride 1.
- Show that gradient w.r.t. input involves flipping the kernel.
- For a \(3 \times 3\) kernel on grayscale input, write explicit formulas for filter updates.
- Verify convolution gradient formulas using a simple 1D example.
- Explain how weight sharing affects gradient computation compared to fully connected layers.
10.2 Matrix Calculus in Recurrent Networks
Recurrent Neural Networks (RNNs) process sequential data by maintaining hidden states that evolve over time. Gradients in RNNs are computed through backpropagation through time (BPTT), which repeatedly applies matrix calculus identities across timesteps.
Forward Pass
For sequence \((\mathbf{x}_1, \dots, \mathbf{x}_T)\):
\[ \mathbf{h}_t = \phi(W_h \mathbf{h}_{t-1} + W_x \mathbf{x}_t + \mathbf{b}), \quad t=1,\dots,T, \]
\[ \hat{\mathbf{y}}_t = f(W_y \mathbf{h}_t). \]
- \(W_h \in \mathbb{R}^{m \times m}\): recurrent weights,
- \(W_x \in \mathbb{R}^{m \times d}\): input-to-hidden weights,
- \(W_y \in \mathbb{R}^{p \times m}\): hidden-to-output weights.
Backward Pass (BPTT)
The loss \(L = \sum_{t=1}^T L_t(\hat{\mathbf{y}}_t, \mathbf{y}_t)\). We propagate errors backward through time using the chain rule.
Output Layer
\[ \nabla_{W_y} L = \sum_{t=1}^T \delta_t^{(y)} \mathbf{h}_t^\top, \]
\[ \delta_t^{(h)} = W_y^\top \delta_t^{(y)} + W_h^\top \delta_{t+1}^{(h)} \odot \phi'(\mathbf{z}_t). \]
Recurrent Weights
\[ \nabla_{W_h} L = \sum_{t=1}^T \delta_t^{(h)} \mathbf{h}_{t-1}^\top. \]
Input Weights
\[ \nabla_{W_x} L = \sum_{t=1}^T \delta_t^{(h)} \mathbf{x}_t^\top. \]
Bias
\[ \nabla_{\mathbf{b}} L = \sum_{t=1}^T \delta_t^{(h)}. \]
Intuition
- Each timestep contributes gradients for \(W_h, W_x, W_y\).
- Error signals accumulate backward across timesteps via recursion.
- This leads to the vanishing/exploding gradient problem: products of Jacobians across long sequences shrink or blow up.
Example: RNN for Sequence Classification
- Forward: process tokens sequentially, final hidden state predicts class.
- Backward: errors propagate backward through hidden states, distributing gradient information across the sequence.
- Gradient vanishing motivates architectures like LSTMs and GRUs, which add gating mechanisms.
Key Takeaways
- RNN gradients involve recursive backpropagation through time.
- Gradients for \(W_h\) depend on products of many Jacobians.
- Vanishing/exploding gradients limit RNNs on long sequences.
- LSTM/GRU mitigate these issues with memory cells and gates.
Exercises
- Derive \(\nabla_{W_h} L\) explicitly for a two-timestep RNN.
- Show how \(\delta_t^{(h)}\) depends on future timesteps.
- Compute \(\nabla_{W_x} L\) for sequence length \(T=3\).
- Explain why products of Jacobians cause vanishing gradients.
- Compare BPTT with standard backpropagation in feedforward networks.
10.3 Attention Mechanisms and Derivatives
Attention is a key component of modern deep learning models, especially transformers. Its gradients involve structured matrix operations — dot products, softmax, and weighted sums — all of which can be handled with matrix calculus.
Scaled Dot-Product Attention
Given queries \(Q \in \mathbb{R}^{n \times d_k}\), keys \(K \in \mathbb{R}^{m \times d_k}\), and values \(V \in \mathbb{R}^{m \times d_v}\):
\[ \text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V. \]
- \(Q\): representations of queries,
- \(K\): representations of keys,
- \(V\): representations of values.
Forward Pass Steps
Score matrix:
\[ S = \frac{QK^\top}{\sqrt{d_k}} \quad (n \times m). \]
Attention weights:
\[ A = \text{softmax}(S) \quad (n \times m). \]
Weighted sum:
\[ O = AV \quad (n \times d_v). \]
Backward Pass
Suppose we have \(\nabla_O L\), the gradient of the loss w.r.t. outputs.
Gradient w.r.t. Values
\[ \nabla_V L = A^\top \nabla_O L. \]
Gradient w.r.t. Attention Weights
\[ \nabla_A L = \nabla_O L \, V^\top. \]
Gradient w.r.t. Scores
Using the Jacobian of softmax:
\[ \nabla_S L = ( \nabla_A L \odot A ) - A \odot \big((\nabla_A L) \mathbf{1}_m\big), \]
which compactly encodes the softmax derivative: \(\frac{\partial A_{ij}}{\partial S_{ik}} = A_{ij}(\delta_{jk} - A_{ik})\).
Gradient w.r.t. Queries and Keys
\[ \nabla_Q L = \frac{1}{\sqrt{d_k}} \, \nabla_S L \, K, \]
\[ \nabla_K L = \frac{1}{\sqrt{d_k}} \, \nabla_S^\top Q. \]
Intuition
- Gradients flow backward from outputs \(O\) through value mixing (\(V\)), then through attention weights (\(A\)), and finally back into queries and keys (\(Q, K\)).
- The softmax derivative ensures attention weights remain normalized during learning.
Example in Transformers
- Forward: compute self-attention with \(Q=K=V=XW\).
- Backward: gradients update projection matrices \(W_Q, W_K, W_V\).
- Efficient GPU implementations rely on matrix calculus identities for speed.
Key Takeaways
- Attention = softmax-normalized dot products followed by weighted sums.
- Gradients flow backward through \(V\), \(A\), then into \(Q, K\).
- Softmax Jacobian ensures normalization constraints.
- Matrix calculus makes these derivatives tractable at scale.
Exercises
- Derive \(\nabla_V L = A^\top \nabla_O L\).
- Show how the softmax Jacobian leads to the formula for \(\nabla_S L\).
- For single-query attention (\(n=1\)), compute gradients explicitly.
- Derive \(\nabla_Q L\) and \(\nabla_K L\) step by step.
- Explain how these gradients enable end-to-end training of transformers.
Part IV. Beyond the Basics
Chapter 11. Automatic Differentiation and Matrix Calculus
11.1 Symbolic vs. Automatic Differentiation
Differentiation in machine learning can be carried out in different ways: symbolic differentiation, numerical differentiation, and automatic differentiation (autodiff). Matrix calculus underlies all of them, but their practicality differs in large-scale models.
Symbolic Differentiation
- Computes derivatives by algebraic manipulation of expressions.
- Example:
\[ f(x) = x^2 + 3x \quad \Rightarrow \quad f'(x) = 2x + 3. \]
- Tools: computer algebra systems (e.g., Mathematica, SymPy).
Pros: exact, interpretable. Cons: expression swell (formulas grow exponentially), impractical for deep networks.
Numerical Differentiation
- Approximates derivatives using finite differences:
\[ f'(x) \approx \frac{f(x+h) - f(x)}{h}, \quad h \ll 1. \]
- Simple to implement but suffers from rounding errors and high computational cost.
- Used mainly for debugging (gradient checking).
Automatic Differentiation (Autodiff)
Breaks computations into primitive operations, applies chain rule systematically.
Two modes:
- Forward mode: propagates derivatives along with values.
- Reverse mode: propagates derivatives backward (basis of backpropagation).
Example:
\[ f(x,y) = x y + \sin(x). \]
Autodiff builds a computational graph:
- Forward: compute values.
- Backward: apply chain rule in reverse to compute gradients.
Why Autodiff Matters
- Symbolic differentiation is exact but unwieldy.
- Numerical differentiation is approximate but slow.
- Autodiff combines exactness and efficiency.
- Essential for training neural networks with millions of parameters.
Example in ML Frameworks
- TensorFlow, PyTorch, and JAX all implement autodiff.
- User writes forward code; gradients are obtained automatically via reverse-mode differentiation.
Key Takeaways
- Symbolic differentiation = exact but impractical for large systems.
- Numerical differentiation = approximate, good for debugging.
- Autodiff = efficient, exact (up to floating-point error), and scalable.
- Reverse-mode autodiff is equivalent to backpropagation.
Exercises
- Differentiate \(f(x) = x^3 + \sin(x)\) symbolically.
- Approximate \(f'(2)\) numerically with finite differences for \(f(x) = e^x\).
- Build a computational graph for \(f(x,y) = x^2 y + \cos(y)\).
- Explain why reverse-mode autodiff is efficient when outputs are scalars but inputs are high-dimensional.
- Compare symbolic vs. automatic differentiation for computing gradients in a deep network.
11.2 Reverse-Mode Differentiation (Backprop)
Reverse-mode differentiation is the workhorse of deep learning. It efficiently computes gradients of scalar-valued functions with respect to high-dimensional inputs — exactly the case in training neural networks.
Forward vs. Reverse Mode
Forward mode: propagates derivatives from inputs to outputs.
- Efficient when input dimension \(d\) is small and output dimension \(m\) is large.
Reverse mode: propagates derivatives from outputs to inputs.
- Efficient when \(m=1\) (scalar loss) and \(d\) is large — the deep learning case.
Computational Graph
Every computation is broken into primitive operations:
- Forward pass: compute all intermediate values.
- Backward pass: compute derivatives of loss w.r.t. each intermediate using chain rule in reverse.
Example
Let
\[ f(x_1, x_2) = x_1 x_2 + \sin(x_1). \]
Forward pass:
- \(z_1 = x_1 x_2\)
- \(z_2 = \sin(x_1)\)
- \(f = z_1 + z_2\)
Backward pass:
- \(\frac{\partial f}{\partial z_1} = 1\), \(\frac{\partial f}{\partial z_2} = 1\)
- \(\frac{\partial f}{\partial x_1} = \frac{\partial f}{\partial z_1}\frac{\partial z_1}{\partial x_1} + \frac{\partial f}{\partial z_2}\frac{\partial z_2}{\partial x_1} = x_2 + \cos(x_1)\)
- \(\frac{\partial f}{\partial x_2} = \frac{\partial f}{\partial z_1}\frac{\partial z_1}{\partial x_2} = x_1\)
Efficiency
- Time complexity: proportional to evaluating the function (up to a constant factor).
- Memory requirement: store all intermediate values for backward pass.
- This explains why deep learning requires checkpointing and memory-efficient backprop.
Connection to Backpropagation
Reverse-mode autodiff is backpropagation:
- Gradients flow backward from loss to inputs.
- Each layer receives a gradient signal from the next layer and multiplies it by its local derivative.
Key Takeaways
- Reverse mode is optimal for scalar-output, high-dimensional-input functions.
- Computational graph enables systematic application of chain rule.
- Backpropagation in neural networks is reverse-mode autodiff.
- Tradeoff: efficiency vs. memory (storing intermediates).
Exercises
- Compute reverse-mode derivatives for \(f(x,y) = e^{xy}\).
- Draw computational graph for \(f(x,y,z) = (x+y)z\) and annotate backward gradients.
- Compare number of derivative evaluations in forward vs. reverse mode for \(f:\mathbb{R}^{1000} \to \mathbb{R}\).
- Explain why reverse-mode requires storing forward-pass values.
- Show explicitly how reverse-mode reduces to backpropagation in a two-layer neural network.
11.3 Computational Graph Perspective
A computational graph is a directed acyclic graph (DAG) that represents how a function is computed. Each node is an operation, each edge carries values, and gradients are propagated through the graph using the chain rule. This perspective unifies forward and backward passes in machine learning.
Structure of a Computational Graph
- Nodes: operations (e.g., addition, multiplication, matrix multiply, activation).
- Edges: tensors flowing between nodes.
- Inputs: parameters (\(W, b\)) and data (\(x\)).
- Output: scalar loss \(L\).
Example: For \(f(x,y) = (x+y) \cdot \sin(x)\), the graph has nodes for addition, sine, and multiplication.
Forward Pass
- Compute values of nodes from inputs to output.
- Each intermediate is cached for reuse in backpropagation.
Example:
- \(z_1 = x + y\)
- \(z_2 = \sin(x)\)
- \(f = z_1 \cdot z_2\)
Backward Pass
- Start from \(\nabla_f L = 1\).
- Propagate gradients backward using local derivatives.
Example:
- \(\nabla_{z_1} f = z_2\), \(\nabla_{z_2} f = z_1\).
- \(\nabla_x f = \nabla_{z_1} f \cdot \frac{\partial z_1}{\partial x} + \nabla_{z_2} f \cdot \frac{\partial z_2}{\partial x} = z_2 \cdot 1 + z_1 \cdot \cos(x)\).
- \(\nabla_y f = z_2 \cdot 1\).
Advantages of Graph Representation
- Modularity – each node defines both forward and backward rules.
- Reusability – same graph works for different inputs.
- Efficiency – reuse cached forward values in backward pass.
- Framework Integration – deep learning libraries (TensorFlow, PyTorch, JAX) use dynamic or static computational graphs to automate differentiation.
Graph-Based Optimization
- Reverse-mode differentiation = backpropagation on the graph.
- Memory–computation tradeoff: storing all intermediates vs. recomputing (checkpointing).
- Graph analysis enables parallelism (e.g., across GPUs or TPUs).
Key Takeaways
- Computational graphs represent functions as DAGs of operations.
- Forward = compute values; backward = propagate gradients.
- Backprop is just reverse-mode differentiation on this graph.
- Graph perspective explains efficiency of modern autodiff frameworks.
Exercises
- Draw the computational graph for \(f(x,y) = (x+y)\sin(x)\).
- Perform forward and backward passes step by step for this graph.
- Explain why caching forward values reduces computation in backprop.
- Compare dynamic vs. static computational graphs (e.g., PyTorch vs. TensorFlow).
- Discuss how computational graphs enable distributed training.
Chapter 12. Matrix Calculus in Probabilistic Models
12.1 Log-Likelihood and Gradients
Log-likelihood functions are central to probabilistic modeling. They measure how well parameters explain observed data, and their gradients — often called score functions — provide the basis for maximum likelihood estimation (MLE) and many machine learning algorithms.
General Definition
For dataset \(\{x_i\}_{i=1}^n\) and parameter vector \(\theta\):
\[ \ell(\theta) = \sum_{i=1}^n \log p(x_i \mid \theta). \]
Gradient (score function):
\[ \nabla_\theta \ell(\theta) = \sum_{i=1}^n \nabla_\theta \log p(x_i \mid \theta). \]
MLE is obtained by solving \(\nabla_\theta \ell(\theta) = 0\).
Example: Gaussian Distribution
For \(x \sim \mathcal{N}(\mu, \sigma^2)\):
\[ \ell(\mu, \sigma) = -\tfrac{n}{2}\log(2\pi\sigma^2) - \tfrac{1}{2\sigma^2}\sum_{i=1}^n (x_i - \mu)^2. \]
Gradients:
\[ \nabla_\mu \ell = \frac{1}{\sigma^2} \sum_{i=1}^n (x_i - \mu), \]
\[ \nabla_\sigma \ell = -\frac{n}{\sigma} + \frac{1}{\sigma^3}\sum_{i=1}^n (x_i - \mu)^2. \]
Logistic Regression
For binary classification,
\[ p(y=1 \mid \mathbf{x}, \mathbf{w}) = \sigma(\mathbf{w}^\top \mathbf{x}). \]
Log-likelihood:
\[ \ell(\mathbf{w}) = \sum_{i=1}^n \left[y_i \log \sigma(\mathbf{w}^\top \mathbf{x}_i) + (1-y_i)\log(1-\sigma(\mathbf{w}^\top \mathbf{x}_i))\right]. \]
Gradient:
\[ \nabla_{\mathbf{w}} \ell = \sum_{i=1}^n (y_i - \hat{y}_i)\mathbf{x}_i, \]
where \(\hat{y}_i = \sigma(\mathbf{w}^\top \mathbf{x}_i)\).
Softmax Regression
For multi-class classification:
\[ \ell(W) = \sum_{i=1}^n \sum_{k=1}^K y_{ik} \log \hat{y}_{ik}, \quad \hat{\mathbf{y}}_i = \text{softmax}(W\mathbf{x}_i). \]
Gradient:
\[ \nabla_W \ell = \sum_{i=1}^n (\mathbf{y}_i - \hat{\mathbf{y}}_i)\mathbf{x}_i^\top. \]
Why Log-Likelihood?
- Turns products into sums, avoiding underflow.
- Gradients are simple, elegant (often prediction – label form).
- Forms the foundation of cross-entropy loss.
Key Takeaways
- Log-likelihood = sum of log probabilities.
- Gradients = score functions.
- Logistic and softmax regression are direct applications.
- Maximizing log-likelihood is equivalent to minimizing cross-entropy.
Exercises
- Derive \(\nabla_\mu \ell\) and \(\nabla_\sigma \ell\) for the Gaussian likelihood.
- Compute the log-likelihood and gradient for a Bernoulli model.
- Show how logistic regression gradient reduces to \(\sum (y_i - \hat{y}_i)x_i\).
- Derive the gradient for softmax regression step by step.
- Explain why log-likelihood gradients are stable compared to direct probability gradients.
12.2 Variational Inference Gradients
Variational inference (VI) approximates complex probability distributions by optimizing a simpler family of distributions. Gradients of the evidence lower bound (ELBO) guide this optimization. Matrix calculus is essential for deriving and implementing these gradients.
Evidence Lower Bound (ELBO)
For observed data \(x\), latent variables \(z\), model \(p_\theta(x,z)\), and variational distribution \(q_\phi(z)\):
\[ \mathcal{L}(\theta, \phi) = \mathbb{E}_{q_\phi(z)} \left[ \log p_\theta(x,z) - \log q_\phi(z) \right]. \]
- Maximizing ELBO ≈ minimizing KL divergence between \(q_\phi(z)\) and the true posterior \(p_\theta(z \mid x)\).
- Gradients w.r.t. \(\theta, \phi\) are required for optimization.
Gradient w.r.t. Model Parameters \(\theta\)
\[ \nabla_\theta \mathcal{L} = \mathbb{E}_{q_\phi(z)} \left[ \nabla_\theta \log p_\theta(x,z) \right]. \]
- Similar to MLE gradients, but expectation under \(q_\phi(z)\).
- Can be estimated with Monte Carlo samples from \(q_\phi\).
Gradient w.r.t. Variational Parameters \(\phi\)
Two approaches are common:
1. Score Function Estimator (REINFORCE)
\[ \nabla_\phi \mathcal{L} = \mathbb{E}_{q_\phi(z)} \left[ \big(\log p_\theta(x,z) - \log q_\phi(z)\big) \nabla_\phi \log q_\phi(z) \right]. \]
- Unbiased but high variance.
- Variance reduction techniques (baselines, control variates) are used.
2. Reparameterization Trick
Express latent variable as:
\[ z = g_\phi(\epsilon), \quad \epsilon \sim p(\epsilon). \]
Then:
\[ \nabla_\phi \mathcal{L} = \mathbb{E}_{p(\epsilon)} \left[ \nabla_\phi \big(\log p_\theta(x, g_\phi(\epsilon)) - \log q_\phi(g_\phi(\epsilon))\big) \right]. \]
- Lower variance.
- Basis of variational autoencoders (VAEs).
Example: Gaussian Variational Distribution
Suppose \(q_\phi(z) = \mathcal{N}(z; \mu_\phi, \sigma_\phi^2)\). Using reparameterization:
\[ z = \mu_\phi + \sigma_\phi \epsilon, \quad \epsilon \sim \mathcal{N}(0,1). \]
Then gradients:
\[ \nabla_{\mu_\phi} \mathcal{L} = \mathbb{E}_\epsilon [\nabla_z f(z)], \quad \nabla_{\sigma_\phi} \mathcal{L} = \mathbb{E}_\epsilon [\epsilon \nabla_z f(z)], \]
where \(f(z) = \log p_\theta(x,z) - \log q_\phi(z)\).
Intuition
- Score function: move probability mass where ELBO increases.
- Reparameterization: push gradients through deterministic transformation.
- Reparameterization is preferred in deep learning due to efficiency.
Key Takeaways
- ELBO gradients enable variational inference optimization.
- \(\theta\): standard likelihood gradients under variational distribution.
- \(\phi\): use score function or reparameterization trick.
- Reparameterization trick is the foundation of VAEs.
Exercises
- Derive \(\nabla_\theta \mathcal{L}\) from the ELBO definition.
- Show how the score function estimator arises from moving the gradient inside the expectation.
- Implement reparameterization for a Gaussian variational family.
- Compare variance of score function vs. reparameterization estimators.
- Explain why the reparameterization trick requires differentiable transformations.
12.3 KL Divergence Derivatives
The Kullback–Leibler (KL) divergence measures how one probability distribution differs from another. In variational inference and many ML models, its gradients provide the optimization signal for aligning approximations with true distributions.
Definition
For distributions \(q(z)\) and \(p(z)\):
\[ D_{\text{KL}}(q \parallel p) = \mathbb{E}_{q(z)} \left[ \log \frac{q(z)}{p(z)} \right]. \]
- Always nonnegative.
- Zero iff \(q = p\).
- Asymmetric: \(D_{\text{KL}}(q \parallel p) \neq D_{\text{KL}}(p \parallel q)\).
Gradient w.r.t. Parameters of \(q\)
Suppose \(q = q_\phi(z)\) depends on parameters \(\phi\). Then:
\[ \nabla_\phi D_{\text{KL}}(q_\phi \parallel p) = \nabla_\phi \mathbb{E}_{q_\phi(z)} \left[\log q_\phi(z) - \log p(z)\right]. \]
Two main estimators:
- Score Function Estimator
\[ \nabla_\phi D_{\text{KL}} = \mathbb{E}_{q_\phi(z)} \left[(1 + \log q_\phi(z) - \log p(z)) \, \nabla_\phi \log q_\phi(z)\right]. \]
- Reparameterization Trick
If \(z = g_\phi(\epsilon)\):
\[ \nabla_\phi D_{\text{KL}} = \mathbb{E}_{p(\epsilon)} \left[ \nabla_\phi \big(\log q_\phi(g_\phi(\epsilon)) - \log p(g_\phi(\epsilon))\big) \right]. \]
Special Case: Gaussian KL
For \(q = \mathcal{N}(\mu_q, \sigma_q^2)\), \(p = \mathcal{N}(\mu_p, \sigma_p^2)\):
\[ D_{\text{KL}}(q \parallel p) = \log \frac{\sigma_p}{\sigma_q} + \frac{\sigma_q^2 + (\mu_q - \mu_p)^2}{2\sigma_p^2} - \frac{1}{2}. \]
Gradients:
\[ \nabla_{\mu_q} D_{\text{KL}} = \frac{\mu_q - \mu_p}{\sigma_p^2}, \]
\[ \nabla_{\sigma_q} D_{\text{KL}} = \frac{\sigma_q}{\sigma_p^2} - \frac{1}{\sigma_q}. \]
These closed forms are heavily used in VAEs.
Example in Variational Autoencoders (VAE)
The ELBO includes a KL divergence term:
\[ \mathcal{L}(\theta, \phi) = \mathbb{E}_{q_\phi(z)}[\log p_\theta(x \mid z)] - D_{\text{KL}}(q_\phi(z) \parallel p(z)). \]
- KL term pushes \(q_\phi(z)\) toward the prior \(p(z)\).
- Gradients ensure latent codes are structured and regularized.
Key Takeaways
- KL divergence gradients align approximate distributions with priors.
- Score function and reparameterization are two gradient estimators.
- Closed forms (Gaussian–Gaussian) are common in practice.
- KL derivatives are essential in variational inference and VAEs.
Exercises
- Derive gradients of \(D_{\text{KL}}(q \parallel p)\) for Gaussian \(q, p\).
- Show how reparameterization simplifies KL gradient estimation.
- Compute KL divergence between two Bernoulli distributions and its gradient.
- Explain why KL divergence is asymmetric and how that affects optimization.
- In VAEs, interpret the role of KL gradients in shaping latent space.
Appendices
Appendix A. Common Derivative Identities Cheat Sheet
This appendix summarizes the most frequently used matrix calculus identities in machine learning. They serve as a quick reference during derivations.
Vector Derivatives
Linear form:
\[ \nabla_{\mathbf{x}} (\mathbf{a}^\top \mathbf{x}) = \mathbf{a}. \]
Quadratic form:
\[ \nabla_{\mathbf{x}} (\mathbf{x}^\top A \mathbf{x}) = (A + A^\top)\mathbf{x}. \]
Norms:
\[ \nabla_{\mathbf{x}} \|\mathbf{x}\|_2^2 = 2\mathbf{x}, \quad \nabla_{\mathbf{x}} \|\mathbf{x}\|_2 = \frac{\mathbf{x}}{\|\mathbf{x}\|_2}. \]
Matrix Derivatives
Linear trace:
\[ \nabla_X \, \mathrm{tr}(AX) = A^\top. \]
Quadratic trace:
\[ \nabla_X \, \mathrm{tr}(X^\top AX) = (A + A^\top)X. \]
Frobenius norm:
\[ \nabla_X \|X\|_F^2 = 2X. \]
Determinant and Log-Det
Determinant:
\[ \nabla_A \det(A) = \det(A) (A^{-1})^\top. \]
Log-determinant:
\[ \nabla_A \log \det(A) = (A^{-1})^\top. \]
Softmax and Cross-Entropy
Softmax Jacobian:
\[ \frac{\partial \hat{y}_i}{\partial z_k} = \hat{y}_i (\delta_{ik} - \hat{y}_k). \]
Cross-entropy with softmax:
\[ \nabla_{\mathbf{z}} L = \hat{\mathbf{y}} - \mathbf{y}. \]
Backpropagation Identities
Linear layer:
\[ \nabla_W L = \delta \mathbf{x}^\top, \quad \nabla_{\mathbf{b}} L = \delta, \quad \nabla_{\mathbf{x}} L = W^\top \delta. \]
Activation (elementwise):
\[ \nabla_{\mathbf{h}} L = \delta \odot \phi'(\mathbf{h}). \]
Appendix B. Notation Reference
This appendix provides a compact reference for the notation used throughout the book. It distinguishes between scalars, vectors, matrices, and higher-order tensors, and clarifies common symbols.
Scalars
- Lowercase letters: \(a, b, c, \alpha, \beta, \theta\).
- Represent single numerical values.
- Example: learning rate \(\eta \in \mathbb{R}\).
Vectors
- Bold lowercase letters: \(\mathbf{x}, \mathbf{y}, \mathbf{w}\).
- Column vectors in \(\mathbb{R}^d\).
- Transpose: \(\mathbf{x}^\top\) is a row vector.
- Example: feature vector \(\mathbf{x} \in \mathbb{R}^d\).
Matrices
- Bold uppercase letters: \(A, B, X, W\).
- Shape indicated when needed: \(A \in \mathbb{R}^{m \times n}\).
- Identity matrix: \(I\).
- Trace: \(\mathrm{tr}(A) = \sum_i A_{ii}\).
- Determinant: \(\det(A)\).
Tensors
- Calligraphic or bold script: \(\mathcal{T}, \mathcal{X}\).
- Higher-order generalizations of matrices.
- Example: convolution kernels \(\mathcal{K} \in \mathbb{R}^{k_h \times k_w \times C_\text{in} \times C_\text{out}}\).
Functions and Operators
- Gradient: \(\nabla_x f\) = vector of partial derivatives w.r.t. \(x\).
- Jacobian: \(J_{ij} = \tfrac{\partial f_i}{\partial x_j}\).
- Hessian: \(H_{ij} = \tfrac{\partial^2 f}{\partial x_i \partial x_j}\).
- Frobenius norm: \(\|X\|_F^2 = \mathrm{tr}(X^\top X)\).
- Kronecker product: \(A \otimes B\).
Probability Notation
- Random variables: capital letters, \(X, Y, Z\).
- Observed values: lowercase, \(x, y, z\).
- Distribution: \(X \sim p(x)\).
- Expectation: \(\mathbb{E}_{p(x)}[f(x)]\).
- KL divergence: \(D_{\text{KL}}(q \parallel p)\).
Machine Learning Conventions
- Inputs: \(\mathbf{x}\).
- Parameters: \(\mathbf{w}, \theta\).
- Predictions: \(\hat{y}, \hat{\mathbf{y}}\).
- Loss: \(L(\theta)\).
- Layers: indexed as \(W^{(l)}, \mathbf{h}^{(l)}\).