Logistic Regression
The foundation of all classification. Sigmoid, decision boundaries, cross-entropy, regularisation, and multi-class extension — built from scratch then in sklearn on real data.
Logistic regression is not regression. It is the foundation of all classification.
The name is misleading. Logistic regression predicts probabilities — "what is the probability that this DoorDash order will be late?" — and converts those probabilities into class labels. It is a classification algorithm, not a regression one. The "regression" refers to the linear equation inside it, not to what it predicts.
Despite being over 60 years old, logistic regression is still the first algorithm deployed at many companies for binary classification. At Stripe it predicts fraud. At DoorDash it predicts late deliveries. At every major bank it predicts loan defaults. It is fast, interpretable, probabilistically calibrated, and works well with good features. Every ML engineer should understand it completely.
This module builds logistic regression from scratch — sigmoid function, cross-entropy loss, gradient descent — so every piece is visible. Then shows you the sklearn implementation, all regularisation options, the multi-class extension, and every evaluation metric that matters for classification problems.
What this module covers:
Why linear regression breaks for classification
The obvious approach to binary classification: train a linear regression, predict a number, and if the number is above 0.5 call it class 1. This actually works for some problems. But it has three fundamental flaws that make it unreliable in general.
Linear regression predicts any real number. For a classification problem, a prediction of 1.7 or -0.3 is meaningless as a probability. The further a point is from the decision boundary, the more absurd the prediction becomes.
Add a single extreme point far into the positive class region. The regression line tilts toward it, moving the decision boundary and misclassifying many correctly-labelled points. Classification should not care about how far positive examples are from the boundary — only that they are on the right side.
For risk-sensitive decisions (fraud, loan default, medical diagnosis), you need a calibrated probability: "this transaction has a 3.2% chance of being fraud." Linear regression gives you a raw number with no probabilistic interpretation.
Logistic regression solves all three by applying one function to the linear prediction before outputting it: the sigmoid.
The sigmoid — squash any number into a probability
The sigmoid function takes any real number — large positive, large negative, anything in between — and maps it to a number strictly between 0 and 1. This is exactly the range of probabilities. As the input grows toward +∞, the output approaches 1. As it shrinks toward −∞, the output approaches 0. At input 0, the output is exactly 0.5.
The full logistic regression model chains two steps: first a linear combination of the features (the same as linear regression), then the sigmoid applied to the result. The linear part (z = w·x + b) can produce any number. The sigmoid converts it into a probability.
Cross-entropy loss — why not MSE for classification
We need a loss function that tells the model how wrong its probability prediction was. Why not use MSE — (p − y)² — the same loss as regression? Two reasons: MSE with sigmoid produces a non-convex loss surface full of local minima that gradient descent gets stuck in. And MSE penalises a confident wrong prediction (p=0.99, y=0) by only (0.99)²=0.98 — not harshly enough to teach the model to be certain only when correct.
Cross-entropy loss penalises a confident wrong prediction with −log(0.01) = 4.6 — much harsher. And it produces a perfectly convex loss surface, meaning gradient descent always finds the global minimum.
Logistic regression from scratch — gradient descent on cross-entropy
To train logistic regression we need the gradient of the cross-entropy loss with respect to the weights. The chain rule through sigmoid produces a beautifully simple result: the gradient is just the prediction error times the input feature — the same form as linear regression.
sklearn LogisticRegression — every option explained
sklearn's LogisticRegression has many parameters. Most tutorials use the defaults without explaining what they do. This section explains every important parameter so you can make principled choices rather than accepting defaults blindly.
Decision boundary and coefficient interpretation
The decision boundary is the set of points where the model is exactly 50% confident — the line (in 2D) or hyperplane (in n dimensions) that separates the two classes. Every point on one side gets predicted as class 1, every point on the other side as class 0.
Unlike neural networks, logistic regression coefficients are directly interpretable. Each coefficient tells you: holding all other features fixed, how does a one standard deviation increase in this feature change the log-odds of the positive class?
Classification evaluation — beyond accuracy
Accuracy is the wrong metric for almost every real classification problem. If 85% of deliveries are on-time, a model that always predicts on-time gets 85% accuracy while being completely useless. You need metrics that capture how well the model finds the minority class.
L1 and L2 regularisation — what they do and when to use each
Regularisation adds a penalty term to the loss function that discourages large weight values. Without it, logistic regression can memorise the training data (especially when features are many or highly correlated), producing large weights that don't generalise.
Multi-class logistic regression — OvR and Softmax
Binary logistic regression predicts two classes. For three or more classes, there are two strategies. One-vs-Rest (OvR) trains one binary classifier per class — "is this class 1 or not?", "is this class 2 or not?" — and picks the class with highest confidence. Multinomial (Softmax) extends the model directly to output a proper probability distribution over all classes simultaneously.
Production late-delivery predictor — end to end
This is what the actual day-one task looks like when you join a data team and are asked to build a late-delivery classifier. Feature engineering, cross-validation, threshold selection, and model persistence — all in one pipeline.
Every common logistic regression error — explained and fixed
Five things people get wrong about logistic regression
Swapping in the sigmoid is not a decorative final step — the entire loss function had to change to make the combination well-behaved. Minimising squared error through a sigmoid produces a non-convex, multi-modal loss surface that gradient descent can get stuck in. Logistic regression instead pairs the sigmoid with cross-entropy loss specifically because that combination is provably convex, guaranteeing gradient descent finds the global minimum. The sigmoid is not bolted onto linear regression's loss; the loss itself had to change for the model to work reliably.
Coefficients live in log-odds space, not probability space. A coefficient of 1.5 does not mean "adds 1.5 to the probability" — it means a one-unit increase in that feature multiplies the odds of the positive class by e^1.5, about 4.5x. Odds and probability are related but different things (odds equals p divided by one minus p), and turning a coefficient into an actual probability change requires running the whole linear combination back through the sigmoid. The effect of one feature on probability also depends on the values of every other feature — it is not a constant additive effect the way it would be in ordinary linear regression.
It trades one set of assumptions for a different, still-real set. Instead of assuming a linear relationship between features and the outcome directly, it assumes a linear relationship between features and the log-odds of the outcome — meaning the decision boundary it can draw is still a straight line, or hyperplane, in feature space, just wrapped in a sigmoid. It still assumes independent observations, needs the absence of severe multicollinearity for stable coefficients, and wants a reasonably large sample per feature to avoid unstable estimates. Fewer assumptions is not the same thing as no assumptions.
They solve different problems. L2 shrinks every coefficient toward zero but essentially never sets one to exactly zero — the right choice when most features probably carry some real signal and the goal is just to tame their magnitude. L1 can drive coefficients to exactly zero, performing automatic feature selection — better when many features are suspected to be pure noise and a sparse, interpretable model is preferred. Picking the wrong one either leaves noisy features in the model at full strength (L2 on a noisy feature set) or arbitrarily discards useful correlated features (L1 tends to keep one from a correlated group and zero out the rest).
0.5 is only correct when a false positive and a false negative cost exactly the same, which is rare in practice. A fraud model where missing real fraud is far more costly than a false alarm should use a lower threshold, flagging more transactions to catch more fraud while accepting more false alarms. A screening test with expensive or invasive follow-ups might want a higher threshold instead. The threshold is a business decision made by weighing the cost of each error type, not a property the model hands you — that is exactly why ROC and precision-recall curves exist: to let that point be chosen deliberately.
Logistic regression — 5 questions interviewers actually ask
MSE paired with a sigmoid produces a non-convex loss surface — because the sigmoid itself is non-linear, squaring the error re-introduces multiple local minima that gradient descent can get stuck in, with no guarantee of finding the best fit. Cross-entropy, paired with sigmoid, produces a convex loss surface, so gradient descent is guaranteed to converge to the global minimum. There is also a modelling reason: cross-entropy penalises confident wrong predictions far more harshly (predicting 0.99 when the true label is 0 costs about 4.6, versus MSE's roughly 0.98), which teaches the model to only be confident when it is actually likely to be correct — exactly the behaviour you want from a probability estimator.
A one standard deviation increase in income multiplies the odds of the positive outcome by e^0.7, roughly 2.0x, holding every other feature constant. I would not say it increases the probability by 70%, or by any fixed amount — the actual probability shift depends on where you start on the sigmoid curve: near the middle, around probability 0.5, a coefficient like this shifts probability substantially; near the tails, close to 0 or 1, the same coefficient barely moves probability at all because the sigmoid saturates there. I would also check whether income was actually standardised, since the coefficient is only comparable to the others if every feature shares the same scale.
Left at defaults, the model can hit 98% accuracy by predicting "not fraud" for every single transaction, since that already matches the base rate — the loss function has little incentive to fit the rare class well. I would stop trusting accuracy entirely and evaluate with precision, recall, and ROC-AUC or PR-AUC instead. For the training itself, I would use class_weight='balanced' so errors on the minority class are weighted more heavily in the loss, or oversample or undersample as an alternative. Just as important, I would not leave the decision threshold at 0.5 — I would pick a threshold on a validation set that reflects the real cost of missing fraud against the cost of a false alarm, since that is usually a bigger lever than the model architecture itself.
Probability is bounded between 0 and 1 and is what most people intuitively reason about. Odds is probability divided by one minus probability, ranging from 0 up to infinity — unbounded on the upper end. Logistic regression's linear component can output any real number, and the log of the odds is the one transformation of probability that also ranges over every real number, which is exactly why the model is linear in log-odds space rather than linear in probability space directly. Coefficients are reported as effects on log-odds, or on odds after exponentiating, because that is the space where the model's math is genuinely linear; reporting them as probability effects would be misleading, since that relationship is neither linear nor constant.
When the true decision boundary is clearly non-linear even in log-odds space — say the relationship between a feature and the outcome is U-shaped — plain logistic regression will underfit unless polynomial or interaction terms are hand-engineered in. I would also avoid it when I need complex feature interactions captured automatically, since tree-based models like XGBoost pick those up natively while logistic regression requires them to be specified by hand. And if calibrated probabilities are not actually needed, gradient boosting methods usually beat logistic regression on raw predictive accuracy for complex tabular data out of the box. I would still often start with logistic regression anyway, though, as a fast, interpretable baseline before reaching for something heavier.
You now have the foundation of classification. Every classifier builds on this.
Sigmoid. Cross-entropy. Gradient descent. Decision boundary. Regularisation. Threshold tuning. These are not logistic regression concepts — they are classification concepts. Neural networks use the same sigmoid (and its variants). The same cross-entropy loss. The same gradient descent. Deep learning is logistic regression applied many times with non-linear layers in between.
Module 21 covers Decision Trees — the algorithm that grows a flowchart from your data. Trees are the conceptual foundation of Random Forests and Gradient Boosting (XGBoost, LightGBM) — the algorithms that win most tabular ML competitions and power most production ML systems at tech companies today.
How trees split features to minimise impurity, how to control overfitting with depth and pruning, and how trees become the building blocks of Random Forests and XGBoost.
🎯 Key Takeaways
- ✓Logistic regression is not regression — it is a classification algorithm. The "regression" refers to the linear equation inside it. It outputs a probability between 0 and 1, converted to a class label by a threshold.
- ✓The sigmoid σ(z) = 1/(1+e⁻ᶻ) maps any real number to (0,1). It is the entire mechanism that makes logistic regression a probability model rather than an unbounded linear predictor.
- ✓Cross-entropy loss − [y·log(p) + (1−y)·log(1−p)] penalises confident wrong predictions far more harshly than MSE. It produces a convex loss surface — gradient descent always finds the global minimum.
- ✓The gradient of cross-entropy with respect to weights is (1/n) × Xᵀ(p−y) — identical in form to linear regression gradient. The sigmoid derivative cancels out perfectly, giving this clean result.
- ✓C is the inverse of regularisation strength. Large C = weak regularisation = risk of overfitting. Small C = strong regularisation = simpler model. Always tune C. L1 regularisation drives some coefficients to exactly zero (feature selection). L2 shrinks all coefficients toward zero.
- ✓Accuracy is the wrong metric for imbalanced classes. Use ROC-AUC (threshold-independent), Precision-Recall curve, and F1 score. The optimal threshold is rarely 0.5 — tune it to match the business cost of false positives vs false negatives.
- ✓Coefficients in logistic regression are directly interpretable: a coefficient of 1.5 for distance_km means one standard deviation increase in distance multiplies the odds of being late by e^1.5 = 4.5. This interpretability is why logistic regression remains widely used in production despite its simplicity.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.