The Cost of Deviations
L2, L1 and Huber
In this post
- Nine measurements and one typo
- Turning a question into an optimisation problem
- Three examples, same recipe
- Slopes, and walking downhill
- Two ways to penalise a deviation
- Deviations pull: the force picture
- Now let’s fit a line
- One more: who grabs the line?
- Rare event or broken data?
- Huber: trust small deviations, distrust large ones
- Choosing a rule on purpose
In Scoring Regressions we scored a model that was already fitted: MAE and RMSE told us how its errors looked. But where did that fitted model come from in the first place? Somebody had to choose it, and that choice is made by an optimiser chasing an objective function.
So today, let’s try to understand how to fit a model. Spoiler: the way you decide to grade (or weigh) each deviation quietly decides which answer you get (and which data points get a say).
Nine measurements and one typo
Let’s start with an example. Nine friends each measure the length of the same table and write down their result, in metres:
\[1,\ 2,\ 3,\ 3.5,\ 3.5,\ 4,\ 4,\ 4,\ 1000\]The last one is obviously wrong. Somebody probably meant to type “1.000”, or “10”. Still, the question stands: if you had to report one number for the table’s length, what would it be?
One could report the table’s length in three ways: the mean, the median or the mode. All three try to represent the size of the same table in the best possible way, but each in its own way, and each makes its own assumptions:
Every answer is a belief
- Mean (≈ 113.9): you choose to believe 1000 was a correctly taken, correctly written measurement.
- Median (3.5): you choose to believe it’s okay to ignore the extremes, since the data might have been contaminated along the way.
- Mode (4): you choose to believe the value the majority agrees on.
These aren’t arbitrary recipes then. Rather, each is the best possible answer under a different rule and different assumptions about the given data points. We just took a glimpse of these rules. Now let’s see them in detail, predict how they’ll behave in situations more complex than this really simple one, and learn how to choose between them on purpose.
Turning a question into an optimisation problem
Before we dive into the rules, let’s first understand how asking “what represents my data best?” gets translated into an optimisation problem. Mathematically it means: assign a number (a score) to every candidate answer, based on how far it deviates from the data, then put all effort into making that number as small as possible. The candidate with the smallest score is the one that represents the data best; finding it is the optimisation. It boils down to five ingredients. Every time you encounter something to optimise, ask the five questions below. Let’s go back to our previous example, the table and the nine friends’ measurements, and answer each one for it:
| Ingredient | The question to ask | In the table example |
|---|---|---|
| Data | What is fixed / given to me? | \(y_1, \dots, y_9 = 1, 2, \dots, 1000\) |
| Decision variable | What am I free to choose? | the number \(c\) |
| Model | What relates my decision variable to what I know? This can be looked at as my prediction model. | “the length is some number \(c\)”, so my prediction is \(\hat y = c\) |
| Residual | How far does each data point deviate from my prediction? | \(r_i = y_i - \hat y = y_i - c\) |
| Objective (cost) | How do I score my residuals? How do I weigh different residuals? | \(J(c) = \sum_i \rho(r_i)\) |
The word residual itself means what is remaining: the part of each data point that my prediction couldn’t explain. It’s the deviation between each data point and the model’s prediction: \(r_i = y_i - \hat y_i\), the data point minus the model’s prediction.
The rule \(\rho(r)\) that turns one residual into a cost is the loss. That cost is my grade for that data point: a penalty, based on how far the prediction from my decision variable deviates from the observed data point. \(\rho\) could be the L2 loss, squaring the residual, or the L1 loss, taking its absolute value (much more on both soon). Added up over all the data points, they give \(J = \lVert r \rVert_2^2\) and \(J = \lVert r \rVert_1\): the norms belong to the whole objective \(J\), while \(\rho\) is its piece for a single point.
Why “loss”? A loss function isn’t something special to fitting models. It’s a general idea. In Wikipedia’s words, “a loss function or cost function (sometimes also called an error function) is a function that maps an event or values of one or more variables onto a real number intuitively representing some ‘cost’ associated with the event.” You can see it as a penalty function: it determines how you weigh each residual, and how much you penalise it. Its output measures how much the model is losing, how far it falls short of the ideal.
The objective adds up the losses, and optimisation means finding the decision variable that makes the objective as small as possible: its minimum. Sometimes we want to make something as large as possible instead, like profit or value. That’s fine too: every maximisation problem can be converted into a minimisation problem, and vice versa, because maximising \(f\) is the same as minimising, for example, \(-f\) (or \(1/f\), as long as \(f\) stays positive).
Just a little thought: these questions aren’t only for maths. What is given to me? What is my situation? What am I free to choose? Asking that, instead of just complaining about the situation, is itself an optimisation problem. (But it’s so difficult to apply in life!)
The anatomy, in general. In its simplest form, an optimisation problem minimises (or maximises) an objective \(f(\mathbf{x})\) over decision variables \(\mathbf{x} \in \mathbb{R}^n\). Real problems often come with rules the answer must obey, written as inequalities or equalities:
Unconstrained
\[\min_{\mathbf{x}}\ f(\mathbf{x})\]\(\mathbf{x}\) may take any value; nothing restricts the answer.
Constrained (standard form)
\[\begin{aligned} \min_{\mathbf{x}}\ \ & f(\mathbf{x})\\ \text{subject to}\ \ & g_i(\mathbf{x}) \le 0,\quad i = 1, \dots, m\\ & h_j(\mathbf{x}) = 0,\quad j = 1, \dots, p \end{aligned}\]Three examples, same recipe
1. The table, from earlier
Data: 9 measurements \(y_i\)
Decision variable: \(c\), our reported length
Model: \(\hat y = c\)
Residual: \(r_i(c) = y_i - c\)
Objective:
\(\rho\) could be the squared (L2) loss \(\rho(r) = r^2\), the absolute (L1) loss \(\rho(r) = \lvert r \rvert\), …
2. Fitting a line
Data: points \((x_i, y_i)\): \((0,0), (1,1), (2,2), (1,2)\)
Decision variables: slope \(m\), intercept \(c\)
Model: \(\hat y_i = m x_i + c\)
Residual: \(r_i = y_i - (m x_i + c)\)
Objective (say, using the squared loss function):
3. The knapsack problem
There are \(n\) distinct items and a knapsack of capacity \(W\). Select a subset of items so that the total weight doesn’t exceed \(W\) and the total value is as large as possible.
Data: each item’s weight \(w_i\) and value \(v_i\); the capacity \(W\)
Decision variables: a yes/no \(y_i \in \{0, 1\}\) for each item (1 = it goes in the bag)
Model: total weight \(\sum_i w_i\, y_i\), total value \(\sum_i v_i\, y_i\)
Residual: none here! There’s no measurement to match, so we grade the choice directly.
Objective:
A different flavour: a max, a constraint, and decision variables that can only be 0 or 1, so there are no slopes to walk down. But the same five questions got us here!
Slopes, and walking downhill
Let’s open up the objective for our table, using the squared loss \(\rho(r) = r^2\), and simplify it:
\[J(c) = \sum_{i=1}^{9} (y_i - c)^2 = \sum_{i=1}^{9} \big(y_i^2 - 2\,y_i\,c + c^2\big) = \underbrace{\textstyle\sum_i y_i^2}_{1{,}000{,}086.5} \;-\; 2c\underbrace{\textstyle\sum_i y_i}_{1025} \;+\; 9c^2 .\](Check: \(1+2+3+3.5+3.5+4+4+4+1000 = 1025\), and the squares add to \(1+4+9+12.25+12.25+16+16+16+1{,}000{,}000\).) So
\[\boxed{J(c) = 9c^2 - 2050\,c + 1{,}000{,}086.5}\]That’s a quadratic in \(c\), and the number in front of \(c^2\) is positive, so it’s a parabola that opens upward: a bowl. Let’s plot it against every candidate \(c\):
The best answer sits at its lowest point. How do you find it? There are two ways.
By hand, with basic calculus. At the bottom of a smooth curve the slope is zero, so compute the derivative \(J'\), set it equal to 0, and check that the second derivative \(J''\) is positive, which means the curve is bending upward there (a bottom, not a top):
\[J'(c) = 18c - 2050 = 0 \ \Rightarrow\ c = \frac{2050}{18} = \frac{1025}{9} \approx 113.9, \qquad\qquad J''(c) = 18 > 0 \ \checkmark\]Here \(J''\) is positive everywhere, not just at that point: the whole curve is a bowl (it’s convex), so this is the one and only minimum. And look, \(1025/9\) is exactly the mean of the nine measurements.
Numerically, by walking downhill. The slope (derivative) of the curve says how fast the cost changes as \(c\) increases. If it’s negative, increasing \(c\) lowers the cost; if it’s positive, decreasing \(c\) does. So a computer can find the minimum by repeatedly taking a small step against the slope, \(c_{k+1} = c_k - \gamma\, J'(c_k)\): gradient descent, literally walking downhill. This is what we use when the equation \(J' = 0\) is too hard to solve by hand.
Keep this picture. Everything that follows is about what different losses do to the shape of this curve, and especially to its slopes.
Two ways to penalise a deviation
The two most common losses are:
| Name | Loss \(\rho(r)\) | In words |
|---|---|---|
| L2, squared error | \(r^2\) | a deviation twice as large is penalised four times as much |
| L1, absolute error | \(\lvert r \rvert\) | a deviation twice as large is penalised twice as much |
(The names come from the \(\ell_2\) and \(\ell_1\) norms. A norm is a way of measuring the size of a whole list of numbers: \(\lVert r \rVert_1 = \sum_i \lvert r_i \rvert\) and \(\lVert r \rVert_2 = \sqrt{\sum_i r_i^2}\). Yep, the same ones hiding inside MAE and RMSE in Scoring Regressions!)
Let’s apply these two to our table and analyse how they behave. Model \(\hat y = c\), residuals \(r_i = y_i - c\), \(n = 9\). Take the derivative and set it to zero:
L2: the mean pops out
\[L_2(c) = \sum_i (y_i - c)^2 \quad \text{(a parabola in } c\text{)}\] \[\frac{dL_2}{dc} = -2 \sum_i (y_i - c) = 0\] \[\sum_i y_i - 9c = 0\] \[\Rightarrow\ c = \frac{1}{9} \sum_i y_i = \textbf{mean}\]L1: the median pops out
\[L_1(c) = \sum_i \lvert y_i - c \rvert\] \[\frac{dL_1}{dc} = -\sum_i \sgn(y_i - c) = 0\]\(\sgn(\cdot)\) only takes values \(-1, 0, 1\), so choose \(c\) such that the number of points below \(c\) equals the number above.
Sit with this for a while. Which number has half the data below it and half above it? Sort the measurements in ascending order and take the middle one:
\[1,\ 2,\ 3,\ 3.5,\ \boxed{3.5},\ 4,\ 4,\ 4,\ 1000\]That’s the median!
You see, for L1, moving \(c\) one unit toward the side with more points always helps, until the count balances. Magnitudes never enter the scene at all.
For this problem, that is the entire reason the median is robust
Change the last value from 1000 to \(10^6\). The mean moves enormously (from ≈ 113.9 to ≈ 111,114), but the median doesn’t budge from 3.5. The counting rule is the whole secret of the median’s toughness: how far the bad point lies never enters, only which side it’s on.
Careful, though: this is for fitting a single number. When we fit a line, an extra \(x_i\) shows up in the pull, and the story changes (see “who grabs the line?” below).
Just a caution
L1 optima might not be unique. For data \((-5, -5, 5, 5)\), every \(c \in [-5, 5]\) has two points on each side, so every one of them is a median and therefore optimal.
Fun fact: and the mode?
Penalise any miss by 1 and an exact hit by 0 (the “0–1 loss”). The best \(c\) is then the value hit most often: the mode, 4. Size doesn’t matter at all, only exact agreement.
Deviations pull: the force picture
Let’s try to analyse what’s happening. Call the slope of a point’s own loss its pull (or influence), \(\psi(r) = \rho'(r)\). Since \(J(c) = \sum_i \rho(y_i - c)\), the chain rule gives \(J'(c) = -\sum_i \psi(r_i)\), so gradient descent becomes
\[c_{k+1} = c_k + \gamma \sum_i \psi(r_i): \qquad \text{move } c \text{ in the direction of the net pull!}\]You see, for L1 it never mattered what the value of \(r\) is, but for L2 it matters: a larger \(r\) makes a greater force, so the best value gets influenced by it.
A physics way to see it
Picture \(c\) as a little bead on a rail, with every data point tied to it by a band that pulls the bead toward that point. Gradient descent keeps nudging the bead along the net force, and the bead settles where it feels zero total force: equilibrium, \(\sum_i \psi(r_i) = 0\). That’s exactly the “slope = 0” condition!
- L2 bands are ideal springs: stretch twice as far, pull twice as hard.
- L1 bands are strings with fixed tension: everyone pulls with strength 1, however far away.
| Size of residual \(r\) | Pull under L1 | Pull under L2 |
|---|---|---|
| 1 | 1 | 2 |
| 10 | 1 | 20 |
| 100 | 1 | 200 |
| 1000 | 1 | 2000 |
L2: a point’s pull grows with its distance, without limit. A point a thousand units away pulls a thousand times harder than one a unit away. That’s why one typo dragged the average to 113.9. L1: every point pulls with the same strength. One point, one vote; the majority decides.
Worked example: who holds the vote?
Three residuals of sizes 1, 1 and 100. Under L2 their pulls are 2, 2 and 200; under L1 they are 1, 1 and 1.
Key idea
To predict how a loss will behave, look at its pull (its slope), not its cost (its value). Under L1 the typo still costs \(\lvert 1000 - 3.5 \rvert = 996.5\); it just can’t pull any harder than anyone else.
Common pitfall
“L1 ignores outliers” is not about adding up absolute values: \(\lvert 1 \rvert + \lvert 2 \rvert + \lvert 3 \rvert + \lvert 4 \rvert + \lvert 1000 \rvert = 1010\) is dominated by the outlier too. The robustness is in where the best answer lands, and it comes from the capped pull.
Now let’s fit a line
Data \((x_i, y_i) = (0,0), (1,1), (2,2), (1,2)\); decision variables \(m, c\); model \(\hat y_i = m x_i + c\); residual \(r_i = y_i - (m x_i + c)\). Stack everything up:
\[A = \begin{bmatrix} x_1 & 1\\ x_2 & 1\\ x_3 & 1\\ x_4 & 1 \end{bmatrix}, \qquad \theta = \begin{bmatrix} m\\ c \end{bmatrix}, \qquad b = \begin{bmatrix} y_1\\ y_2\\ y_3\\ y_4 \end{bmatrix}, \qquad r = b - A\theta.\]L2: a closed-form answer
\[F(\theta) = \lVert A\theta - b \rVert^2 = (A\theta - b)^\top (A\theta - b) = \theta^\top A^\top A\, \theta - 2\, b^\top A\, \theta + b^\top b\] \[\frac{\partial F}{\partial \theta} = 2 A^\top A\, \theta - 2 A^\top b = 0 \quad\Longrightarrow\quad A^\top A\, \theta = A^\top b \quad\Longrightarrow\quad \boxed{\theta = (A^\top A)^{-1} A^\top b}\]For our points: \(A^\top A = \begin{bmatrix} 6 & 4\\ 4 & 4 \end{bmatrix}\), \(A^\top b = \begin{bmatrix} 7\\ 5 \end{bmatrix}\), so \(m = 1\) and \(c = 0.25\).
When does \((A^\top A)^{-1}\) exist?
\(A\) is \(N \times p\): \(N\) data points, \(p\) parameters (here \(4 \times 2\)). \(A^\top A\) is invertible exactly when the columns of \(A\) are linearly independent. Two things follow:
- Why \(N \ge p\)? \(p\) independent columns need at least \(p\) rows. One point can’t pin down both a slope and an intercept: infinitely many lines pass through it.
- Are the columns always independent in reality? Not always! If every \(x_i\) is the same, the \(x\) column is a multiple of the column of 1s, and every line through that vertical stack of points is equally good. Real noisy data is almost never exactly dependent, but nearly dependent columns make \(A^\top A\) almost singular and the answer very jumpy (more on taming that later in the series).
Who pulls on what? Look at each parameter separately:
\[\frac{\partial F}{\partial m} = -2 \sum_i x_i\, r_i, \qquad \frac{\partial F}{\partial c} = -2 \sum_i r_i.\]The pull on the slope is weighted by both the residual \(r_i\) and its \(x_i\). So in this case every point except \((0,0)\) has a say on the slope, as its \(x_i = 0\). The pull on the intercept only sees the residuals. In general, for any parameters \(\theta\) and any loss, \(\nabla_\theta J = \sum_i \psi(r_i)\, \nabla_\theta r_i\): the pull \(\psi\) times how much that parameter moves that residual.
L1 (least absolute deviation)
\[G(m, c) = \sum_i \big\lvert y_i - (m x_i + c) \big\rvert, \qquad \frac{\partial G}{\partial m} = -\sum_i x_i \sgn(r_i), \qquad \frac{\partial G}{\partial c} = -\sum_i \sgn(r_i).\]Setting these to zero is a median-type relation: for \(c\), the signs must balance (as many points above the line as below); for \(m\), the signs must balance weighted by \(x_i\), so the bigger the \(x_i\), the more weight its vote has.
| Balance conditions at the optimum | What has to cancel | |
|---|---|---|
| L2 | \(\sum_i r_i = 0\) and \(\sum_i x_i r_i = 0\) | residual sizes |
| L1 | \(\sum_i \sgn(r_i) = 0\) and \(\sum_i x_i \sgn(r_i) = 0\) | residual signs |
The takeaway
Both fits balance the residuals against \(1\) and \(x\). L2 balances their sizes, so the error spreads out; L1 balances only their signs, so the error can concentrate on a few points.
One more: who grabs the line?
Let’s take one more example to see the influence of both \(x_i\) and \(r_i\). Points: \((0,0), (1,1), (2,2)\), plus two troublemakers: \((1,10)\), which is far off in \(y\), and \((10,1)\), which is far off in \(x\).
My prediction (before computing anything!)
L2 will be torn apart between \((1,10)\) and \((10,1)\), with their big residuals dominating. L1 will be solely dominated by \((10,1)\): its pull on the slope is \(x_i \sgn(r_i)\), and \(x_i = 10\) is a big vote.
Prediction confirmed ✓! L2 gets torn: \((1,10)\) lifts it and \((10,1)\) tilts it downward, so it fits nobody well. L1 completely ignores \((1,10)\) (its residual is 9, but it only gets one vote), yet it gets captured by \((10,1)\): the best L1 line is the flat \(y = 1\), passing through \((1,1)\) and \((10,1)\) and ignoring the clear \(y = x\) trend.
Key idea: leverage
Under L1, a big residual buys a point no extra pull. On the intercept of the line fit, everyone gets exactly one vote (remember \(\partial G / \partial c = -\sum_i \sgn(r_i)\)). On the slope of the line fit, the residual’s size still doesn’t count, but each vote is multiplied by that point’s \(x_i\) (\(\partial G / \partial m = -\sum_i x_i \sgn(r_i)\)). So a point far out in \(x\), called a leverage point, gets a big vote on the slope, and that’s true under any loss \(\rho\). Changing the loss can’t fix it; you need methods that also limit how much a far-away \(x\) can count.
This is a different problem from having “many bad points”. Bad points have wrong \(y\) values, so their residuals are big, and L1 handles them by majority vote. A leverage point’s trouble is its \(x\) value: its lever arm is long, so even one vote from it moves the line a lot.
Rare event or broken data?
So L2 is fragile and L1 is tough. Should we always use L1? No, and the reason is the most important judgment in this whole article.
- A rare event is unusual but genuine: a real reading from the same process, just far from typical.
- An outlier comes from a different process: a typo, a sensor glitch, a mislabelled example.
The same number can be either, and you can’t tell from the number alone. A robot that is 50 cm off course might have a faulty sensor, or might really be 50 cm off course and about to hit a wall.
Key idea
Ask why a deviation is large, not whether it is large. If large deviations are real and costly, you want the answer to work hard to avoid them: L2 (or something even stronger). If they might be fake, you want to limit their pull: L1, or the compromise coming up next.
Worked example: collision avoidance
Which set of errors (in cm) is better?
A. \([1,1,1,1,1,1,1,1,1,1]\): ten predictions, each off by 1 cm
B. \([0,0,0,0,0,0,0,0,0,10]\): nine perfect, one off by 10 cm
The single 10 cm miss is the one that hits the wall, so A is better. L2 agrees: A costs \(10 \times 1^2 = 10\), B costs \(10^2 = 100\). L1 can’t tell them apart: 10 vs 10.
Worked example: which miss is real?
100 predictions each off by 10 cm, or 99 perfect and one off by 5 m? L1: 10 m vs 5 m, so it prefers the second. L2: 1 m² vs 25 m², so it prefers the first. Which is right depends on whether that 5 m miss is real (use L2) or a glitch (use L1, or the compromise coming up next).
Huber: trust small deviations, distrust large ones
Huber’s loss is quadratic for small residuals and linear for large ones, joined smoothly at a threshold \(\delta\):
\[\rho_\delta(r) = \begin{cases} \tfrac12 r^2 & \lvert r \rvert \le \delta \\ \delta \lvert r \rvert - \tfrac12 \delta^2 & \lvert r \rvert > \delta \end{cases} \qquad\qquad \text{pull} \quad \psi_\delta(r) = \begin{cases} r & \lvert r \rvert \le \delta \\ \pm\delta & \lvert r \rvert > \delta \end{cases}\](The \(\tfrac12\) in front of \(r^2\) is a convention that makes the pull exactly \(r\); it changes nothing about where the minimum is. From here on, L2 means \(\tfrac12 r^2\) too.)
Key idea
Huber’s sentence: “Inside \(\pm\delta\) I treat deviations as genuine; beyond it, a deviation’s size buys it no extra pull.” A wild point still pulls, but with its strength capped at \(\delta\). It caps the pull; it doesn’t delete the point.
- As \(\delta \to \infty\), Huber becomes L2; as \(\delta \to 0\), it becomes (a scaled) L1. \(\delta\) is a dial between the two.
- How big should \(\delta\) be? It’s measured relative to the typical size \(\sigma\) of the genuine noise, and the usual choice is \(\delta \approx 1.345\,\sigma\). (On our nine measurements, Huber lands at \(c \approx 3.5\), right next to the median.)
| Loss | \(\rho(r)\) | Pull \(\psi(r)\) | A far outlier’s pull | Convex? |
|---|---|---|---|---|
| L2 | \(\tfrac12 r^2\) | \(r\) | unbounded | yes |
| L1 | \(\lvert r \rvert\) | \(\sgn(r)\) | capped at 1 | yes |
| Huber | \(\tfrac12 r^2\) if \(\lvert r \rvert \le \delta\), else \(\delta \lvert r \rvert - \tfrac12 \delta^2\) | \(r\) inside, \(\delta \sgn(r)\) outside | capped at \(\delta\) | yes |
Choosing a rule on purpose
| Situation | Choice, and why |
|---|---|
| Clean data, small genuine noise | L2: large deviations are real and worth fixing first |
| Mostly clean, some bad points (a few wrong \(y\) values) | Huber: a safe default with capped pull |
| Many bad points (lots of wrong \(y\) values) | L1: majority rules |
| Catastrophes matter most, and are real | L2, a higher power (\(r^4\)), the worst case \(\max_i \lvert r_i \rvert\), or a hard limit written as a constraint, e.g. \(\lvert r_i \rvert \le 5\) cm for every \(i\) (no prediction may ever be off by more than 5 cm) |
| Outliers in \(x\) (leverage): a point whose \(x\) is far from the rest | no choice of \(\rho\) helps, because \(x_i\) multiplies its pull on the slope (see “who grabs the line?”): limit the influence of \(x\) too |
Requirements stated in words translate into objectives too. The short version: “must” and “never” become constraints; “prefer” and “less” become penalties.
Coming later
Some requirements, like “a simple model”, ask us to penalise the parameters themselves, not just the deviations. Same L1 and L2, brand new job: regularisation. And one more puzzle: squaring the errors works best when the noise follows a bell curve (Gaussian noise), while taking absolute values works best when the noise has a sharper peak and more occasional big jumps (Laplace noise). Why? That’s for a later post on estimation. Let’s find out!!
If you would like the next part in your inbox, you can subscribe on Substack.