Skip to content
E
Educatum

Loss function of logistic regression

Curated by Educatum AI teamLast updated:
Model EvaluationLoss
Direct Answer

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 zi=wTxi+bz_i = w^T x_i + b and sigmoid probabilities p^i=σ(zi)\hat{p}_i = \sigma(z_i):

L(w,b)=−1m∑i=1m[yilog⁡(σ(zi))+(1−yi)log⁡(1−σ(zi))]\mathcal{L}(w, b) = -\frac{1}{m} \sum_{i=1}^{m} \Big[ y_i \log(\sigma(z_i)) + (1 - y_i)\log(1 - \sigma(z_i)) \Big]

Minimizing this loss is mathematically identical to Maximum Likelihood Estimation (MLE) assuming yi∣xi∼Bernoulli(p^i)y_i \mid x_i \sim \text{Bernoulli}(\hat{p}_i). 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 (w,b)(w, b) with a clean gradient:

∇wL=1mXT(p^−y)\nabla_w \mathcal{L} = \frac{1}{m} X^T (\hat{p} - y)

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 y∈{0,1}y \in \{0, 1\} and predicted probabilities p^∈(0,1)\hat{p} \in (0, 1).
  • Maximum Likelihood Estimation (MLE): Finds (w,b)(w, b) 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 ∇wL\nabla_w \mathcal{L} and ∂L∂b=1m∑i(p^i−yi)\frac{\partial \mathcal{L}}{\partial b} = \frac{1}{m}\sum_i (\hat{p}_i - y_i).
  • Sigmoid Function: σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}}, 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 −ln⁡(0.9)≈0.105-\ln(0.9) \approx 0.105; if it outputs 0.1, the loss spikes to −ln⁡(0.1)≈2.303-\ln(0.1) \approx 2.303, producing a strong gradient (p^−y)=−0.9(\hat{p} - y) = -0.9 to correct the weights. By contrast, under MSE 12(σ(z)−y)2\frac{1}{2}(\sigma(z) - y)^2, an extremely wrong prediction with σ(z)≈0\sigma(z) \approx 0 multiplies the error by σ′(z)=σ(z)(1−σ(z))≈0\sigma'(z) = \sigma(z)(1 - \sigma(z)) \approx 0, 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()
  • Regularization: Adding λ2∥w∥22\frac{\lambda}{2}\|w\|_2^2 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 −1m∑i∑kyiklog⁡(softmax(zi)k)-\frac{1}{m}\sum_i \sum_k y_{ik} \log(\text{softmax}(z_i)_k) for K>2K > 2 classes.
  • Alternative Loss Functions: Contrast with hinge loss (SVMs), which yields sparse support vectors and focuses on margin violations rather than calibrated probabilities.
View all →

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