Hello! Welcome to the next module of our course. We've just finished our exploration of tensor products, a key concept for understanding multi-particle systems in quantum mechanics. Now, we're making a significant shift in focus towards the other pillar of your goal: deep learning. This module, "Matrix Calculus and Optimization," will equip you with the mathematical tools needed to understand how machine learning models are trained.
In this first lesson, we'll start with a fundamental building block: the gradient. You're familiar with derivatives from single-variable calculus and partial derivatives from multivariable calculus. We are now going to generalize these ideas to functions that take entire vectors or matrices as input. This is the engine that powers optimization algorithms like gradient descent, which are at the very heart of deep learning.
Learning Outcome: Compute the gradient of a scalar-valued function with respect to a vector or matrix.
1. From Scalar Derivatives to Gradients
Before we jump into vectors and matrices, let's briefly revisit the core idea of a derivative in single-variable calculus. The derivative gives us the best linear approximation of a function near a point . This idea of linearization is the foundation we will build upon.
To see a great review of this concept and how it sets the stage for everything that follows, please watch the beginning of the following lecture by MIT's Alan Edelman.
Matrix Calculus 2020 04 16 for MIT Linear Algebra 18.06 Spring 2020 (Alan Edelman)
This video, 'Matrix Calculus' from MIT's Linear Algebra course, provides an excellent intuitive path from scalar calculus to matrix calculus. We'll start with the first part to solidify our foundation.
Watch the video from the beginning until 14:34. Pay close attention to the concept of the differential, dy = f'(x)dx, and how it represents the first-order change in the function's output for a small change in its input. This is the key idea we will generalize.
As the video explains, the relationship is central. It tells us how a small perturbation in the input is linearly transformed into a perturbation in the output. We are now going to extend this to functions whose inputs are not single numbers, but vectors.
2. The Gradient: Differentiating with Respect to a Vector
Let's consider a function that maps a vector to a single scalar, written . A common example in machine learning is a "cost" or "loss" function, which measures how poorly a model is performing. The input vector could represent all the tunable weights in the model.
The gradient of with respect to is the vector containing all the partial derivatives of . We denote it as .
Notice that the gradient is a column vector with the same dimension as the input vector . This is a common convention in machine learning known as denominator layout.
Geometric Intuition
What does this vector represent? The gradient evaluated at a point points in the direction of the steepest ascent of the function at that point. Conversely, the negative gradient, , points in the direction of steepest descent. This is precisely why gradients are crucial for optimization: to minimize a function, we just need to follow the direction of its negative gradient.
.webp)
Computation Method 1: Element-wise Derivation
The most direct way to compute a gradient is to calculate each partial derivative one by one, treating all other components of as constants.
Example: The Squared L2 Norm
Let .
To find the gradient, we compute the partial derivative with respect to an arbitrary component :
The derivative is zero for all terms where . The only non-zero term is when , which gives .
Assembling these into a vector, we get:
This element-wise approach is straightforward, but it can become very tedious.
Computation Method 2: The Differential Approach
A more powerful and elegant method, especially for complex functions, is to use differentials, just as Alan Edelman did in the video. We generalize the scalar linearization to vectors. The total differential of is the dot product of the gradient with the differential vector :
Our strategy will be to compute using calculus rules for vectors and matrices, and then manipulate the expression into the form (something)^T d**x**. That "something" will be our gradient.
Let's re-do our example using this approach. We'll use the product rule, which for vectors states .
- Find the differential:
- Simplify: Note that is a scalar (a matrix). The transpose of a scalar is itself. So, . The two terms are identical.
- Identify the gradient: We have our expression in the form . By comparing the forms, we can directly identify the gradient: .
This method avoids breaking the vector down into its components. The next segment of the Edelman video masterfully demonstrates this technique.
Matrix Calculus 2020 04 16 for MIT Linear Algebra 18.06 Spring 2020 (Alan Edelman)
Let's continue with the video, where Prof. Edelman computes gradients for vector functions using this powerful differential method.
Watch from 14:34 to 38:22. First, he formalizes the gradient concept. Then, he derives the gradient for the squared norm, just as we did. Finally, he tackles a more complex and highly relevant example: the squared norm of Ax - b, which is the cost function for the linear least squares problem. Follow his derivation closely.
Test your understanding!
Let for a constant vector . Find the gradient using the differential approach.
Show answer
- Find the differential: Since is a constant vector, .
- Identify the gradient: The expression is already in the form . Therefore, .
3. Differentiating with Respect to a Matrix
Now we extend the concept to functions that take a matrix and return a scalar, . The gradient is now a matrix of the same size as , where each element is a partial derivative.
To use our differential method, we need a way to turn a matrix expression back into a scalar. The dot product worked for vectors. For matrices, the analogous operation is the trace.
The Trace Operator
The trace of a square matrix, denoted , is the sum of its diagonal elements. For our purposes, it has two crucial properties:
- Linearity: and .
- Cyclic Property: . You can cycle the matrices in a product without changing the trace, as long as the dimensions remain compatible.
The identity that connects the differential to the gradient is:
Our strategy remains the same: calculate using calculus rules, then massage the expression into the form . That "something" will be the gradient.
Let's see this in action with the help of the final part of the video.
Matrix Calculus 2020 04 16 for MIT Linear Algebra 18.06 Spring 2020 (Alan Edelman)
The final part of the video introduces the trace and uses it to compute a matrix gradient.
Watch from 38:22 to 51:15. The video first introduces the trace and its properties. Then, it uses this to derive the gradient of f(A) = tr(A^2). Follow the steps carefully to see how the product rule and the cyclic property of the trace work together.
As shown in the video, for , we found that . By matching this to the identity , we can conclude that . Correction: The video shows , let's re-verify the derivation.
Let's retrace the steps from the video for :
- Using the cyclic property on the first term: .
- So, .
- To match the form , we identify with .
- Therefore, .
The video's result is correct. This elegant, element-free approach is extremely useful. For a more direct, text-based explanation of these definitions, you can refer to the following resources.
The Matrix Calculus You Need For Deep Learning
These two resources provide concise, formal definitions of the gradient for both vector and matrix inputs.
Skim the 'Introduction to vector calculus and partial derivatives' section for the definition of the gradient of a vector. Then, look at the 'Matrix Calculus Reference' at the end for a quick summary.
Matrix Calculus for 10-301/601
This document from CMU provides a clear definition of the derivative of a scalar with respect to a vector and a matrix, explicitly mentioning the layout notation.
Read section 2.1.1, 'Derivatives of Scalar'. It provides clear definitions for dy/dx (scalar), dy/dx (vector), and dy/dX (matrix), and highlights the useful property that the shape of the derivative matches the shape of the variable.
Conclusion
In this lesson, we have taken our first and most important step into matrix calculus. We have defined the gradient for functions of vectors and matrices, which is the cornerstone of optimization in machine learning.
Key Takeaways:
- The gradient () of a scalar-valued function is the vector or matrix of its partial derivatives.
- The gradient has the same shape as the input variable (using denominator layout convention).
- Geometrically, the gradient points in the direction of the function's steepest ascent.
- Gradients can be computed element-by-element, but a more powerful differential method treats vectors and matrices as whole objects.
- The key relations for the differential method are:
- For vectors:
- For matrices:
- The product rule and the cyclic property of the trace are essential tools for this approach.
Preview of the Next Lesson:
We've dealt with functions that output a single scalar. But what if a function outputs a whole vector? For example, each layer in a neural network transforms an input vector into an output vector. To handle derivatives of such functions, we need to generalize the gradient to the Jacobian matrix. That will be our next topic.