Week 12 · Capstone · Build a binary classifier from scratch
Derive a binary classifier, check its gradient, and explain why scaling changes the behaviour of training.
Derive a binary classifier, check its gradient, and explain why scaling changes the behaviour of training.
Build a classifier you can inspect from end to end
The capstone combines the pieces from the previous weeks in one small system. Each synthetic observation has two measurements and a label, either 0 or 1. The goal is to give unseen observations useful probabilities and verify that the learned model improves on a simple predictor that ignores the measurements.
You will trace one prediction by hand, derive its contribution to the gradient, check that derivative numerically, and compare raw and standardized training. The code is deliberately small enough to identify where each piece of the math runs.
The idea
Build a classifier for synthetic two-feature data. For a row x, compute a score z = x · w + b and turn it into a probability p = 1/(1 + exp(−z)). This is the sigmoid. The decision boundary at threshold 0.5 is the set of points where z = 0.
For a binary target y, the loss per row is −y ln(p) − (1 − y) ln(1 − p). An equivalent expression is log(1 + exp(z)) − yz. NumPy’s logaddexp evaluates that expression without computing exp(z) directly. The derivative with respect to z is p − y. If we append a column of ones to X, the derivative for all parameters, including the intercept, is Xᵀ(p − y)/n.
Choose a fixed train and test split. Compute the feature means and scales on the training rows, then reuse them on the test rows. The capstone compares a trained model against a constant predictor that uses the training positive rate. Use mean log loss as the primary metric so an overconfident mistake has a visible cost.
Derive the update from one observation
The score z = x · w + b adds a weighted contribution from each input and an intercept b. The sigmoid converts any real score into a probability p in (0, 1). A score of zero maps to 0.5. At threshold 0.5, the decision boundary is where the score is zero, so it is a line for two features.
For binary y, a positive observation contributes −ln(p) and a negative one contributes −ln(1 − p). Combining the two cases gives ℓ = −y ln(p) − (1 − y) ln(1 − p). Rewriting it as ln(1 + exp(z)) − yz is convenient because differentiating the first term gives exp(z)/(1 + exp(z)) = p. The derivative of the second term is −y. Thus ∂ℓ/∂z = p − y.
The score changes by xⱼ for each unit increase in weight wⱼ. By the chain rule, the derivative of the loss with respect to that weight is xⱼ(p − y). The derivative with respect to the intercept is simply p − y. Stacking the rows and averaging gives the batch gradient Aᵀ(p − y)/n, where A contains the features and an added column of ones.
For the one-row example below, take a learning rate of 0.1 and start with zero weights and intercept. Subtract 0.1 times the gradient. The new weights are (0.1, −0.05) and the intercept is 0.05. At x = (2, −1), the score becomes 0.30 and the probability rises from 0.50 to about 0.574.
Work it out
Before running the full lab, work through one row. With z = 0 and y = 1, p = 0.5 and the loss is ln(2). The derivative with respect to z is −0.5. If x = (2, −1), the weight gradient is (−1, 0.5) and the intercept gradient is −0.5. A descent step on that row raises its score.
The second feature in the generated data is recorded on a much larger scale. At the same learning rate, a step with raw features can increase the training loss. Standardization changes the scale of the derivatives. It keeps the information in the two features and makes the optimization easier to control for this example.
Use the finite-difference check before fitting. Then compare the first training step on the two scales and evaluate the fitted model once on the held-out rows.
The left panel shows a sample of the training rows. The right panel compares the first step at the same learning rate.
Run the Python lab
import numpy as np
rng = np.random.default_rng(2026)
features = rng.normal(size=(600, 2))
features[:, 1] *= 60
true_score = 0.9 * features[:, 0] - 0.8 * features[:, 1] / 60 - 0.25
def sigmoid(z):
return np.exp(-np.logaddexp(0, -z))
y = (rng.random(len(features)) < sigmoid(true_score)).astype(float)
train, test = slice(0, 450), slice(450, None)
mean = features[train].mean(axis=0)
scale = features[train].std(axis=0)
def with_intercept(rows):
return np.column_stack([rows, np.ones(len(rows))])
X = with_intercept((features - mean) / scale)
raw = with_intercept(features)
def loss(scores, targets):
return np.mean(np.logaddexp(0, scores) - targets * scores)
def gradient(A, targets, w):
return A.T @ (sigmoid(A @ w) - targets) / len(targets)
zero = np.zeros(3)
analytic = gradient(X[train], y[train], zero)
eps = 1e-5
numeric = np.array([
(loss(X[train] @ (eps * e), y[train])
- loss(X[train] @ (-eps * e), y[train])) / (2 * eps)
for e in np.eye(3)
])
np.testing.assert_allclose(analytic, numeric, atol=1e-8)
print("gradient check: passed")
rate = 0.2
before = loss(X[train] @ zero, y[train])
scaled_step = zero - rate * analytic
raw_step = zero - rate * gradient(raw[train], y[train], zero)
assert loss(X[train] @ scaled_step, y[train]) < before
assert loss(raw[train] @ raw_step, y[train]) > before
print("first step: scaled loss falls, raw loss rises")
w = zero.copy()
for _ in range(500):
w -= rate * gradient(X[train], y[train], w)
positive_rate = y[train].mean()
baseline_score = np.log(positive_rate / (1 - positive_rate))
baseline = loss(baseline_score, y[test])
model = loss(X[test] @ w, y[test])
assert model < baseline
print("held-out log loss: model beats constant baseline")
Expected output
gradient check: passed
first step: scaled loss falls, raw loss rises
held-out log loss: model beats constant baseline
Read the lab as three separate checks
- Correct derivative. The finite-difference loop perturbs one weight at a time and compares the change in loss with the analytic gradient. A passing derivative check establishes the update direction at that point.
- Stable training. Compare the first update on raw and standardized features with the same learning rate. The raw feature scale makes one update much larger in the space of scores. The standardized version uses means and scales computed on training rows only.
- Generalization. The baseline assigns every test row the same probability, equal to the positive rate in the training data. The fitted model is assessed on the same held-out rows with mean log loss. This gives one controlled comparison on the synthetic split.
Try changing the seed, the feature scale, or the learning rate one at a time. Record what changed and whether the derivative check, training behavior, or test comparison changed. If you tune choices repeatedly, use a validation split for those decisions and reserve a separate final test split.
Try it yourself
Submit a short report with the loss derivation, gradient check, two training curves, and held-out log loss for the baseline and the model.
- Print the exact losses and fitted weights. Convert the weights back into the original feature units and verify that the scores match.
- Reduce the raw-feature learning rate until its first step lowers the loss. Compare the number of updates it takes to reach the same loss as the scaled fit.
- Change one of the data-generation assumptions. For example, add a nonlinear term to the true score. Explain a pattern of errors the current linear boundary might miss.
Check your work. If scaled scores are w · ((x − μ)/s) + b, the original-unit weights are w/s and the new intercept is b − (w/s) · μ. The scores should match to floating-point precision. Use training loss for the optimizer comparison. Reserve test results for the final comparison after selecting the learning rate.