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?
- About 90%
- No better than a coin flip
- 0%
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}\))
Why the weights read as odds, and why the probabilities come out honest
- 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\).
- 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.
- 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.
- 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.
- 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?
- Grows it forever: every step makes the probabilities a bit closer to exactly 0 and 1
- Stops at the weight that separates them
- Can't fit it at all
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
- Edges that bend. Rings, checkerboards, "risky only at night and only downtown": a single straight edge can't. Add the columns that make it straight (squares, products, bins), or switch to trees (pages 5 to 7).
- Perfect separation. When some column splits the classes completely (often a leak: "account closed" predicting churn), the weight runs to infinity and the probabilities become 0 and 1. A penalty keeps it finite; then ask why that column is so perfect.
- Twin columns. As on page 1, near-duplicates make the weights unreadable; the economy columns in the bank data (euribor, employment, variation rate) are 0.91 to 0.97 correlated with each other, which is why the code box keeps only one.
- Unscaled columns. Gradient descent crawls when one column is in thousands and another in fractions (the bowl is a long narrow valley), and the penalty is unfair across scales. Scale first.
- Rare classes. At 1% positives, "always no" is 99% accurate and the model may never predict yes. Judge it by AUC or precision and recall, pick the threshold from the costs (chapter 12), or reweight the classes (
class_weight="balanced"), which shifts the probabilities so they're no longer calibrated.
5. The knobs that matter
| Knob | In scikit-learn | What it does |
|---|---|---|
| Penalty strength | C (= 1/λ; default 1) | Small C: smaller weights, softer probabilities, less overfitting. Tune on a log scale (LogisticRegressionCV). |
| Penalty kind | l1_ratio (0 = squares, 1 = absolute values) | As on page 1: L2 shrinks every weight, L1 switches columns off. |
| The features | your columns | One-hot categories, bins, products and squares let one straight edge make bent boundaries. |
| Class weights | class_weight | Makes rare classes count more; better recall, worse calibration. |
| Threshold | your code, on predict_proba | Not 0.5 by law: pick it from what a false yes and a false no cost. |
| More than two classes | automatic (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