Loss function of logistic regression
Logistic regression uses binary cross-entropy (log loss) rather than mean squared error. Derived directly from Maximum Likelihood Estimation under a Bernoulli likelihood, binary cross-entropy is convex with respect to the model weights and bias, ensuring gradient-based optimizers avoid spurious local minima.
Study Card: Loss Function of Logistic Regression
Direct Answer
Logistic regression minimizes the binary cross-entropy (log loss) objective over logits and sigmoid probabilities :
Minimizing this loss is mathematically identical to Maximum Likelihood Estimation (MLE) assuming . Unlike Mean Squared Error applied to a sigmoid output—which creates a non-convex loss surface with flat saturated gradients—binary cross-entropy is convex in with a clean gradient:
making optimization via gradient descent or quasi-Newton methods (like L-BFGS) reliable.
Key Terms
- Log Loss (Binary Cross-Entropy): Measures dissimilarity between true binary labels and predicted probabilities .
- Maximum Likelihood Estimation (MLE): Finds maximizing the data likelihood; taking the negative average log-likelihood yields binary cross-entropy.
- Convex Function: A function in which any local minimum is a global minimum. With L2 regularization (or full-rank features without perfect separation), logistic loss is strictly convex and has a unique global minimum.
- Gradient Descent: First-order iterative optimization using and .
- Sigmoid Function: , transforming linear scores into probabilities.
Example
Consider predicting ad clicks (1 for click, 0 for no click). If a user clicks (1) and the model outputs 0.9, the loss is ; if it outputs 0.1, the loss spikes to , producing a strong gradient to correct the weights. By contrast, under MSE , an extremely wrong prediction with multiplies the error by , stalling learning due to vanishing sigmoid gradients.
Code Implementation
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(z):
"""Numerically stable sigmoid function."""
z = np.asarray(z, dtype=float)
return 1.0 / (1.0 + np.exp(-np.clip(z, -500, 500)))
def log_loss(y_true, y_pred):
"""
Calculates binary cross-entropy / log loss.
Clips probabilities with epsilon to avoid log(0).
"""
epsilon = 1e-15
y_pred = np.clip(y_pred, epsilon, 1 - epsilon)
return -np.mean(y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred))
# Example usage from linear logits -> probabilities -> log loss
y_true = np.array([0, 1, 1, 0, 1])
logits = np.array([-2.2, 2.2, 1.4, -1.4, 0.85])
y_pred_prob = sigmoid(logits)
loss = log_loss(y_true, y_pred_prob)
print(f"Log Loss: {loss:.4f}")
# Visualizing Log Loss vs predicted probability for y_true=1 and y_true=0
p_grid = np.linspace(0.001, 0.999, 100)
plt.figure(figsize=(8, 5))
plt.plot(p_grid, -np.log(p_grid), label='y_true = 1: -log(p)')
plt.plot(p_grid, -np.log(1 - p_grid), label='y_true = 0: -log(1 - p)')
plt.xlabel("Predicted Probability (p)")
plt.ylabel("Log Loss")
plt.title("Log Loss vs Predicted Probability")
plt.legend()
plt.grid(True)
plt.show()
Related Concepts
- Regularization: Adding makes the loss strictly convex even when features are collinear or data is linearly separable (preventing weights from growing toward infinity).
- Optimization Algorithms: Gradient descent, SGD, Newton-Raphson / Iteratively Reweighted Least Squares (IRLS), and L-BFGS can all minimize log loss efficiently.
- Multi-class Classification: Generalizes to categorical cross-entropy for classes.
- Alternative Loss Functions: Contrast with hinge loss (SVMs), which yields sparse support vectors and focuses on margin violations rather than calibrated probabilities.