Loss functions and gradient descent
How models learn: a loss to minimise and steps downhill.
Lesson 22 of 6614 minIntermediate
You will learn to
- Define squared, absolute and log loss
- Explain gradient descent and the learning rate
- Relate loss to metric
Before this lesson
Intuition
To learn, a model needs a way to know how wrong it is. That is the job of the loss function: a number that is small when the predictions are good and large when they are bad. Training is the search for the parameters that make the total loss over the training rows as small as possible.
Picture yourself on a foggy hillside, trying to get to the lowest point. You cannot see the valley, but you can feel the slope under your feet. A sensible strategy is to take a step in the direction that goes downhill most steeply, then feel the slope again and repeat. This is gradient descent. The slope is the gradient, and the size of each step is the learning rate.
- A step that is too small gets you there, but very slowly.
- A step that is too large can carry you over the valley and up the other side.
- A well-chosen step gets you to the bottom in a few moves.
The choice of loss defines what "wrong" means. Different losses make different trade-offs, and the loss used for training is often not the metric you report at the end.
Picture it
The bowl is the loss as a function of one parameter, . The bottom is the best value. The three panels use the same model and data and differ only in the learning rate.
The math
Losses for a number. For one row with actual value and prediction :
Squared loss punishes big errors heavily and has a smooth bowl shape, which is easy to optimise. Absolute loss treats all errors in proportion and is less sensitive to outliers. Averaging the squared loss over the rows gives the mean squared error (MSE).
Loss for a probability. For a binary target and a predicted probability of class 1, the log loss (also called cross-entropy) is
When the true class is 1 the loss is : small when p is near 1, and growing without limit when p approaches 0. So a model that is confidently wrong is punished heavily.
Gradient descent. With parameters , total loss and learning rate , each step is
The partial derivative is the slope of the loss with respect to that parameter. With many parameters the same rule applies to each of them at once.
Loss and metric. A metric is what you report (accuracy, RMSE, F1). A loss is what you optimise. They are often different because accuracy cannot be used for descent: it changes in jumps, so it has no useful slope. Log loss is smooth, so it is used to train, and accuracy is used to report. A good loss is a smooth stand-in for the metric you really care about.
Worked example
One parameter, three rows: and , with the model . The true relation is , so the best parameter is .
The mean squared error as a function of works out to . At the start, , the loss is 14/3 × 4 = 18.67. The gradient is , which is -18.67 at : negative, so the loss falls if we increase .
Each step multiplies the distance to the optimum, , by . These are the values of after each step, starting at 0:
| Learning rate | Factor | Step 1 | Step 2 | Step 3 | Step 4 | Step 5 |
|---|---|---|---|---|---|---|
| 0.05 | 0.533 | 0.933 | 1.431 | 1.697 | 1.838 | 1.914 |
| 0.10 | 0.067 | 1.867 | 1.991 | 1.999 | 2.000 | 2.000 |
| 0.25 | -1.333 | 4.667 | -1.556 | 6.741 | -4.321 | 10.428 |
- With 0.05 the distance to the optimum shrinks by almost half each step: correct, but still 0.09 away after five steps.
- With 0.10 the factor is small, so the parameter reaches 2 within four steps.
- With 0.25 the factor has absolute value above 1, so every step lands further away than the one before and the loss grows. Descent converges only when the factor lies between -1 and 1, here when .
Outliers. The errors 1, 1, 1 and 10 give MSE = (1 + 1 + 1 + 100) / 4 = 25.75 and MAE = 13 / 4 = 3.25. The error of 10 is 77% of the absolute total but 97% of the squared total, which is why a model trained with squared loss bends towards outliers.
Log loss. A true positive predicted at p = 0.9 costs -ln(0.9) = 0.105. Predicted at p = 0.1 it costs -ln(0.1) = 2.303, more than twenty times as much. At p = 0.5 it costs 0.693.
How mlflow does it
You do not write the loss or the descent yourself; each algorithm brings its own. What you can see and set are the hyperparameters of the algorithms. Models trained by gradient steps, such as gradient boosting, XGBoost, LightGBM and the neural network, have a learning_rate hyperparameter, and some have a loss choice. On a run's model card, the section Estimator hyperparameters shows the values a candidate used. A smaller learning rate usually needs more iterations or trees to reach the same fit. The hyperparameters reference explains how to change them.
Common mistakes
- Optimising one thing and reporting another without checking. A model with the best log loss can have a slightly different best threshold or accuracy. Evaluate with the metric your decision needs.
- Choosing squared loss when the data has outliers you do not trust. One bad row can dominate. Check the largest errors, clean the data or use a more robust loss.
- Setting the learning rate by feel. If the loss goes up or oscillates, reduce it. If it barely moves, increase it or train for more steps.
- Believing a lower training loss means a better model. Training loss keeps falling as the model becomes more flexible. Compare models on validation data (see overfitting and bias-variance).
- Forgetting that features on very different scales slow descent down. The bowl becomes a long narrow valley and the steps zigzag. Scale the features first.
Try it in mlflow
Look at a model's parameters
- Open Runs and open a finished run.
- On the Leaderboard tab, open one of the model candidates to see its Model card.
- Read the Estimator hyperparameters. For a gradient boosting or neural network model, find learning_rate (or learning_rate_init).
- Train again with a different learning rate in Manual mode and compare the two scores.