Welcome back. In the previous lesson, we wrote a linear model for a dataset as
with rows representing observations and columns representing features. That notation now gives us a precise answer to a practical training question: if the model’s total error changes, which parameter should change, and by how much?
This lesson develops the mathematical object that answers it: the gradient of a scalar loss with respect to a vector of parameters. You will compute gradients from partial derivatives, derive the gradient for squared-error linear regression, and interpret the resulting vector in a way that makes the next lesson’s gradient-descent update rule almost inevitable.
A scalar loss, many adjustable parameters
To focus on training rather than prediction notation, write the model parameters as
The intercept may be included as , paired with a constant feature , exactly as in the prior lesson. A model fitted to data has one scalar objective value:
The loss is a single number: for example, total squared prediction error, average log loss, or that loss plus a regularization penalty. But it depends on every entry of .
For a scalar function of vector parameters, the gradient collects one partial derivative per parameter:
We will use the convention that gradients are column vectors, so the gradient has the same shape as its parameter vector. Each component says how rapidly the loss changes when only that parameter is varied and all other parameters are held fixed.
For example, consider the simple loss
Its two partial derivatives are
Therefore,
At , the gradient is
A small positive change in raises the loss much more strongly than an equally sized positive change in , locally at that point.
The gradient is not just a bundle of derivatives. For a small parameter displacement ,
This first-order approximation says that the gradient identifies the direction of greatest local increase in loss. Consequently, its negative identifies the direction of greatest local decrease for a fixed, sufficiently small displacement. We will turn that observation into gradient descent in the next lesson.
A small derivative toolkit
Most conventional ML objectives can be decomposed into a small number of patterns. When in doubt, expand an expression into components and differentiate one parameter at a time; compact matrix identities are conveniences, not substitutes for reasoning.
| Scalar function of | Gradient with respect to | Why |
|---|---|---|
| , a constant | No parameter affects a constant. | |
| Each occurs as . | ||
| This is . | ||
| A parameter can occur in both positions of the quadratic form. | ||
| , with symmetric | Symmetry makes the two contributions equal. |
The most reusable rule is the gradient of a dot product:
It is the vector version of the one-variable rule that the derivative of with respect to is .
This immediately gives a compact chain-rule pattern. If
where is any differentiable scalar function, then
The scalar factor measures the sensitivity of the outer loss; the vector distributes that sensitivity across the parameters.
[PDF] Linear Algebra - Stanford University
Read the matrix-calculus portion of Stanford’s CS229 Linear Algebra Review to reinforce the convention that a scalar loss differentiated with respect to a vector produces a vector of the same shape. It also derives the linear, quadratic, and least-squares gradients used below.
In the “Matrix Calculus” material on pp. 54–64, begin with “The Gradient” on pp. 54–56. Read the gradient definition, focusing on why its shape matches the input vector or matrix. Then read “Gradients of Linear Functions” on pp. 58–59, especially the dot-product result. Finally, in “Matrix Calculus Example: Least Squares” on p. 64, follow the least-squares expansion; the normal equations themselves are a preview, but the gradient calculation is central here.
A practical caveat: sources differ on whether they write a derivative with respect to a vector as a row or a column. This is a notation convention, sometimes called numerator versus denominator layout. Rather than memorizing formula sheets blindly, establish the convention at the start and check dimensions throughout. In this lesson,
because
Deriving the squared-error gradient for one observation
Consider one observation . The linear model score is
and, for regression, the score itself is the prediction:
Use a half-squared-error loss for this one observation:
The factor does not change which parameter values minimize the loss. It simply cancels the factor of produced when differentiating the square.
Introduce the residual
Then
To derive the gradient without relying on a remembered identity, take the partial derivative with respect to one parameter :
The outer derivative is
For the inner derivative, expand the score:
Only the term depends on , so
Combining the two pieces gives
Stacking these component derivatives produces the gradient:
This formula deserves interpretation. An observation contributes a gradient proportional to:
- Its signed residual: underprediction produces a negative residual; overprediction produces a positive residual.
- Its feature vector: parameters associated with large feature values receive a larger contribution.
If the prediction is exactly correct, , that observation contributes a zero gradient. If a feature is zero for this observation, its corresponding coefficient receives no direct gradient contribution from that observation.
From one observation to a dataset
For observations, stack feature vectors into the design matrix , and stack targets into :
The vector of predictions and residuals is
Define the average half-squared-error loss:
The norm notation is shorthand for a sum of squared residuals:
Since differentiation distributes over a sum, average the individual gradients:
The equivalent matrix expression is
The transpose is essential. The residual vector has one entry per row of , whereas the gradient must have one entry per column, or feature:
The expression is a vector of feature–residual alignments. A coefficient’s gradient is large when its feature values tend to coincide with large residuals of one sign. At a least-squares optimum, these alignments balance out:
That condition will later lead to the ordinary least-squares solution.

The data-flow diagram makes a useful modeling distinction. The data loss depends on predictions and labels. A regularization loss depends directly on the parameters and expresses a preference for simpler parameter values. The total loss is still a single scalar, so its gradient is simply the sum of the two gradient contributions.
For ridge-style regularization, the objective is
Its gradient is
The term increases with coefficient magnitude. In many libraries, the intercept is excluded from regularization; mathematically, this means applying the penalty only to the selected non-intercept entries rather than to every component of .
A complete numerical calculation
Take a model with an intercept and one feature:
The predictions are
and the residuals are
The average half-squared-error loss is
Now compute the gradient:
Both entries are negative. Locally, increasing either parameter would decrease this particular loss; the feature coefficient has the larger magnitude because the larger feature values coincide with substantial underprediction.
The calculation also demonstrates why units and scaling matter. If the feature column were recorded in individual users rather than thousands of users, its values would be times larger. The corresponding coefficient would need a different numerical scale, and its gradient would also have a dramatically different scale. The underlying predictions can be equivalent, but optimization behavior is not. We will examine that consequence directly in the next lesson.
Stanford CS229: Machine Learning - Linear Regression and Gradient Descent | Lecture 2 (Autumn 2018)
Watch the selected portion of “Stanford CS229: Machine Learning — Linear Regression and Gradient Descent,” from Stanford Online, for a board-style derivation of the same squared-error gradient. The lecturer uses \boldsymbol{\theta} where this lesson uses \mathbf{w}.
In the segment on the formal gradient-descent procedure, watch one example to see why differentiating a linear score with respect to parameter \theta_j leaves x_j. Then watch the full dataset, where the individual-example contributions are summed over the training set. Notice the use of a factor \frac{1}{2} in the loss; it removes the otherwise harmless factor of 2 in the derivative.
Checking a gradient in code
Analytical gradients are fast and exact up to floating-point arithmetic. When implementing a nontrivial custom objective, a finite-difference gradient check is a valuable debugging tool.
For coordinate , let be the vector with a at position and zeros elsewhere. The central-difference estimate is
For a small fixed dataset, compare this approximation with the -th entry of your analytical gradient:
import numpy as np
X = np.array([[1.0, 2.0],
[1.0, 4.0]])
y = np.array([5.0, 8.0])
w = np.array([1.0, 1.0])
def mse_half(w, X, y):
residuals = X @ w - y
return 0.5 * np.mean(residuals ** 2)
def grad_mse_half(w, X, y):
residuals = X @ w - y
return X.T @ residuals / len(y)
analytic = grad_mse_half(w, X, y)
epsilon = 1e-6
numeric = np.zeros_like(w)
for j in range(len(w)):
direction = np.zeros_like(w)
direction[j] = 1.0
numeric[j] = (
mse_half(w + epsilon * direction, X, y)
- mse_half(w - epsilon * direction, X, y)
) / (2 * epsilon)
print(analytic)
print(numeric)
The two vectors should be very close, though not character-for-character identical because the finite-difference expression itself is an approximation. If they disagree substantially, common causes include a missing averaging factor, an incorrect transpose, a sign error in the residual definition, or evaluating the loss and gradient on different data slices.
A gradient is the vector of partial derivatives of a scalar objective with respect to its parameter vector:
For linear regression with average half-squared error, the central result is
It aggregates each observation’s residual, weighted by its feature values. Adding regularization contributes the additional gradient term .
Next, we will use the negative gradient to perform a gradient-descent update, then examine why learning rate and feature scale determine whether optimization converges smoothly, crawls, or diverges.
Can't find a good explanation? Sign up and we'll make it for you
Sign up