Contents
Loss FunctionsMean Squared Error, Cross-Entropy, Hinge
Squared error, absolute error, cross-entropy and hinge: what each one punishes, and why
A tutorial companion to the video Machine Learning Interview #7: Loss Functions (Mean Squared Error, Cross-Entropy, Hinge) PDF
01Introduction
1.1The question
“Which loss function would you use, and why?” comes up in almost every machine learning interview. Think of a loss as a teacher’s grading rule. One teacher takes off points in proportion to how far off an answer is; another takes off the square of the distance, so one wild answer costs more than many small slips; a third only asks whether the answer is right and how confident the student was. The same student, trained by each teacher, learns different habits. A model is that student: it does whatever makes its loss small. This tutorial explains what each classic loss rewards and punishes, where it comes from, and when to use it.
1.2Prerequisites and notation
Prerequisites. Derivatives and the chain rule, basic probability (the normal and Bernoulli distributions), and maximum likelihood (covered in the tutorial of episode 5).
Notation. The training data are pairs (x_n,y_n), n=1,\dots,N. A model with parameters \theta predicts \hat y_n=f_\theta(x_n). For regression, r_n=y_n-\hat y_n is the residual (the error). For classification the model outputs real-valued logits (scores) z, turned into probabilities by the sigmoid \sigma(z)=1/(1+e^{-z}) or the softmax; y is then a label in \{0,1\} or a one-hot vector. For the margin view of Section 7 we write the label as \tilde y\in\{-1,+1\}. \log is the natural logarithm.
1.3A short history
Legendre (1805) published the method of least squares to fit the orbits of comets, and Gauss (1809) justified it: least squares gives the most probable answer when measurement errors follow what we now call the normal (Gaussian) distribution. For more than a century squared error was the loss. Huber (1964) asked what happens when a few measurements are gross errors and proposed a loss that is quadratic for small errors and linear for large ones, the start of robust statistics. On the classification side, Shannon (1948) defined entropy, the quantity behind cross-entropy; Brier (1950) proposed scoring weather forecasters’ probabilities with a squared error, and Good (1952) proposed the logarithmic score, which is the log loss. Cortes and Vapnik (1995) built the soft-margin support vector machine on the hinge loss. Neural networks of the 1980s and 1990s were mostly trained with mean squared error; switching to cross-entropy greatly improved networks with sigmoid and softmax outputs (Goodfellow et al., 2016, §6.6). Today’s large language models are trained with cross-entropy on the next word (Radford et al., 2018).