KatInterview

Binary Classification Loss: Derivation and Gradient Computation

Machine LearningModel answer
MediumModel answerMachine Learninglogistic-regressionmaximum-likelihoodgradients

Last 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