Chapter 16 of 42 · ~26 min read & lab+65 XP
Chapter 16 · Machine Learning

Logistic Regression, Sigmoid, Softmax & GLMs

Odds & Log-Odds, Sigmoid S-curves, Binary Cross-Entropy, Multiclass Softmax + LogSumExp stability, and Poisson GLMs

What Is It?

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.

Why Is It Required?

Linear regression can output nonsensical probabilities like -0.4 or +1.8; Logistic Regression guarantees calibrated probabilities strictly between 0 and 1.

Everyday Analogy: A dimmer switch that smoothly maps any raw evidence score into a clean 0%–100% confidence gauge.
Why ML Engineers & Data Scientists Actually Need This

Logistic Regression & Softmax Cross-Entropy ARE the output head of practically every classifier and Large Language Model on Earth!

ML / AI Engineer

Understanding LogSumExp stabilization (z − max(z)) stops exp(1000) = inf → NaN crashes in PyTorch, Softmax Attention, and LLM token decoding!

Data Scientist

Logistic Regression is the #1 fast, calibrated, explainable baseline in ads CTR, credit scoring, and medical risk (odds ratios!).

Interview & Debug Edge

'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!

Step 0 · Test Your Gut Before Any Math!

Why do we train Logistic Regression with Binary Cross-Entropy (Log-Loss) instead of Mean Squared Error (y − σ(z))²?

What You Will Master in This Chapter
  • 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).
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
z = wᵀx + bSay aloud:“Logit (Log-Odds Score)”
Plain-English Meaning
Unbounded confidence score from −∞ to +∞: z = 0 means 50/50, z = +3 means ~95% sure!
Everyday Example
log(p / (1 − p)) = wᵀx + b.
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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 KK classes) to output clean, calibrated probabilities!

1. From Linear Scores to Probabilities (Sigmoid & Log-Odds)

Everyday Story First (Zero Math Yet!)

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!

1.00.0z = 0 → p = 0.50Linear breaks > 1.0!Sigmoid σ(z) = 1 / (1 + e⁻ᶻ)
Figure 7.1 — Why Linear Regression Fails for Classification: a straight line shoots below 0% and above 100%, while the Sigmoid S-curve smoothly squishes any score z ∈ (−∞, +∞) into (0, 1)!

Interpreting Logistic Coefficients via Odds

Because ln⁡ ⁣(p1−p)=w⊤x+b\ln\!\left(\frac{p}{1 - p}\right) = \mathbf{w}^\top \mathbf{x} + b, increasing feature xjx_j by +1+1 multiplies the Odds p1−p\frac{p}{1 - p} by ewje^{w_j}! (For example, wj=+0.693  ⟹  e0.693=2.0×w_j = +0.693 \implies e^{0.693} = 2.0\times higher odds!)

Try It YourselfWarm-Up

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

Everyday Story First (Zero Math Yet!)

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!

Confidently Wrong (p̂ → 0) ⇒ Penalty → ∞!p̂ → 1 ⇒ Loss = 0Predicted Probability p̂ when True Label y = 1 [Loss = −log(p̂)]
Figure 7.2 — Binary Cross-Entropy (Log Loss): when true y = 1, predicting p̂ = 0.99 incurs near-zero penalty, while being confidently wrong (p̂ = 0.01) incurs a massive −log(0.01) = 4.6 penalty!

Click the pieces of the Logistic Gradient below — notice it looks 100% identical to Linear Regression's gradient!

Formula Anatomy · Click Any Colored Piece to Decode It
Logistic Gradient: ∇_w BCE = (1/n) · Xᵀ (σ(Xw + b) − y)

Sigmoid's derivative σ(1−σ) cancels out completely with log's derivative!

Predicted Probability

Model's current confidence between 0 and 1.

In our example: True y=1, predicted p̂=0.10 → huge error (−0.90)!
Put it together with real numbers: Every single binary classifier head in PyTorch (BCEWithLogitsLoss) uses this exact math!

3. Multiclass Softmax, LogSumExp Stability & GLMs

Everyday Story First (Zero Math Yet!)

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!

Raw Logits z[2.0, 1.0, 0.1]→Stable Softmaxexp(zᵢ − max z) / Σ exp→Probabilities (Σ=1)[0.66, 0.24, 0.10]
Figure 7.3 — Multiclass Softmax: raw logits z pass through exp(z − max z) / Σ exp to produce a valid K-class probability distribution summing to 100%.

Generalized Linear Models (GLMs) — One Family Rules Them All!

  • Normal target (y∈Ry \in \mathbb{R}): Identity link → Linear Regression (MSE).
  • Binary target (y∈{0,1}y \in \{0, 1\}): Sigmoid/Logit link → Logistic Regression (BCE).
  • Count target (y∈{0,1,2,… }y \in \{0, 1, 2, \dots\}): Log link (λ=ew⊤x\lambda = e^{w^\top x}) → Poisson Regression!
Hands-On Mini-Lab · Softmax Temperature Dial (Used in Classifiers & Every LLM!)
Cat (z=2.4)70.8%
Dog (z=1.2)21.3%
Fox (z=0.2)7.8%
Pause & Check · Quick Intuition Pulse

Pause & Check: Adding a constant c = −1000 to EVERY entry of logit vector z = [1002, 1001, 1000] changes Softmax(z) by how much?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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!

Interactive Visual Lab
Lab Challenge: Tune weights (w₁, w₂) in the Logistic Decision Boundary Deep Lab until Binary Cross-Entropy drops below 0.20!
Interactive Stage • Logistic Regression & Binary Cross-Entropy

Tune Steepness w & Boundary Shift x₀ to Minimize Log-Loss

Log-Loss = 0.134
Intuition Takeaway: Logistic Regression pairs linear logits z = wᵀx + b with Sigmoid/Softmax and strictly convex Cross-Entropy Loss — always stabilize exp() via max-shifting and remember C = 1/λ in sklearn!
Where This Powers Real ML, Deep Learning & Generative AI

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.

Production NumPy & PyTorch Code Patterns
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))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Computing np.exp(z) / np.sum(np.exp(z)) without subtracting max(z).
Best Practice: Always shift by z - np.max(z, axis=-1, keepdims=True) first!
Trap #2: Computing np.log(sigmoid(z)) directly → log(0.0) = -inf → NaN when z = −100.
Best Practice: Use the stable identity BCEWithLogits(z, y) = max(z, 0) - z*y + log(1 + exp(-|z|))!
Trap #3: Forgetting that in scikit-learn LogisticRegression(C=...), C = 1/λ is INVERSE regularization!
Best Practice: Smaller C = STRONGER regularization; larger C = WEAKER regularization!
Chapter Mastery Check (+65 XP)
Score: 0 / 5
11. In sklearn.linear_model.LogisticRegression(C=...), which applies STRONGER L2 regularization?
22. What is the derivative of Sigmoid σ(z)?
33. Why do we subtract max(z) before exponentiating in Softmax?
44. What happens to unregularized Logistic Regression weights on 100% linearly separable data?
55. As Softmax Temperature T → 0⁺, the output distribution becomes:

Apply What You Learned — Solve Matching Coding Problems