The Sigmoid and Fitting
Topic — How do we fit an S-shaped curve to discrete binary data? In linear regression, parameters are chosen by minimizing Mean Squared Error through a closed-form formula. In logistic regression, squared error creates non-convex surfaces with treacherous local minima. This chapter derives Binary Cross-Entropy (Log Loss) from the principle of Maximum Likelihood Estimation (MLE), steps through hand-worked parameter fitting, and tracks gradient descent convergence.
1. The Core Concept
Logistic regression combines a linear combination of input features with the non-linear sigmoid activation function:
Because the output represents the probability of a Bernoulli random variable, we cannot optimize parameters and using Ordinary Least Squares. Instead, we use Maximum Likelihood Estimation (MLE) to find the parameters that make the observed training data most probable.
If you only take one thing from this page
Log Loss (Binary Cross-Entropy) is not an arbitrary choice: it is the direct negative log-likelihood of a Bernoulli distribution. It is strictly convex with respect to linear weights, guaranteeing that gradient descent always converges to the global minimum without getting trapped in local valleys.
2. Interactive Loss Penalty Sandbox: Log Loss vs. MSE
Compare how Binary Cross-Entropy and Mean Squared Error respond to prediction certainty:
Loss Function Penalty Explorer
Select the true label and adjust predicted probability ŷ to inspect error divergence:
3. Deriving Log Loss from Maximum Likelihood Estimation
Why do we use ? It is not an arbitrary heuristic.
- 1. The Bernoulli Likelihood
- 2. The Log-Likelihood
- 3. Negative Log-Likelihood (Loss)
- For a single sample , the probability of observing outcome is given by the Bernoulli PMF:
- If , this simplifies to .
- If , this simplifies to .
- Assuming independent and identically distributed (i.i.d.) observations, the joint likelihood across all samples is the product:
- Multiplying thousands of fractional probabilities causes severe floating-point underflow.
- Taking the natural logarithm converts the product into a numerically stable summation:
- In optimization, algorithms are conventionally formulated to minimize cost rather than maximize likelihood.
- Multiplying by and averaging over samples produces the standard Binary Cross-Entropy Loss function:
- Maximizing likelihood is mathematically identical to minimizing log loss.
4. Interactive Parameter Fitting Sandbox
Experiment with fitting a logistic regression model manually on 5 students (, ):
Interactive 5-Student Parameter Fitting
Adjust slope m and intercept b to minimize mean log loss across the 5 students:
(at m = 0.40, b = -1.60)
| Hours (x) | Actual (y) | z = mx + b | P(Pass) = σ(z) | Sample Loss |
|---|---|---|---|---|
| 2 | 0 | -0.70 | 33.2% | 0.4032 |
| 4 | 0 | 0.00 | 50.0% | 0.6931 |
| 6 | 1 | 0.70 | 66.8% | 0.4032 |
| 8 | 1 | 1.40 | 80.2% | 0.2204 |
| 10 | 1 | 2.10 | 89.1% | 0.1155 |
5. Optimization Mechanics: Gradient Descent
Unlike Ordinary Least Squares linear regression, setting yields a transcendental equation that cannot be solved analytically in closed form. We must use iterative optimization (Gradient Descent).
The Elegance of the Gradient
Using the chain rule, the derivative of the sigmoid is:
When taking the partial derivative of Log Loss with respect to weight , the non-linear terms cancel out cleanly:
The Universal Gradient Pattern
Notice that the gradient for Logistic Regression is identical in algebraic form to the gradient of Linear Regression:
The only difference is that for Logistic Regression, is bounded between and .
6. Implementation Lab
Lab Exercise: Log Loss Calculations & Gradient Descent Convergence
An interactive, fully functional Google Colab / Jupyter Notebook is available to experiment with manual parameter grid searches, compare Log Loss against MSE, and track SGD convergence 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 benchmark candidate parameter pairs and train an SGD classifier.
Key Experiments to Run:
- Experiment 1 (Grid Search over Parameters): Verify how candidate parameters achieve minimum log loss () on the 5-student toy dataset.
- Experiment 2 (Extreme Error Divergence): Compare a prediction of on an actual positive: observe MSE plateauing at while Log Loss spikes to .
- Experiment 3 (Tracking SGD Convergence): Train
SGDClassifier(loss='log_loss')on 50 students across 50 epochs, watching loss smoothly descend from to .
7. Common Mistakes
- 1. Believing Closed-Form Solutions Exist
- 2. Using MSE with Sigmoidal Activations
- 3. Neglecting Numerical Stability in Logarithms
- 4. Forgetting to Scale Features Before Optimization
- 5. Omitting Regularization on Separable Data
- The Misconception: "We can compute optimal logistic regression weights directly using a matrix formula like ."
- Wrong Thinking: Searching for an analytical closed-form solution.
- The Right Principle: The non-linear sigmoid inside the log-likelihood makes the derivative non-linear in parameters. Numerical optimization (Gradient Descent, Newton-CG, or L-BFGS) is mathematically required.
- The Misconception: "Minimizing Mean Squared Error should work just as well as log loss."
- Wrong Thinking: Combining MSE with sigmoid activations for classification.
- The Right Principle: MSE combined with a sigmoid creates a non-convex cost function full of saddle points and local minima. Furthermore, confident wrong predictions produce tiny gradients (vanishing gradient problem), stopping learning entirely.
- The Misconception: "Computing in Python directly is fine for all model outputs."
- Wrong Thinking: Passing raw floating-point 0.0 or 1.0 to
np.log(). - The Right Principle: If , evaluates to or raises a
ZeroDivisionError/RuntimeWarning. Production implementations must always clamp probabilities using an epsilon ( with ).
- The Misconception: "Logistic regression outputs probabilities, so raw feature scales do not matter."
- Wrong Thinking: Training gradient descent on unscaled features (e.g. Age in vs. Income in ).
- The Right Principle: Unscaled features create distorted, elliptical loss contours, causing gradient descent to oscillate wildly and converge slowly. Always scale features via
StandardScalerinside aPipeline.
- The Misconception: "If classes are perfectly linearly separable, logistic regression achieves 100% accuracy and zero loss."
- Wrong Thinking: Fitting unregularized logistic regression to perfectly separable data.
- The Right Principle: On perfectly separable data, unregularized maximum likelihood drives weights to to force and , causing numerical overflow. Always apply L2 regularization (
Cparameter in scikit-learn).
8. Summary
Theoretical Foundations
- Model Hypothesis: .
- Cost Function: Binary Cross-Entropy .
- Derivation: Derived directly from the log-likelihood of a Bernoulli distribution.
- Convexity: Log loss is strictly convex with respect to linear weights, guaranteeing a single global minimum.
Optimization Realities
- No Closed Form: Requires numerical optimization (Gradient Descent, L-BFGS, Newton-Raphson).
- Gradient Equation: .
- Loss Gradient Advantage: Steep gradients for confident mistakes prevent vanishing gradient stalls.
- Feature Scaling: Standardize features to ensure isotropic circular contours for fast gradient descent.
Key Takeaways
- Log Loss is MLE: Minimizing Binary Cross-Entropy is mathematically equivalent to maximizing the likelihood of observing the training data under a Bernoulli assumption.
- Avoid MSE on Classification: MSE creates non-convex surfaces and vanishes when predictions are confidently incorrect.
- Gradient Descent is Universal: The gradient update formula is shared between Linear and Logistic regression, providing seamless mathematical continuity.
Next Section: Multiclass and Practical Use - extending binary logistic regression to multiclass problems via One-vs-Rest (OvR) and Multinomial Softmax.
9. Active Recall
Test your understanding by answering first, then clicking to reveal the underlying principles.
Interactive Checkpoint Quiz
Interactive Checkpoint: The Vanishing Gradient in MSE
If we train a logistic classifier ŷ = σ(z) using Mean Squared Error loss L = (y - ŷ)², what happens to the gradient when the model makes a confident wrong prediction (e.g. true y = 1 but predicted ŷ ≈ 0.001)?
Review Flashcards
1. [THEORY] Why does minimizing Binary Cross-Entropy guarantee finding the global optimum?
- Convexity: The negative log-likelihood function of logistic regression is strictly convex with respect to the weights and bias .
- Its Hessian matrix (where is a diagonal matrix with entries ) is positive semi-definite everywhere.
- Because there are no local minima or saddle points, gradient descent is mathematically guaranteed to converge to the unique global minimum.
2. [MATH] Why does the sigmoid derivative cancel out when differentiating Binary Cross-Entropy?
- Using the chain rule:
- .
- .
- Multiplying them together cancels the denominator completely, leaving:
- This cancellation eliminates the vanishing gradient problem.
3. [PRACTICE] What happens to logistic regression weights if the training classes are perfectly linearly separable and no regularization is applied?
- Weight Explosion: If classes are perfectly separable, the model can achieve a log loss of zero only if for all positives and for all negatives.
- Because only as and only as , gradient descent continues increasing the magnitude of weights .
- The Remedy: Apply L2 weight regularization (e.g.
C=1.0), which adds penalty to the cost function, preventing weights from growing unbounded.
4. [ANALYZE] If a model predicts probability ŷ = 0.99 for an actual positive sample, what is the log loss? What if ŷ = 0.50?
- For : Loss . The penalty is virtually zero because the model is confident and correct.
- For : Loss . A loss of represents complete uncertainty (random coin flip guessing).
- Baseline Benchmark: Any trained binary classification model that exhibits a mean log loss is performing worse than a trivial coin toss.
5. [PRACTICE] Why are second-order optimization algorithms like L-BFGS or Newton-CG often used instead of basic SGD for small-to-medium logistic regression?
- Curvature Information: Second-order methods utilize the Hessian matrix (curvature of the loss surface).
- Because logistic regression is strictly convex, Newton-Raphson steps jump directly toward the optimum without requiring manual learning rate tuning ().
- For datasets with , L-BFGS converges in iterations, whereas basic SGD may require hundreds of epochs.