AI from scratch · Model zoo 2 of 10 · Logistic regression

Logistic regression

The model behind most yes/no predictions in banks, hospitals and ad systems: will this customer say yes, is this payment fraud, will this person click. It's page 1's weighted sum, squashed into a probability. You met it as chapter 3's single neuron; here it's a model in its own right, with weights you can read as odds, probabilities you can trust, and a short list of ways it fails.

1. The idea in one picture: a straight edge and a soft slope

Red dots are class 1, blue are class 0. The shading is the model's probability of red at every spot: bright red near 1, bright blue near 0, dark where it's unsure. Logistic regression's map is always the same shape: a straight edge (where the probability is exactly 0.5), with the probability sliding smoothly from one side to the other.

Predict, then pick ring around a disc: how well can a straight edge separate a disc from the ring around it?

Every straight line through a ring leaves ring dots on both sides, so the best line is no better than guessing. (Here it even scores 30% on new dots: it leaned toward a tilt in the 200 training dots that new dots don't share, a small lesson in fitting noise.) Now tick add x², y², x·y: the model gets the column x² + y² (the squared distance from the center) as a sum of two of its columns, and a straight edge in those columns is a circle on the map. The model is still linear, in the columns you gave it.

Logistic regression draws one straight edge and turns the distance from it into a probability; give it new columns and the edge can bend on the map.

2. How it learns: log-odds, a sigmoid and log-loss

The weighted sum \(z = w_0 + w_1 x_1 + \dots\) can be any number, and a probability must sit between 0 and 1, so the sigmoid squashes it: \(p = \sigma(z) = 1 / (1 + e^{-z})\). Turn it around and \(z\) is the log-odds, \(\ln \frac{p}{1-p}\): the model says the log-odds are a weighted sum. Training minimizes chapter 5's log-loss, which has no closed form like page 1's, so it's gradient descent (or a cleverer cousin):

\[ L = -\frac{1}{n}\sum_i \big[\,y_i \ln p_i + (1 - y_i)\ln(1 - p_i)\,\big], \qquad \nabla_w L = \frac{1}{n}\sum_i (p_i - y_i)\, x_i \]

The gradient reads as: for each example, the miss \(p_i - y_i\) times its inputs, averaged. It's the same shape as least squares' gradient, which is no accident. And the loss is a bowl (calculus 5), so there's one minimum and gradient descent finds it from anywhere.

On the bank calls, the weight for "the last campaign succeeded with this customer" is 2.68. By what factor does that multiply the odds of a yes? (\(e^{2.68}\))

\(e^{2.68} \approx 14.5\). Adding \(w\) to the log-odds multiplies the odds by \(e^w\): that's an odds ratio. Measured on the data: 64% of those customers said yes, against 9.6% of the rest. Each extra call in this campaign has an odds ratio of 0.92 (8% lower odds per call), and being called on a landline instead of a mobile, 0.40.
Why the weights read as odds, and why the probabilities come out honest
  1. The model says \(\ln \frac{p}{1-p} = w_0 + w_1 x_1 + \dots\). Raise \(x_1\) by 1 and the right side grows by \(w_1\).
  2. So \(\ln\) of the odds grows by \(w_1\), and the odds themselves get multiplied by \(e^{w_1}\), whatever the other columns are. That's the readable part: one number per column, the same everywhere.
  3. At the minimum the gradient is zero. Its intercept entry is \(\frac{1}{n}\sum_i (p_i - y_i) = 0\): the average predicted probability equals the share of yeses in the training data.
  4. The same holds for every column: \(\sum_i (p_i - y_i)\, x_{ij} = 0\). For a 0/1 column like "landline", that says the predicted yeses among landline calls add up to the real count.
  5. So log-loss pushes the predictions to be right on average in every group the columns describe: that's why logistic regression is usually calibrated out of the box (a 20% means about 20%), which many stronger models aren't.

3. Build it: gradient descent from scratch, then scikit-learn

The bank-call data from the features lesson: will a customer agree to a term deposit (11% did)? Five numeric columns, scaled; the leaking call duration is dropped.

Every group's average prediction sits near its real rate of yes, and the low groups are where most calls are. Notice the model hardly ever says "yes": its most confident tenth of calls averages a 40% chance (and 45% of them did say yes). That's the honest answer for these calls, and why chapter 12's thresholds matter more than accuracy here.

4. Where it shines, where it breaks

Shines: on the bank calls with every column (one-hot categories, scaled), logistic regression's test AUC was 0.779; scikit-learn's boosted trees got 0.760, XGBoost 0.776, LightGBM 0.748. With 10,000 rows and effects that mostly add up, a line is as good as anything, trains in milliseconds, and each weight is an odds ratio a regulator can read. That's why credit scoring still runs on it.

Four points on a line, the two left ones blue and the two right ones red: perfectly separable. What does unpenalized logistic regression do to the weight?

Log-loss keeps shrinking as the edge gets steeper, so the weight runs off to infinity (in practice, until the optimizer gives up). Measured on six points: with the penalty \(C = 1\) the weight is 1.2; \(C = 100\), 5.8; \(C = 10^4\), 12.7; \(C = 10^8\), 15.3 and still climbing when the solver stopped. The penalty is what keeps it finite. That's why scikit-learn penalizes by default.

Logistic regression is the readable, calibrated baseline for yes/no questions; it fails when the edge between classes isn't straight in the columns you gave it.

Where it breaks, and what people do

5. The knobs that matter

KnobIn scikit-learnWhat it does
Penalty strengthC (= 1/λ; default 1)Small C: smaller weights, softer probabilities, less overfitting. Tune on a log scale (LogisticRegressionCV).
Penalty kindl1_ratio (0 = squares, 1 = absolute values)As on page 1: L2 shrinks every weight, L1 switches columns off.
The featuresyour columnsOne-hot categories, bins, products and squares let one straight edge make bent boundaries.
Class weightsclass_weightMakes rare classes count more; better recall, worse calibration.
Thresholdyour code, on predict_probaNot 0.5 by law: pick it from what a false yes and a false no cost.
More than two classesautomatic (softmax)One weighted sum per class, turned into probabilities by softmax: chapter 5's classifier.

Next in the zoo: a model with no weights at all.

All chapters: AI from scratch. Bank marketing data: Moro, Cortez and Rita (2014), UCI Machine Learning Repository, CC BY 4.0.

Last updated