Why doesn't MSE work with logistic regression?
Mean Squared Error (MSE) is poorly suited for logistic regression for two fundamental optimization reasons: non-convexity and vanishing gradients. Composing the non-linear sigmoid function with squared error produces a non-convex loss landscape with flat plateaus and local minima, whereas Binary Cross-Entropy (Log Loss) is convex in the weights. Furthermore, MSE's gradient includes the sigmoid derivative y_hat(1 - y_hat), which approaches zero precisely when predictions are confidently wrong, stalling gradient descent.
Study Card: Why Doesn’t MSE Work with Logistic Regression?
Direct Answer
In logistic regression, predictions take the form where and . Using Mean Squared Error (MSE) instead of Binary Cross-Entropy (Log Loss) fails for three concrete mathematical and statistical reasons:
- Non-convexity: The MSE objective composes a bounded, non-convex/non-concave sigmoid with squared error, yielding a non-convex loss surface in with flat saturation plateaus and potential local minima. By contrast, Log Loss:
has positive semi-definite Hessian , guaranteeing convexity and a global optimum (strictly unique with full-rank features or L2 regularization).
- Vanishing gradients and mismatched gradient scaling: Differentiating both per-sample losses with respect to the logit reveals why MSE stalls on bad mistakes:
Under MSE, the sigmoid derivative whenever or . So when the model is confidently wrong ( while ), MSE’s gradient collapses toward right when the error is largest, freezing gradient descent. Under Log Loss, the factor from differentiating and cancels identically, leaving a gradient that scales linearly with the prediction error.
- Probabilistic mismatch: Minimizing MSE corresponds to Maximum Likelihood Estimation (MLE) under Gaussian noise, whereas binary targets yield Binary Cross-Entropy directly as the exact negative log-likelihood.
Key Terms
- Sigmoid Derivative (): Factor multiplying MSE’s gradient that vanishes toward in saturated probability tails near and .
- Log Loss (Binary Cross-Entropy): Convex classification loss derived from Bernoulli MLE whose logit gradient avoids sigmoid saturation.
- Convexity: Guarantee that every local minimum is a global minimum (), ensuring reliable gradient descent convergence.
- Saturation Plateau: Flat region of the loss surface where or and MSE gradients become tiny even for completely wrong classifications.
Example
Compare numerical losses and logit gradients (using natural logarithm ) for a true positive label :
- Near-correct (): , gradient magnitude ; , gradient magnitude .
- Uncertain (): , gradient magnitude ; , gradient magnitude .
- Confidently wrong (): , yet its gradient shrinks to (ten times smaller than at !). Meanwhile, , and its gradient grows cleanly to .
Code Implementation
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(z):
z = np.clip(z, -500, 500)
return 1.0 / (1.0 + np.exp(-z))
# 1. Compare gradient descent from a confidently wrong initialization
rng = np.random.default_rng(42)
X_raw = rng.uniform(-4, 4, size=120)
y = (X_raw > 0.0).astype(float)
X = np.column_stack([np.ones_like(X_raw), X_raw]) # [bias, x]
def run_gd(loss_type, w_init, lr=0.5, steps=200):
w = w_init.copy()
for _ in range(steps):
z = X @ w
p = sigmoid(z)
if loss_type == "mse":
# d/dw [0.5 * mean((p - y)^2)]
grad = (X.T @ ((p - y) * p * (1.0 - p))) / len(y)
else:
# d/dw [mean(-y*log(p) - (1-y)*log(1-p))]
grad = (X.T @ (p - y)) / len(y)
w -= lr * grad
return w
# Confidently wrong start: slope = -3.0 (saturated in wrong direction)
w_start = np.array([0.0, -3.0])
w_mse = run_gd("mse", w_start, lr=0.5, steps=200)
w_bce = run_gd("bce", w_start, lr=0.5, steps=200)
acc_mse = np.mean((sigmoid(X @ w_mse) >= 0.5) == y)
acc_bce = np.mean((sigmoid(X @ w_bce) >= 0.5) == y)
print(f"Start w=[0, -3] -> MSE weights: {np.round(w_mse, 3)}, Train Acc: {acc_mse:.3f}")
print(f"Start w=[0, -3] -> BCE weights: {np.round(w_bce, 3)}, Train Acc: {acc_bce:.3f}")
# 2. Plot single-sample loss and gradient magnitude vs logit z for y = 1
z_grid = np.linspace(-6, 6, 300)
p_grid = sigmoid(z_grid)
mse_single = 0.5 * (p_grid - 1.0) ** 2
bce_single = np.logaddexp(0.0, z_grid) - 1.0 * z_grid # stable -ln(sigmoid(z))
mse_grad_mag = np.abs((p_grid - 1.0) * p_grid * (1.0 - p_grid))
bce_grad_mag = np.abs(p_grid - 1.0)
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
axes[0].plot(z_grid, mse_single, label="MSE Loss (non-convex plateau for z < 0)", lw=2)
axes[0].plot(z_grid, bce_single, label="Log Loss (convex)", lw=2)
axes[0].set_title("Loss vs. Logit z (y = 1)")
axes[0].set_xlabel("Logit z")
axes[0].set_ylabel("Loss")
axes[0].legend()
axes[0].grid(True)
axes[1].plot(z_grid, mse_grad_mag, label="|dL_MSE / dz| (vanishes for z << 0)", lw=2)
axes[1].plot(z_grid, bce_grad_mag, label="|dL_BCE / dz| (grows smoothly to 1)", lw=2)
axes[1].set_title("Gradient Magnitude vs. Logit z (y = 1)")
axes[1].set_xlabel("Logit z")
axes[1].set_ylabel("|Gradient w.r.t. z|")
axes[1].legend()
axes[1].grid(True)
plt.tight_layout()
plt.show()
Related Concepts
- Maximum Likelihood Estimation (MLE): Bernoulli MLE derives Binary Cross-Entropy directly; Gaussian MLE derives MSE.
- Categorical Cross-Entropy (Softmax): Multi-class generalization of Log Loss whose logit gradient exhibits the exact same clean cancellation.
- Brier Score: Evaluates MSE on predicted probabilities at evaluation time (where it is a proper scoring rule for calibration), even though optimizing it directly with gradient descent through a sigmoid suffers from vanishing gradients.
- Generalized Linear Models (GLMs): Matching a canonical link function (logit for Bernoulli) to its exponential-family log-likelihood always produces a convex objective with linear error gradients.