Logistic Regression, Sigmoid, Softmax & GLMs
Odds & Log-Odds, Sigmoid S-curves, Binary Cross-Entropy, Multiclass Softmax + LogSumExp stability, and Poisson GLMs
Logistic Regression predicts the probability of a discrete class (0 or 1, or K classes via Softmax) by squashing a linear score through the S-shaped sigmoid curve.
Linear regression can output nonsensical probabilities like -0.4 or +1.8; Logistic Regression guarantees calibrated probabilities strictly between 0 and 1.
Logistic Regression & Softmax Cross-Entropy ARE the output head of practically every classifier and Large Language Model on Earth!
Understanding LogSumExp stabilization (z − max(z)) stops exp(1000) = inf → NaN crashes in PyTorch, Softmax Attention, and LLM token decoding!
Logistic Regression is the #1 fast, calibrated, explainable baseline in ads CTR, credit scoring, and medical risk (odds ratios!).
'Why do we use Cross-Entropy instead of MSE for Logistic Regression?' and 'Write numerically stable Softmax & Log-Softmax from scratch' are top FAANG screens!
Why do we train Logistic Regression with Binary Cross-Entropy (Log-Loss) instead of Mean Squared Error (y − σ(z))²?
- Explain why Linear Regression fails for binary classification and how Sigmoid σ(z) = 1/(1+e⁻ᶻ) maps logits cleanly to (0, 1).
- Interpret Logistic Regression weights as changes in Log-Odds (logit) and prove why Binary Cross-Entropy is convex (unlike MSE on Sigmoid!).
- Generalize to K classes with Numerically Stable Softmax (subtracting max(z) to prevent exp() overflow!) and Categorical Cross-Entropy.
- Unify Linear, Logistic, and Poisson Regression as Generalized Linear Models (GLMs).
Despite the word 'Regression' in its name, Logistic Regression is a Classification algorithm! It computes a linear score z = wᵀx + b just like Chapter 5, then feeds z through an S-shaped Sigmoid (for 2 classes) or Softmax (for classes) to output clean, calibrated probabilities!
1. From Linear Scores to Probabilities (Sigmoid & Log-Odds)
Imagine predicting whether a patient has flu (0 or 1) from their fever temperature. A straight line shoots above 1.0 (140% chance of flu?!) and below 0.0 (−20% chance?!). The Sigmoid curve gently bends both ends flat so predictions NEVER escape (0, 1), while its decision boundary (p̂ = 0.5 ⟺ wᵀx + b = 0) stays a crisp straight hyperplane!
Interpreting Logistic Coefficients via Odds
Because , increasing feature by multiplies the Odds by ! (For example, higher odds!)
A spam model outputs logit z = 0 for Email A and z = +2 for Email B. What is the predicted probability σ(z) for Email A, and roughly for Email B? (Hint: e⁻² ≈ 0.135)
2. Binary Cross-Entropy & Why Its Gradient Is So Clean
Why does Logistic Regression minimize Binary Cross-Entropy (Log-Loss)? Because maximizing the Bernoulli Likelihood (Probability Ch 8!) produces the exact formula −[y log(p̂) + (1−y) log(1−p̂)] — which is strictly convex (one global minimum!) and hits confident mistakes with a massive penalty!
Click the pieces of the Logistic Gradient below — notice it looks 100% identical to Linear Regression's gradient!
Sigmoid's derivative σ(1−σ) cancels out completely with log's derivative!
Model's current confidence between 0 and 1.
BCEWithLogitsLoss) uses this exact math!3. Multiclass Softmax, LogSumExp Stability & GLMs
Need to classify K = 10 digits or 50,000 LLM tokens? Replace Sigmoid with Softmax! And remember the #1 numerical stability rule in Deep Learning: subtract max(z) BEFORE calling exp() so exp(1000) never overflows to inf → NaN! Play with the Softmax Temperature Dial below!
Generalized Linear Models (GLMs) — One Family Rules Them All!
- Normal target (): Identity link → Linear Regression (MSE).
- Binary target (): Sigmoid/Logit link → Logistic Regression (BCE).
- Count target (): Log link () → Poisson Regression!
Pause & Check: Adding a constant c = −1000 to EVERY entry of logit vector z = [1002, 1001, 1000] changes Softmax(z) by how much?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
NO! Because σ(Xw) is nonlinear, setting the gradient to zero has no closed-form algebraic solution. Instead, scikit-learn solves it rapidly via L-BFGS, Newton-CG, or Mini-Batch Gradient Descent — and because Cross-Entropy is strictly convex, it is guaranteed to reach the unique global minimum!
Tune Steepness w & Boundary Shift x₀ to Minimize Log-Loss
C = 1/λ in sklearn!Ads Click-Through Rate (CTR) Calibration
Online ad auctions require well-calibrated probabilities P(click) — Logistic Regression & Log-Loss naturally optimize calibrated probabilities!
LLM Next-Token Softmax & Temperature
Every Transformer outputs raw logits z ∈ ℝ^V and applies softmax(z / T) to sample the next token!
Medical Risk & Odds-Ratio Scorecards
Hospitals love Logistic Regression because exp(wⱼ) translates directly into clinical odds ratios!
Poisson GLMs for Demand & Insurance
Predicting non-negative event counts (accidents/year, orders/hour) uses log-link Poisson regression.
import numpy as np
# Numerically Stable Softmax & Log-Softmax (zero overflow/underflow!)
def stable_softmax(z: np.ndarray) -> np.ndarray:
z_shift = z - np.max(z, axis=-1, keepdims=True)
e = np.exp(z_shift)
return e / np.sum(e, axis=-1, keepdims=True)
def stable_log_softmax(z: np.ndarray) -> np.ndarray:
m = np.max(z, axis=-1, keepdims=True)
z_shift = z - m
return z_shift - np.log(np.sum(np.exp(z_shift), axis=-1, keepdims=True))
logits = np.array([1002.0, 1001.0, 1000.0]) # Raw np.exp(logits) would overflow to NaN!
print("Stable Softmax:", np.round(stable_softmax(logits), 4))
np.exp(z) / np.sum(np.exp(z)) without subtracting max(z).z - np.max(z, axis=-1, keepdims=True) first!np.log(sigmoid(z)) directly → log(0.0) = -inf → NaN when z = −100.BCEWithLogits(z, y) = max(z, 0) - z*y + log(1 + exp(-|z|))!LogisticRegression(C=...), C = 1/λ is INVERSE regularization!C = STRONGER regularization; larger C = WEAKER regularization!sklearn.linear_model.LogisticRegression(C=...), which applies STRONGER L2 regularization?