Binary Classification Loss: Derivation and Gradient Computation
Machine LearningModel answerLast updated
Derive the cross-entropy objective for binary logistic regression from first principles and compute its gradients with respect to parameters.
You are training a binary classifier using logistic regression on a dataset of m examples ${(x_i, y_i)}_{i=1}^m$ where each $x_i \in \mathbb{R}^d$ is a feature vector and $y_i \in {0, 1}$ is the binary label.
The model predicts probabilities using:
- Score: $s_i = w^T x_i + b$ where $w \in \mathbb{R}^d$ and $b \in \mathbb{R}$
- Sigmoid activation: $\sigma(s) = \frac{1}{1 + e^{-s}}$
- Predicted probability: $\hat{p}_i = \sigma(s_i)$
Answer the following:
Part A: Starting from the assumption that labels are independent Bernoulli random variables, derive the maximum likelihood estimation problem. Express it both as a maximization and as a minimization problem. Then write the same problem when L2 regularization with coefficient $\lambda \geq 0$ is added.
Part B: Write out the full cross-entropy loss function $\mathcal{L}(w, b)$ that you would minimize (the negative log-likelihood).
Part C: Compute the partial derivatives $\frac{\partial \mathcal{L}}{\partial w}$ and $\frac{\partial \mathcal{L}}{\partial b}$. Show your work using the chain rule.
Part D: Explain the relationship between the terms "loss function," "objective function," and "regularized objective" in this setting. Which one corresponds to maximum likelihood estimation?
Hints
Hint 1
Start by writing the likelihood of a single Bernoulli observation, then take the product over all examples
Hint 2
The derivative of the sigmoid function has a particularly clean form: σ'(s) = σ(s)(1 - σ(s))
Hint 3
The gradient with respect to the score will have the form (prediction - label); use the chain rule to propagate this to w and b
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Part A: Maximum Likelihood Formulation
Probabilistic model:
Each label is a Bernoulli random variable with success probability determined by the sigmoid:
$$P(y_i = 1 \mid x_i; w, b) = \sigma(w^T x_i + b) = \hat{p}_i$$
For a single observation, the probability of the observed label is:
$$P(y_i \mid x_i) = \hat{p}_i^{y_i} (1 - \hat{p}_i)^{1 - y_i}$$
Assuming independence, the likelihood over all m examples is:
$$\mathcal{L}(w, b) = \prod_{i=1}^m \hat{p}_i^{y_i} (1 - \hat{p}_i)^{1 - y_i}$$
Taking the logarithm (which preserves the location of the maximum):
$$\log \mathcal{L}(w, b) = \sum_{i=1}^m \left[ y_i \log \hat{p}_i + (1 - y_i) \log(1 - \hat{p}_i) \right]$$
Maximum likelihood estimation (maximization form):
$$\max_{w, b} \sum_{i=1}^m \left[ y_i \log \sigma(s_i) + (1 - y_i) \log(1 - \sigma(s_i)) \right]$$
Equivalent minimization form:
Since optimizers typically minimize, we minimize the negative log-likelihood (cross-entropy):
$$\min_{w, b} \mathcal{L}(w, b) = -\sum_{i=1}^m \left[ y_i \log \hat{p}_i + (1 - y_i) \log(1 - \hat{p}_i) \right]$$
With L2 regularization:
Adding a penalty on the squared norm of $w$ (but not on $b$, since penalizing the bias would make the model depend on arbitrary feature scaling):
$$\min_{w, b} J(w, b) = \mathcal{L}(w, b) + \frac{\lambda}{2} |w|_2^2$$
This corresponds to maximum a posteriori (MAP) estimation with a Gaussian prior $w \sim \mathcal{N}(0, \lambda^{-1} I)$.
Part B: Explicit Cross-Entropy Loss
The loss function to minimize is:
$$\mathcal{L}(w, b) = -\sum_{i=1}^m \left[ y_i \log \sigma(s_i) + (1 - y_i) \log(1 - \sigma(s_i)) \right]$$
where $s_i = w^T x_i + b$.
Alternative stable form:
Using the identities $\log \sigma(s) = -\log(1 + e^{-s})$ and $\log(1 - \sigma(s)) = -s - \log(1 + e^{-s})$, this simplifies to:
$$\mathcal{L}(w, b) = \sum_{i=1}^m \left[ \log(1 + e^{s_i}) - y_i s_i \right]$$
This form is numerically stable and makes the convexity of the problem apparent.
Part C: Gradient Derivation
Step 1: Derivative of the sigmoid
$$\frac{d\sigma}{ds} = \frac{e^{-s}}{(1 + e^{-s})^2} = \sigma(s)(1 - \sigma(s))$$
Step 2: Gradient with respect to the score
For a single example, the loss contribution is:
$$\ell_i = -\left[ y_i \log \hat{p}_i + (1 - y_i) \log(1 - \hat{p}_i) \right]$$
Taking the derivative with respect to $s_i$:
$$\frac{\partial \ell_i}{\partial s_i} = -\left[ \frac{y_i}{\hat{p}_i} - \frac{1 - y_i}{1 - \hat{p}_i} \right] \cdot \hat{p}_i(1 - \hat{p}_i)$$
Simplifying:
$$= -\left[ y_i(1 - \hat{p}_i) - (1 - y_i)\hat{p}_i \right] = \hat{p}_i - y_i$$
This is the key result: the gradient at each example is simply the prediction error.
Step 3: Chain rule to parameters
Since $\frac{\partial s_i}{\partial w} = x_i$ and $\frac{\partial s_i}{\partial b} = 1$:
$$\boxed{\frac{\partial \mathcal{L}}{\partial w} = \sum_{i=1}^m (\hat{p}_i - y_i) x_i = X^T(\hat{p} - y)}$$
$$\boxed{\frac{\partial \mathcal{L}}{\partial b} = \sum_{i=1}^m (\hat{p}_i - y_i)}$$
where $X \in \mathbb{R}^{m \times d}$ has rows $x_i^T$ and $\hat{p}, y \in \mathbb{R}^m$ are the prediction and label vectors.
With regularization:
$$\frac{\partial J}{\partial w} = X^T(\hat{p} - y) + \lambda w, \quad \frac{\partial J}{\partial b} = \sum_{i=1}^m (\hat{p}_i - y_i)$$
Note that the bias gradient remains unchanged.
Part D: Terminology
Loss function: The per-example cost, here the binary cross-entropy $\ell(y, \hat{p}) = -[y \log \hat{p} + (1-y) \log(1-\hat{p})]$. Measures prediction quality on a single data point.
Objective function: The full function being optimized. For pure MLE this is the negative log-likelihood $\mathcal{L}(w,b) = \sum_i \ell_i$, which aggregates loss over the dataset.
Regularized objective: The objective plus a complexity penalty: $J(w,b) = \mathcal{L}(w,b) + \frac{\lambda}{2}|w|^2$. This is no longer the MLE; it's a MAP estimate that trades off data fit against model simplicity.
Key distinction: Only the unregularized $\mathcal{L}$ corresponds to maximum likelihood. The regularized $J$ incorporates a prior belief about parameter magnitudes. When evaluating on held-out data, report the unregularized loss, not $J$.
Implementation Notes
import numpy as np
def sigmoid(s):
return 1.0 / (1.0 + np.exp(-np.clip(s, -500, 500)))
def loss_and_gradients(w, b, X, y, lam=0.0):
"""Compute loss and gradients for logistic regression."""
m = X.shape[0]
s = X @ w + b
p_hat = sigmoid(s)
# Numerically stable loss
loss = np.sum(np.logaddexp(0, s) - y * s) + 0.5 * lam * (w @ w)
# Gradients
residual = p_hat - y
grad_w = X.T @ residual + lam * w
grad_b = np.sum(residual)
return loss, grad_w, grad_b
Common pitfalls:
- Confusing ascent vs. descent: the log-likelihood gradient is $X^T(y - \hat{p})$ for maximization; we derived $X^T(\hat{p} - y)$ for minimization of the negative log-likelihood
- Regularizing the bias term (incorrect; makes predictions depend on feature origins)
- Numerical overflow when computing $\sigma(s)$ for large $|s|$; use
logaddexpor clipping - Calling the regularized solution "the MLE" (it's MAP, not MLE)