CodeRigor

LESSON

Gradient descent on a classifier

Turn a gradient into a training loop: batch gradient descent on softmax regression, with the loss recorded before every step.

A gradient tells you how the loss changes when the weights change. Gradient descent turns that into learning: move the weights a small step the other way, measure again, and repeat. This lesson pairs with Lecture 4 of CMU's 11-785 (Fall 2026), linked under Watch & read. You build the training loop for softmax regression, a single linear layer followed by a softmax, and check it against PyTorch's own optimizer.

The gradient of the loss points uphill, the direction in which the loss grows fastest. So the update is w ← w - lr · ∇L(w), where the learning rate lr sets the step length. For a small enough lr the loss goes down. For a large one it may not. Try f(w) = w², whose slope at w = 3 is 6:

Python
for lr in (0.1, 1.1):
    w = 3.0
    w = w - lr * 2 * w          # the slope of w² is 2w
    print(lr, round(w, 2), round(w * w, 2))

The loss starts at 9. A step of 0.1 gives 5.76. A step of 1.1 jumps over the minimum and lands at 12.96, higher than where it began. The lesson on learning rates and momentum explains where that threshold sits.

Now the model. For a batch of N rows the logits are z = xWᵀ + b, with W stored as (classes, D) like torch.nn.Linear. The loss is the mean over the rows of -log p, where p is the softmax probability of the true class. Let P hold the probabilities for every row and Y the one-hot labels. Then

  • delta = (P - Y) / N
  • dW = deltaᵀ x, which has the shape of W
  • db = the column sums of delta

The 1/N sits in delta once, because the loss is a mean. Every row of x takes part in every step, which is why this is called batch gradient descent. Mini-batches, which use a few rows per step, come later in the course.

One step, repeated
start / 5
Each pass uses all N rows. The loss is recorded where it is computed, before the update changes the weights.
One step, repeated
Each pass uses all N rows. The loss is recorded where it is computed, before the update changes the weights.

Record the loss before the update. Then losses[0] is the loss of the starting weights, and every later entry is the loss of the weights that step's gradient was computed at. No second forward pass is needed. From zero weights every class gets probability 1/C, so losses[0] is log C, which is 1.0986 for three classes. Recording after the update shifts the whole history by one step and hides that starting point.

A short example you can check by hand. Four rows, three classes, labels 0, 0, 0, 1, all weights zero:

Python
import numpy as np

x = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [2.0, 0.0]])
y = np.array([0, 0, 0, 1])
rows = np.arange(4)

def loss_and_delta(W, b):
    z = x @ W.T + b
    p = np.exp(z) / np.exp(z).sum(axis=1, keepdims=True)
    delta = p.copy()
    delta[rows, y] -= 1.0
    return -np.log(p[rows, y]).mean(), delta / 4

W, b = np.zeros((3, 2)), np.zeros(3)
loss, delta = loss_and_delta(W, b)
dW, db = delta.T @ x, delta.sum(axis=0)
print(round(loss, 4), dW.round(4).tolist(), db.round(4).tolist())
print(round(loss_and_delta(W - 0.5 * dW, b - 0.5 * db)[0], 4))

One step with lr = 0.5 takes the loss from 1.0986 to 0.8355.

Softmax regression has a convex loss in (W, b): it has no bad local minima, so starting from zero is safe. Every step is also a fixed function of the data and the current weights, so two correct implementations follow the same path, which is why the tests can demand agreement to 1e-9. Convex does not mean a minimum exists. On data that straight lines separate perfectly, the loss keeps shrinking as the weights grow: in one run the loss was 0.00023 after 200 steps and 0.00002 after 5000, while the weight norm rose from 1.88 to 2.43. You stop after a chosen number of steps, not at the bottom.

The learning rate decides how this plays out. On a seeded dataset of 90 overlapping points in three groups, measured with the reference solution:

  • lr = 0.03: loss 0.991 after one step and 0.325 after 29. Safe and slow.
  • lr = 1: loss 0.189 after one step and 0.145 after 29. Fast.
  • lr = 15: the first step overshoots. The loss rises from 1.099 to 1.329, then recovers to 0.422 after 29 steps, far behind lr = 1.
Training loss for three learning rates
The same 90 points, 30 steps, zero start. Every point is the loss recorded before that step's update.
Training loss for three learning rates
The same 90 points, 30 steps, zero start. Every point is the loss recorded before that step's update.

These are the mistakes that pass for working code:

  • Recording the loss after the update. The history looks plausible and is wrong by one step.
  • Updating the bias in the wrong direction, or not at all. With the bias sign flipped and lr = 0.1, the loss on that dataset still fell at every one of 30 steps, ending at 0.2132 instead of 0.2062. A falling loss does not show the update is right.
  • Leaving out the 1/N, which multiplies the effective learning rate by N.

The tests compare W, b and every recorded loss with the same loop written in PyTorch: a zero-initialised torch.nn.Linear, cross_entropy and torch.optim.SGD. That separates a correct loop from one that merely descends. It does not tell you the model generalises. With 20 random points in 40 dimensions and random labels, 500 steps reached training loss 0.002 and 100% training accuracy, and 33% accuracy on 3000 fresh points, which is chance. Training loss measures the optimizer. Held-out data measures the model.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →