Why L1 Loss Produces the Median and L2 Loss Produces the Mean
Statistics & ExperimentsModel answerLast updated
Explain why minimizing absolute deviations yields the median while minimizing squared deviations yields the mean, and how these principles extend to higher dimensions.
You're working with a dataset and need to find a representative value that minimizes error across all observations.
Part 1: Explain with both intuition and mathematical reasoning why:
- The mean minimizes the sum of squared differences from all points
- The median minimizes the sum of absolute differences from all points
Part 2: Extend this reasoning to two-dimensional data:
- What point minimizes total Manhattan distance to a set of coordinates?
- What point minimizes total Euclidean distance (not squared)?
- What point minimizes total squared Euclidean distance?
Part 3: Discuss when using the mean as a summary statistic is inappropriate and what alternatives exist.
Provide derivations where appropriate, explain the geometric intuition, and highlight common pitfalls.
Hints
Hint 1
For L2, the derivative approach works cleanly. For L1, consider what happens to total cost when you shift the candidate point left or right by a small amount.
Hint 2
In two dimensions, check whether the objective function separates into independent x and y components or whether the coordinates are coupled.
Hint 3
Think about how far-away points influence the optimal location under each loss function—does a point twice as far away pull twice as hard, or the same amount?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Loss Functions and Central Tendency
Understanding L2 Loss and the Mean
Mathematical derivation:
We want to find the value c that minimizes:
$$L_2(c) = \sum_{i=1}^n (x_i - c)^2$$
Since this function is differentiable and convex, we take the derivative and set it equal to zero:
$$\frac{d}{dc} L_2(c) = \sum_{i=1}^n 2(x_i - c)(-1) = -2\sum_{i=1}^n (x_i - c) = 0$$
Solving for c:
$$\sum_{i=1}^n x_i = nc \quad \Rightarrow \quad c^* = \frac{1}{n}\sum_{i=1}^n x_i$$
This is exactly the arithmetic mean. The second derivative is 2n > 0, confirming this is a minimum.
Geometric intuition:
Under squared loss, each data point exerts influence proportional to its distance from c. A point 10 units away contributes 100 to the loss, while a point 1 unit away contributes only 1. The gradient term 2(x_i - c) shows that pull strength grows linearly with distance. The mean is the "balance point" where these distance-weighted forces cancel out.
Think of each data point as connected to c by a spring with stiffness proportional to distance—the mean is where all springs are in equilibrium.
Understanding L1 Loss and the Median
Mathematical derivation:
We want to minimize:
$$L_1(c) = \sum_{i=1}^n |x_i - c|$$
The absolute value function isn't differentiable at zero, so we use a subgradient argument. Consider what happens when we shift c by a small amount ε to the right:
- Points to the left of c (where x_i < c) increase their distance by ε, adding ε to the cost
- Points to the right of c (where x_i > c) decrease their distance by ε, reducing the cost by ε
If L is the count of points below c and R is the count above c, the change in total cost is:
$$\Delta L_1 = \varepsilon \cdot L - \varepsilon \cdot R = \varepsilon(L - R)$$
The cost decreases if L > R (shift right) or if R > L (shift left). The optimal c is where L = R, which defines the median.
Critical detail for even n:
When n is even, any value between the two middle elements (positions n/2 and n/2+1 when sorted) minimizes the objective. The function is flat across this interval. The conventional median takes the average of these two values, but all points in the interval are equally optimal.
Geometric intuition:
Under absolute loss, every data point pulls with unit force regardless of distance. Moving the largest value from 100 to 1,000,000 doesn't change the median because only the count on each side matters, not the magnitudes. This is why the median is robust to outliers—it has a 50% breakdown point.
Extension to Two Dimensions
Manhattan Distance (L1 in 2D)
Minimizing:
$$\sum_{i=1}^n |x_i - a| + |y_i - b|$$
This objective separates into independent components:
$$\sum_{i=1}^n |x_i - a| + \sum_{i=1}^n |y_i - b|$$
Each coordinate can be optimized independently. The optimal point is (median of all x-coordinates, median of all y-coordinates). This is the classic "warehouse location" problem solvable in O(n) time.
Squared Euclidean Distance
Minimizing:
$$\sum_{i=1}^n [(x_i - a)^2 + (y_i - b)^2]$$
This also separates by coordinate, so the optimum is (mean of x-coordinates, mean of y-coordinates)—the centroid. This is why k-means clustering updates each cluster center to the mean of its assigned points.
Euclidean Distance (Unsquared)
Minimizing:
$$\sum_{i=1}^n \sqrt{(x_i - a)^2 + (y_i - b)^2}$$
This does not separate because the square root couples the coordinates. Setting the gradient to zero:
$$\sum_{i=1}^n \frac{(a,b) - (x_i, y_i)}{|(a,b) - (x_i, y_i)|} = \mathbf{0}$$
Each point contributes a unit vector pointing from itself toward c. The optimal point, called the geometric median or Fermat-Weber point, requires the sum of these unit vectors to cancel.
There's no closed-form solution for n ≥ 3 in general position. It's computed iteratively using Weiszfeld's algorithm:
$$c_{k+1} = \frac{\sum_i w_i p_i}{\sum_i w_i}, \quad \text{where } w_i = \frac{1}{|p_i - c_k|}$$
Key distinction: The coordinate-wise median depends on axis orientation (rotate the data and you get different answers), while the geometric median is rotation-invariant.
| Loss Function | 1D Minimizer | 2D Minimizer |
|---|---|---|
| Sum of absolute differences | Median | Coordinate-wise median |
| Sum of squared distances | Mean | Centroid (mean) |
| Sum of Euclidean distances | Median | Geometric median |
When the Mean Fails
Situations favoring the median:
-
Heavy-tailed or skewed distributions: Income, session duration, page load times, social network degree distributions. A small number of extreme values dominate the mean. For latency metrics, p50/p95/p99 quantiles are standard.
-
Data contamination: Logging errors, placeholder values (-1, 999), bots, or data corruption can drastically shift the mean while leaving the median intact.
-
Infinite variance: Some distributions (Cauchy, Pareto with α ≤ 2) have undefined or infinite mean. The sample mean doesn't converge to anything useful.
-
Seeking a "typical" value: With data {1, 2, 3, 4, 100}, the mean is 22, which represents no actual observation, while the median is 3.
When the mean is appropriate:
- Aggregating totals: Total revenue = n × mean revenue. A/B tests on business metrics care about sums.
- Gaussian-like noise: The mean is the maximum likelihood estimator under Gaussian assumptions and is statistically efficient.
- Optimization framework: L2 loss ↔ Gaussian noise MLE; L1 loss ↔ Laplace noise MLE
Practical alternatives:
- Trimmed/winsorized means: Remove or cap extreme percentiles before averaging
- Huber loss: Combines L2 near zero (efficiency) with L1 in tails (robustness)
- Log transformation: For positive skewed data, use exp(mean(log(x)))
- Quantile regression: Generalization where different asymmetric losses yield different quantiles
The median's asymptotic efficiency under Gaussian noise is only 2/π ≈ 64% compared to the mean, so there's a real cost to robustness when the Gaussian assumption holds.
Common Errors to Avoid
-
Treating |x| as differentiable everywhere and claiming a unique L1 minimizer exists. Must use subgradients and acknowledge the flat interval when n is even.
-
Confusing unsquared and squared Euclidean distance. Only the squared version gives a closed-form centroid solution.
-
Claiming the coordinate-wise median minimizes Euclidean distance. It minimizes Manhattan distance; Euclidean requires the geometric median.
-
Overstating the median's advantages. When your metric is inherently a sum (revenue, total compute cost), the mean is correct even if the distribution is skewed.
-
Missing the influence function perspective. L2 gives unbounded influence (outliers matter a lot); L1 gives bounded influence at ±1 (outliers saturate). This single insight explains why medians resist contamination.