Module 1
Linear and logistic regression
Two models small enough to see whole: a line through points, and a curve that turns a number into a probability. Both are trained the way every later model is trained, by walking downhill on a loss.
Why it matters
The two losses in this module, squared error and cross-entropy, are the ones that train everything else in the course. The last layer of almost every classifier, including a transformer choosing its next token, is logistic regression, in its multi-class form, on features the earlier layers have learned. With only two parameters, you can also draw the whole loss surface and watch gradient descent move across it, which stops being possible as soon as models grow.
The idea
A line and squared error
Given data $(x_1, y_1), \dots, (x_n, y_n)$, the model predicts $\hat y_i = w x_i + b$. The squared loss measures how wrong the parameters $(w, b)$ are:
$$L(w, b) = \frac{1}{n} \sum_{i=1}^{n} (\hat y_i - y_i)^2 .$$Differentiating gives the gradient, the direction in which the loss rises fastest:
$$\frac{\partial L}{\partial w} = \frac{2}{n} \sum_{i} (\hat y_i - y_i)\, x_i , \qquad \frac{\partial L}{\partial b} = \frac{2}{n} \sum_{i} (\hat y_i - y_i).$$Gradient descent repeatedly steps the other way, with a step size $\eta$ called the learning rate:
$$w \leftarrow w - \eta \frac{\partial L}{\partial w}, \qquad b \leftarrow b - \eta \frac{\partial L}{\partial b}.$$This loss is a convex quadratic bowl in $(w, b)$ with a single minimum, and setting the gradient to zero even gives that minimum exactly. We use descent anyway, because it is the method that keeps working when the model stops being a line. On a quadratic bowl its behaviour is fully understood: it converges when $\eta \lt 2/\lambda_{\max}$, where $\lambda_{\max}$ is the curvature of the bowl in its steepest direction (the largest eigenvalue of the Hessian), and diverges above that.
A probability and cross-entropy
For labels $y_i \in \{0, 1\}$ a line is the wrong shape, so squash it through the logistic sigmoid:
$$p_i = \sigma(z_i), \qquad z_i = w x_i + b, \qquad \sigma(z) = \frac{1}{1 + e^{-z}} .$$Read $p_i$ as the model's probability that $y_i = 1$. The natural loss is the negative log-likelihood of the observed labels, the cross-entropy:
$$L(w, b) = -\frac{1}{n} \sum_{i=1}^{n} \Big[\, y_i \log p_i + (1 - y_i) \log (1 - p_i) \Big].$$Since $\sigma'(z) = \sigma(z)\,(1 - \sigma(z))$, the chain rule collapses to something that looks just like the linear case:
$$\frac{\partial L}{\partial w} = \frac{1}{n} \sum_{i} (p_i - y_i)\, x_i , \qquad \frac{\partial L}{\partial b} = \frac{1}{n} \sum_{i} (p_i - y_i).$$Both gradients are error times input. That is not a coincidence: up to constants, squared error is the negative log-likelihood under Gaussian noise and cross-entropy is the negative log-likelihood of a Bernoulli label, and pairing each with its matching output gives this form. The cross-entropy loss is also convex, but it has no closed-form minimum, so descent is no longer optional. One surprise is waiting in the demo: if the two classes can be separated perfectly, there is no minimum at all.
More than one feature
With $d$ features, stack the inputs as rows of $X \in \mathbb{R}^{n \times d}$ and let $w \in \mathbb{R}^d$. Then $z = Xw + b$, $p = \sigma(z)$ and
$$\nabla_w L = \frac{1}{n} X^{\top} (p - y), \qquad \frac{\partial L}{\partial b} = \frac{1}{n} \sum_i (p_i - y_i).$$You will write exactly this in the exercise.
Live demo: descent on a loss surface
Drag the data, watch the fit and the loss surface
Data and fitted line (drag the points)
Loss over (w, b): darker is higher. Click to move the start.
Try this
- Press Run gradient descent and let it settle on the cross. Then drag the right-most point to the bottom of the plot. One outlier drags the whole line: squared error punishes a miss in proportion to its square.
- Press Reset, raise η to 0.3 and run. The path now zig-zags across the valley. Reset again with η at 0.45: every step overshoots by more than the last. The steep direction of the bowl sets the speed limit.
- Switch to Logistic and run. Then drag points until every blue point is left of every orange one, and leave it running. The loss keeps falling and $w$ keeps growing, because a steeper curve always fits separable data better. Drag one point back across and a finite minimum reappears.
Exercise
Write the gradient of the logistic loss
Complete logistic_grad for $d$ features, using the vector formulas above. The hidden tests compute the same gradient with a scalar autograd engine like the one from module 0; yours must agree to within $10^{-6}$.
Compute the predictions p = sigmoid(X @ w + b) and the error vector p - y. The gradient for w is X.T @ (p - y) divided by the number of examples; the gradient for b is the mean of p - y.
Check yourself
Both gradients are “error times input”. What is the input that goes with the bias $b$?
The constant 1. The bias behaves like a weight on a feature that is always 1, which is why its gradient is just the average error.
Why not keep squared error and simply put a sigmoid on the output?
The chain rule would then leave a factor $\sigma'(z) = p(1 - p)$ in the gradient. When the model is confidently wrong, $p$ is near 0 or 1, that factor is near zero, and learning stalls exactly when it is needed most. Cross-entropy cancels the factor, leaving $p - y$. Squared error through a sigmoid is also no longer convex.
On perfectly separable data, gradient descent on the logistic loss never settles. Why, and what is a standard fix?
Once a boundary separates the classes, scaling $w$ and $b$ up makes every prediction more confident and more correct, so the loss keeps falling towards zero without ever reaching it. Standard fixes are a penalty on the size of the weights (L2 regularisation) or stopping early, both in module 4.
Where this leads
A single sigmoid unit can only draw a straight boundary. Module 2 stacks these units into layers, and the boundaries start to bend.
Sources: C. M. Bishop, Pattern Recognition and Machine Learning, Springer (2006), §3.1 (least squares) and §4.3 (logistic regression, including the separable case); S. Boyd and L. Vandenberghe, Convex Optimization, Cambridge University Press (2004), §9.3 (gradient descent).