MoonSay /Tutorials/Machine Learning Interview #7
Contents
  1. 01Introduction
  2. 02What a loss function does
  3. 03Squared error
  4. 04Absolute error and Huber loss
  5. 05Cross-entropy
  6. 06Why not squared error for classification?
  7. 07Hinge loss
  8. 08Choosing a loss
  9. 09Interview questions and model answers
  10. 10Summary
  11. References
Loss Functions/Chapter 02 of 10

02What a loss function does

2.1From one prediction to training

A loss function \ell(y,\hat y)\ge0 scores one prediction: zero when it is perfect, larger when it is worse. Training minimizes the empirical risk, the average loss over the training set (Murphy, 2022, §4.3):

\hat\theta=\arg\min_\theta\;\frac1N\sum_{n=1}^N\ell\bigl(y_n,f_\theta(x_n)\bigr). \tag{1}

Gradient descent moves \theta against the gradient of (1). By the chain rule, each example contributes

\frac{\partial\ell}{\partial\theta}=\frac{\partial\ell}{\partial\hat y}\,\frac{\partial\hat y}{\partial\theta},

so the derivative \partial\ell/\partial\hat y is the pull of that example on the model. Two questions tell you almost everything about a loss: how hard does a large mistake pull, and does a correct, confident prediction still pull at all? We will ask both of every loss.

2.2Loss versus metric

The metric is what you report or what the business cares about: accuracy, error rate, mean absolute error in dollars. The loss is what you can optimize. Often they differ. The classification error (the 0-1 loss) is a step function: its gradient is zero almost everywhere, so gradient descent cannot use it, and minimizing it directly is computationally hard (Murphy, 2022, §4.3.2). We therefore train on a smooth or convex surrogate such as cross-entropy or hinge loss and report accuracy. A good surrogate is one whose minimizer also makes the metric good (Section 7).

2.3Where losses come from: negative log-likelihood

Most classic losses are not arbitrary: they are negative log-likelihoods. If the model defines a probability p_\theta(y\mid x) for the target, maximum likelihood is the same as minimizing

\ell(y,x;\theta)=-\log p_\theta(y\mid x). \tag{2}

Choosing a loss is then choosing a noise model: Gaussian noise gives squared error, Laplace noise gives absolute error, a Bernoulli or categorical label gives cross-entropy. We derive each in turn. The exception is the hinge loss, which comes from geometry (the margin) rather than from a probability model.

Pause and think. A model predicts house prices. Your manager judges it by the mean absolute error in dollars. Must you train it with absolute error?

Show the answer

No. The loss and the metric may differ. Training with squared error estimates the mean price, absolute error the median (Section 4); if the errors are roughly symmetric the two are close, and squared error is smoother to optimize. If there are outliers or the price distribution is skewed, training with absolute error or Huber loss will usually give a better mean absolute error.