LearnQuestion bank

Derive binary cross-entropy from a Bernoulli likelihood and the gradient of logistic regression. Why is MSE a poor loss for classification?

ML engineeringTechnicalEasy

Theme reported publicly: Deliveroo

Answer it yourself first, out loud or on paper, then compare.

Answer

Model answer, written in a candidate's voice

In short

  • Bernoulli likelihood p(y|x)=p^y(1-p)^(1-y) gives NLL −[y log p + (1−y) log(1−p)].
  • With p=σ(z), z=wᵀx+b, dσ/dz=σ(1−σ), so mean-NLL gradient is Xᵀ(p−y)/n.
  • MSE on sigmoid outputs is non-convex in w and its gradient carries a p(1−p) factor, vanishing when confidently wrong.
  • Use logits and stable log-sum-exp/softplus forms to avoid log(0) and overflow.

In full

For a Bernoulli outcome, p(y|x)=p^y(1-p)^(1-y), so the negative log-likelihood is −[y log p + (1−y) log(1−p)]. With p=σ(z), z=wᵀx+b, and dσ/dz=σ(1−σ), the mean loss gradient is Xᵀ(p−y)/n (bias gradient is the mean of p−y). MSE on sigmoid outputs is poor because it is a quadratic in p but a non-convex function of w, and its gradient is scaled by p(1−p), so when the model is confidently wrong (p near 0 for y=1 or near 1 for y=0) the signal collapses. Binary cross-entropy is convex in w for a linear model and keeps a useful gradient, roughly (p−y), even in those cases. In practice I compute everything from logits with stable log-sum-exp/softplus forms, e.g. log σ(z)=−softplus(−z) and log(1−σ(z))=−softplus(z), rather than forming p and then taking logs.

Checked against sources by an independent AI reviewer.

What a strong answer covers

  • Negative log-likelihood of a Bernoulli gives −[y log p + (1−y) log(1−p)].
  • With p = σ(wᵀx + b), the gradient is Xᵀ(p − y)/n.
  • MSE with a sigmoid is non-convex in w and gives vanishing gradients when the model is confidently wrong.
  • Mentions numerical stability (log-sum-exp, logits form).

Common mistakes

  • sign errors in the gradient
  • computing log(sigmoid) naively and getting −inf.