Why Logistic Regression
Topic — Linear regression is designed to predict unbounded continuous quantities like housing prices or temperature. When applied to classification problems (pass/fail, default/repay, spam/ham), linear regression fails catastrophically: it produces nonsensical negative or probabilities and allows distant outliers to warp the decision boundary. This chapter explores these structural failure modes and introduces the sigmoid activation function as the proper mathematical gateway to probabilistic classification.
1. The Core Concept
In supervised binary classification, target labels are discrete binary states:
Rather than outputting hard discrete labels directly, modern machine learning models estimate the conditional posterior probability:
A valid probability must strictly adhere to the Kolmogorov axioms, specifically bounded within the unit interval:
While Ordinary Least Squares (OLS) linear regression fits a hyper-plane , its outputs are completely unconstrained (). Wrapping this linear score inside a monotonic, non-linear sigmoid squashing function guarantees valid probabilities.
If you only take one thing from this page
Despite its historical name, Logistic Regression is a classification algorithm, not a regression algorithm. It models the log-odds of a binary event as a linear function of features, mapping real-valued inputs into valid probabilities via the sigmoid function .
2. Interactive Sigmoid & Probability Sandbox
Use the interactive slider below to vary the linear score and observe how the sigmoid function maps real numbers into probabilities, odds, and discrete classifications:
Interactive Sigmoid & Odds Sandbox
Adjust the linear logit score $z$ to inspect the transformation into probability $\sigma(z)$:
3. The Two Fatal Flaws of Linear Regression
Why can we not simply fit Ordinary Least Squares and apply a cutoff at ?
- Flaw 1: Nonsensical Probabilities
- Flaw 2: Severe Outlier Sensitivity
- The Problem: Linear equations are unbounded rays: as , .
- Real-world Disaster: If predicting student pass/fail based on study hours ():
- Student studying 1 hour: predicted score is (Negative probability!).
- Student studying 15 hours: predicted score is (Probability of 182%!).
- Statistical Violation: Violates Kolmogorov probability axioms. Downstream decision systems (expected value, risk budgeting) fail when passed negative probabilities.
- The Problem: OLS minimizes squared residuals .
- The Distortion: A student who studied 50 hours and passed easily has . The linear model predicts .
- The Paradox: Because , OLS treats this successful student as an enormous error with squared loss .
- The Collapse: To minimize this artificial penalty, OLS rotates its slope downwards, pulling down predictions for borderline students and misclassifying true positives.
4. Interactive Outlier Shock Comparator
Observe how adding an extreme data point tilts a linear regression line while leaving Logistic Regression's decision boundary stable:
Outlier Vulnerability Comparator
Compare how an extreme observation (50 study hours) warps model parameters:
• 6-Hour Student Prediction: 0.40 / Pass boundary
• Impact: Standard linear fit across range.
• 6-Hour Student Prediction: 0.82 (PASS )
• Impact: Sigmoid plateau asymptotes cleanly at 1.0; extreme points create zero gradient distortion!
5. Mathematical Anatomy of the Sigmoid Curve
The standard logistic sigmoid function maps any real number into the open unit interval :
- 1. Numerator: 1
- 2. Denominator Term: e^(-z)
- 3. Fundamental Symmetry
- Acts as the upper asymptotic ceiling.
- As , , forcing .
- The exponential engine driving smooth non-linear saturation.
- When , , producing the exact symmetry center: .
- As , , driving .
- The Identity: .
- Proof:
- Engineering Value: The probability of failure () equals the sigmoid of the negated linear score.
Key Sigmoid Benchmarks (Mental Math)
| Input () | Expression () | Probability () | Practical Interpretation |
|---|---|---|---|
| Near certainty of Negative Class | |||
| Low confidence Negative | |||
| Maximum uncertainty (Decision Boundary) | |||
| Strong confidence Positive | |||
| Near certainty of Positive Class |
6. Implementation Lab
Lab Exercise: Linear Classification Failures & Sigmoid Mechanics
An interactive, fully functional Google Colab / Jupyter Notebook is available to demonstrate linear regression probability failures, outlier line tilts, and sigmoid symmetry live in your browser.
How to run the lab:
- Click the "Open In Colab" badge above to launch the interactive notebook.
- Run cells sequentially to reproduce linear probability violations and sigmoid stability.
Key Experiments to Run:
- Experiment 1 (Negative & >100% Errors): Fit OLS linear regression on 10 student records to observe predicted values of and .
- Experiment 2 (Outlier Shock Test): Inject a single student at to watch the linear slope collapse by while Logistic Regression maintains accurate classifications.
- Experiment 3 (Sigmoid Symmetry Verification): Empirically test across floating-point ranges using
scipy.special.expit.
7. Common Mistakes
- 1. Confusing Classification with Regression
- 2. Using OLS for Probability Estimation
- 3. Blindly Fixing Threshold at 0.5
- 4. Confusing Sigmoid with Tanh
- 5. Fitting Linear Regression Outliers
- The Misconception: "Logistic Regression has 'Regression' in its name, so it is used to predict continuous numeric values."
- Wrong Thinking: Using LogisticRegression to forecast prices or temperature.
- The Right Principle: The name is an artifact of statistics (modeling the continuous log-odds parameter). Logistic Regression is fundamentally a classification algorithm designed for discrete categorical targets.
- The Misconception: "We can fit linear regression to 0/1 labels and simply clamp predictions into [0, 1] using min/max."
- Wrong Thinking: Patching linear models with artificial clipping.
- The Right Principle: Clamping ignores the non-linear relationship of probabilities near 0 and 1, distorts variance, and remains fragile to outlier-induced boundary shifts. Use Logistic Regression natively.
- The Misconception: "A model should always predict positive when ."
- Wrong Thinking: Treating the 0.5 mathematical midpoint as a universal business rule.
- The Right Principle: Thresholds must reflect downstream asymmetric costs. In fraud detection or cancer diagnostics, false negatives are catastrophic; lower the threshold to 0.1 or 0.2 to maximize recall.
- The Misconception: "Sigmoid and Hyperbolic Tangent (Tanh) are interchangeable activation functions."
- Wrong Thinking: Using Tanh to model probabilities.
- The Right Principle: Sigmoid maps to , matching probability axioms. Tanh maps to , zero-centered for neural network hidden states, but invalid for direct binary probabilities.
- The Misconception: "Squared error loss () is suitable for training binary classification models."
- Wrong Thinking: Minimizing on binary targets.
- The Right Principle: Squared error penalizes correct but confident predictions (). Logistic regression uses Binary Cross-Entropy (Log Loss), which creates zero penalty for confident correct classifications.
8. Summary
Linear Regression Failures
- Unbounded Output: Linear predictions escape , producing impossible negative and probabilities.
- Outlier Sensitivity: OLS penalizes confident correct samples (), tilting the decision boundary.
- Loss Function Mismatch: Mean Squared Error creates non-convex optimization surfaces when paired with non-linear activations.
The Sigmoid Solution
- Strict Bounding: mathematically guarantees outputs in open unit interval .
- Symmetry: Perfect anti-symmetry centered at via .
- Robust Asymptotes: Extreme values plateau smoothly, rendering parameter updates robust to outliers.
Key Takeaways
- Probabilities require sigmoid: Linear models cannot enforce the unit interval constraint .
- Sigmoid symmetry simplifies math: ensures that modeling automatically defines .
- Asymptotes protect against outliers: The plateau of the S-curve prevents extreme inputs from distorting classifications near the decision threshold.
Next Section: The Sigmoid and Fitting - deriving the log-loss function, maximum likelihood estimation, and gradient descent optimization.
9. Active Recall
Test your understanding by answering first, then clicking to reveal the underlying principles.
Interactive Checkpoint Quiz
Interactive Checkpoint: OLS vs. Sigmoid Loss
Why does fitting a linear regression model with Mean Squared Error (MSE) fail when an extremely obvious positive sample (e.g. $x=100, y=1$) is present in the training set?
Review Flashcards
1. [THEORY] Why is the sigmoid function preferred over a simple step function (Heaviside) for classification?
- Differentiability: A step function has a derivative of zero everywhere except at , where it is undefined. Gradient-based optimization (gradient descent) cannot compute parameter updates.
- Continuous Probabilities: The sigmoid function is smooth, continuously differentiable everywhere (), providing informative gradients that indicate not just whether a sample is classified correctly, but how confident the prediction is.
2. [MATH] Prove the sigmoid symmetry property: σ(-z) = 1 - σ(z).
- Start with the right-hand side:
- Multiply numerator and denominator by :
- Thus, holds identically for all .
3. [PRACTICE] A logistic regression model outputs a linear logit score of z = 2.197. What is the predicted probability and odds?
- Odds: (i.e. 9 to 1 odds).
- Probability: ().
- Direct Sigmoid: .
4. [ANALYZE] Why is setting the classification threshold to 0.5 dangerous in an automated credit card fraud detection system?
- Asymmetric Costs: A false positive (flagging a legit 5,000 fraudulent charge) causes direct financial loss.
- Severe Imbalance: Fraud represents of transactions. A default 0.5 threshold will fail to flag suspicious transactions that have a 20% or 30% probability of fraud.
- Solution: Lower the threshold to 0.05 or 0.10 to prioritize recall over precision.
5. [THEORY] What geometric shape is the decision boundary of Logistic Regression in feature space?
- A Linear Hyperplane: The decision boundary occurs where , which corresponds to .
- Since , the decision boundary is a straight line in 2D, a flat plane in 3D, and a hyperplane in higher dimensions.
- Despite the non-linear sigmoid activation, Logistic Regression is fundamentally a linear classifier.