Learn machine learning from scratch

Start at chapter 1 and build up: what a model is, how it measures its own mistakes, and how it learns. Everything is worked out in plain Python, with the maths shown rather than assumed. Two shorter tracks hold reference notes on the maths and on modern architectures.

Track Progress: 0 Completed
0%
Maths for MLLEVEL 2 Β· INTERMEDIATEModule 7 Β· Putting it together

Capstone: logistic regression from scratch

A dot product, a sigmoid, cross-entropy and gradient descent make a classifier. The chain rule turns its gradient into prediction minus label.

10 min Prerequisites: Modules 1, 4, 5 and 6

1. The idea

The second capstone builds a classifier from the parts. Two classes of points lie in the plane. The model scores each point with z = 𝐰ᡀ𝐱 + b (a dot product, Module 1), squashes the score into a probability p = Οƒ(z) with the sigmoid, and learns by minimizing cross-entropy, the negative log-likelihood of a Bernoulli (Module 5), with gradient descent (Module 6).

The gradient comes out remarkably clean. By the chain rule (Module 4), the derivative of the cross-entropy with respect to z is just p βˆ’ y, the predicted probability minus the label. So βˆ‡π°L = (1/n) Ξ£ (pα΅’ βˆ’ yα΅’) 𝐱ᡒ: the same shape as linear regression's gradient, with p where Ε· was.

The decision boundary, where p = 0.5, is the line 𝐰ᡀ𝐱 + b = 0. The loss is convex, so training finds the best line from any start. A logistic regression is a one-neuron network; add hidden layers and you have the networks of the Core Course.

2. Try it: train a boundary

Circles are class 1 and squares class 0. The line is where the model says 50/50. Train and watch it turn and settle while the loss falls.

Forty points in two overlapping groups, circles and squares, and a straight decision boundary that starts in the wrong place. Buttons train 10 or 200 steps of gradient descent; the line turns to separate the groups, and the text gives the weights, the cross-entropy loss and the accuracy.

3. The math

Score, then probability
z=w⊀x+b,p=Οƒ(z)=11+eβˆ’zz = \mathbf{w}^\top\mathbf{x} + b, \qquad p = \sigma(z) = \frac{1}{1 + e^{-z}}
Read an equation: the linear model and the sigmoid.
The loss
L=βˆ’1nβˆ‘i=1n(yilog⁑pi+(1βˆ’yi)log⁑(1βˆ’pi))L = -\frac{1}{n}\sum_{i=1}^{n}\Big(y_i \log p_i + (1 - y_i)\log(1 - p_i)\Big)
Binary cross-entropy: βˆ’log of the probability given to the true label.
The clean gradient
βˆ‚Liβˆ‚zi=piβˆ’yi\frac{\partial L_i}{\partial z_i} = p_i - y_i
The sigmoid's derivative p(1 βˆ’ p) cancels against the log's 1/p.
All the gradients
βˆ‡wL=1nβˆ‘i(piβˆ’yi) xi,βˆ‚Lβˆ‚b=1nβˆ‘i(piβˆ’yi)\nabla_{\mathbf{w}} L = \frac{1}{n}\sum_{i}(p_i - y_i)\,\mathbf{x}_i, \qquad \frac{\partial L}{\partial b} = \frac{1}{n}\sum_{i}(p_i - y_i)
In NumPy: X.T @ (p βˆ’ y) / n.
The decision boundary
w⊀x+b=0β€…β€ŠβŸΊβ€…β€Šp=0.5\mathbf{w}^\top\mathbf{x} + b = 0 \iff p = 0.5
A straight line in 2-D, a flat plane in more dimensions.

4. The code (python)

mm7_logreg.py
import numpy as np

rng = np.random.default_rng(3)
n = 200
y = rng.integers(0, 2, size=n)                                # labels, 0 or 1
centres = np.where(y[:, None] == 1, [1.2, 0.9], [-1.1, -0.8])
X = centres + rng.normal(size=(n, 2))                        # two overlapping clouds

w, b = np.zeros(2), 0.0
for step in range(2000):
    p = 1 / (1 + np.exp(-(X @ w + b)))
    w -= 0.5 * X.T @ (p - y) / n
    b -= 0.5 * np.mean(p - y)

p = 1 / (1 + np.exp(-(X @ w + b)))
loss = -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
print(w.round(3), round(b, 3))                               # [2.49  2.049] -0.644
print(round(loss, 4), np.mean((p > 0.5) == y))               # 0.1662 0.915

6. Check yourself

Answer all 4 questions correctly to complete the chapter Β· 0 / 4 done
Q1/4 For one example, what is the derivative of the cross-entropy loss with respect to the score z?
Q2/4 Where is the decision boundary?
Q3/4 Is logistic regression's loss convex in 𝐰 and b?
Q4/4 Logistic regression is the same thing as…

Finished this chapter?

Weekly newsletter

What changed in ML architectures this week

New models worth knowing, benchmark moves, and one architecture explained in plain words. Free, once a week, unsubscribe anytime.