Skip to content
E
Educatum

Why doesn't MSE work with logistic regression?

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

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 y^=σ(z)=11+e−z\hat{y} = \sigma(z) = \frac{1}{1 + e^{-z}} where z=w⊤x+bz = \mathbf{w}^\top \mathbf{x} + b and y∈{0,1}y \in \{0, 1\}. Using Mean Squared Error (MSE) instead of Binary Cross-Entropy (Log Loss) fails for three concrete mathematical and statistical reasons:

  1. Non-convexity: The MSE objective LMSE(w,b)=12N∑i=1N(σ(w⊤xi+b)−yi)2\mathcal{L}_{\text{MSE}}(\mathbf{w}, b) = \frac{1}{2N}\sum_{i=1}^N (\sigma(\mathbf{w}^\top \mathbf{x}_i + b) - y_i)^2 composes a bounded, non-convex/non-concave sigmoid with squared error, yielding a non-convex loss surface in (w,b)(\mathbf{w}, b) with flat saturation plateaus and potential local minima. By contrast, Log Loss:
LBCE(w,b)=−1N∑i=1N[yiln⁡y^i+(1−yi)ln⁡(1−y^i)]\mathcal{L}_{\text{BCE}}(\mathbf{w}, b) = -\frac{1}{N}\sum_{i=1}^{N}\left[y_i \ln \hat{y}_i + (1 - y_i)\ln(1 - \hat{y}_i)\right]

has positive semi-definite Hessian ∇w2LBCE=1NX⊤diag⁡(y^i(1−y^i))X⪰0\nabla^2_{\mathbf{w}} \mathcal{L}_{\text{BCE}} = \frac{1}{N} X^\top \operatorname{diag}(\hat{y}_i(1-\hat{y}_i)) X \succeq 0, guaranteeing convexity and a global optimum (strictly unique with full-rank features or L2 regularization).

  1. Vanishing gradients and mismatched gradient scaling: Differentiating both per-sample losses with respect to the logit zz reveals why MSE stalls on bad mistakes:
∂ℓMSE∂z=(y^−y) σ′(z)=(y^−y) y^(1−y^)vs.∂ℓBCE∂z=y^−y\frac{\partial \ell_{\text{MSE}}}{\partial z} = (\hat{y} - y)\,\sigma'(z) = (\hat{y} - y)\,\hat{y}(1 - \hat{y}) \qquad \text{vs.} \qquad \frac{\partial \ell_{\text{BCE}}}{\partial z} = \hat{y} - y

Under MSE, the sigmoid derivative y^(1−y^)→0\hat{y}(1-\hat{y}) \to 0 whenever y^→0\hat{y} \to 0 or y^→1\hat{y} \to 1. So when the model is confidently wrong (y=1y=1 while y^≈0.001\hat{y} \approx 0.001), MSE’s gradient collapses toward 00 right when the error is largest, freezing gradient descent. Under Log Loss, the 1y^(1−y^)\frac{1}{\hat{y}(1-\hat{y})} factor from differentiating ln⁡y^\ln \hat{y} and ln⁡(1−y^)\ln(1-\hat{y}) cancels σ′(z)\sigma'(z) identically, leaving a gradient y^−y\hat{y} - y that scales linearly with the prediction error.

  1. Probabilistic mismatch: Minimizing MSE corresponds to Maximum Likelihood Estimation (MLE) under Gaussian noise, whereas binary targets Y∣X∼Bernoulli(σ(z))Y \mid X \sim \text{Bernoulli}(\sigma(z)) yield Binary Cross-Entropy directly as the exact negative log-likelihood.

Key Terms

  • Sigmoid Derivative (σ′(z)=y^(1−y^)\sigma'(z) = \hat{y}(1-\hat{y})): Factor multiplying MSE’s gradient that vanishes toward 00 in saturated probability tails near 00 and 11.
  • Log Loss (Binary Cross-Entropy): Convex classification loss derived from Bernoulli MLE whose logit gradient y^−y\hat{y} - y avoids sigmoid saturation.
  • Convexity: Guarantee that every local minimum is a global minimum (H⪰0H \succeq 0), ensuring reliable gradient descent convergence.
  • Saturation Plateau: Flat region of the loss surface where y^≈0\hat{y} \approx 0 or 11 and MSE gradients become tiny even for completely wrong classifications.

Example

Compare numerical losses and logit gradients (using natural logarithm ln⁡\ln) for a true positive label y=1y = 1:

  • Near-correct (y^=0.95\hat{y} = 0.95): ℓMSE=12(0.95−1)2=0.00125\ell_{\text{MSE}} = \frac{1}{2}(0.95 - 1)^2 = 0.00125, gradient magnitude ∣−0.05×0.95×0.05∣≈0.0024|{-0.05}\times 0.95 \times 0.05| \approx 0.0024; ℓBCE=−ln⁡(0.95)≈0.0513\ell_{\text{BCE}} = -\ln(0.95) \approx 0.0513, gradient magnitude 0.050.05.
  • Uncertain (y^=0.60\hat{y} = 0.60): ℓMSE=12(0.60−1)2=0.08\ell_{\text{MSE}} = \frac{1}{2}(0.60 - 1)^2 = 0.08, gradient magnitude ∣−0.40×0.60×0.40∣=0.096|{-0.40}\times 0.60 \times 0.40| = 0.096; ℓBCE=−ln⁡(0.60)≈0.5108\ell_{\text{BCE}} = -\ln(0.60) \approx 0.5108, gradient magnitude 0.400.40.
  • Confidently wrong (y^=0.01\hat{y} = 0.01): ℓMSE=12(0.01−1)2=0.49005\ell_{\text{MSE}} = \frac{1}{2}(0.01 - 1)^2 = 0.49005, yet its gradient shrinks to ∣−0.99×0.01×0.99∣≈0.0098|{-0.99} \times 0.01 \times 0.99| \approx \mathbf{0.0098} (ten times smaller than at y^=0.60\hat{y}=0.60!). Meanwhile, ℓBCE=−ln⁡(0.01)≈4.605\ell_{\text{BCE}} = -\ln(0.01) \approx 4.605, and its gradient grows cleanly to 0.99\mathbf{0.99}.

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()
  • 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 p−y\mathbf{p} - \mathbf{y} 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.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.