Module contents
Lesson 1 of 24Core 80 min

The supervised learning problem: tasks, losses and what each one estimates

Frames supervised learning as a choice of output space, predictor, and loss, with training minimizing its empirical version. Catalogs regression and classification losses and derives the conditional-distribution functional each estimates (mean, median, quantile, expectile, log-odds), because choosing a loss means choosing what to predict. Risk theory, the Bayes predictor, and surrogate consistency are formalized in m13; here they serve as modeling tools.

After this lesson you can

  • Formulate a real problem, such as prioritizing security alerts, as a supervised task by choosing an output space, predictor, training loss, and evaluation metric.
  • Derive the population minimizers of squared, absolute, Huber, pinball, and asymmetric squared losses.
  • Compare 0-1, hinge, logistic, and exponential losses as functions of the margin and reason about their gradients and sensitivity to outliers.
  • Check empirically which transformation of P(Y = 1 | x) a classifier trained with each classification loss learns.
  • Distinguish the loss being optimized, the metric reported, and the cost that matters in the application.

Before you start

Motivation: choosing the loss means choosing what you predict

Your security team receives hundreds of alerts and vulnerability findings every day, and you have a labeled history: for each finding, its features (component, type of flaw, exposure to the internet, age of the code) and what happened afterward. You want a model to help make decisions. But “predicting” is not just one thing, and two similar-sounding questions call for different mathematical objects.

  • How long will it take to fix this finding? Fix time is positive and long-tailed: most findings are closed in days, but a few take months. If the model returns one number, which one should it be? The mean helps plan the team’s total workload, but extreme cases in the tail pull it far above the typical case. The median describes the typical case. To commit to a deadline met nine times out of ten, you need the 0.9 quantile. These are three different numbers for the same distribution, each obtained by training with a different loss.
  • Is this alert a real incident? The output could be a label, a score for ranking the queue, or a probability. If you want to make decisions based on costs (a missed incident costs much more than an unnecessary review) or pass the number to another system, you need a probability, and not every loss produces one: an SVM trained with hinge loss ranks the queue, but its output is not a probability and does not become one without recalibration.

This lesson frames supervised learning as three choices (an output space, a family of predictors, and a loss) and derives, loss by loss, which functional of the conditional distribution of YY given x\vb{x} each one estimates: the mean, median, a quantile, an expectile, the log-odds, half the log-odds, or just the sign. Risk theory, the Bayes predictor, and the consistency of surrogate losses are formalized in learning theory; here you will use them as modeling tools.

Setup: data, predictor, and loss

Let (X,Y)(X, Y) be a random pair with unknown joint distribution PP on X×Y\mathcal{X}\times\mathcal{Y}. XX represents the features (usually X=Rd\mathcal{X} = \R^d) and YY the response. You observe a sample D={(xi,yi)}i=1n\Data = \{(\vb{x}_i, y_i)\}_{i=1}^n with (xi,yi)∼iidP(\vb{x}_i, y_i) \iid P.

A predictor is a measurable function f:X→Af: \mathcal{X} \to \mathcal{A}. The set A\mathcal{A} of possible outputs need not match Y\mathcal{Y}: for labels y∈{−1,+1}y \in \{-1, +1\}, the model often returns a score f(x)∈Rf(\vb{x}) \in \R or a probability in [0,1][0, 1]. A loss is a function L:A×Y→[0,∞)L: \mathcal{A}\times\mathcal{Y} \to [0, \infty) measuring the cost of answering aa when the truth is yy. Its average under PP is the risk, and its sample average is the empirical risk:

R(f)=E[L(f(X),Y)],R^(f)=1n∑i=1nL(f(xi),yi).R(f) = \E\big[L(f(X), Y)\big], \qquad \hat{R}(f) = \frac{1}{n}\sum_{i=1}^n L(f(\vb{x}_i), y_i).

Training means choosing ff from a family F\mathcal{F} (lines, trees, networks) by minimizing empirical risk plus a regularization term that penalizes complexity:

f^=arg min⁡f∈F R^(f)+λ Ω(f).\hat f = \argmin_{f \in \mathcal{F}}\ \hat{R}(f) + \lambda\,\Omega(f).

This is the principle of empirical risk minimization, and when R^\hat{R} approximates RR well is the subject of population risk and generalization bounds. This lesson asks the preceding question: if you could minimize true risk over all functions, what would you obtain? The answer depends only on LL and the conditional distribution of YY given XX, and tells you what your model tries to approximate when you give it data.

The problem separates point by point

Risk is a double expectation: first over YY given X=xX = \vb{x} and then over XX. To write it this way we need the regular conditional distribution PY∣X=xP_{Y\given X=\vb{x}}, which exists whenever Y\mathcal{Y} is a Polish space (in particular Rk\R^k or a finite set). Define the conditional risk of answering aa at x\vb{x}:

r(a,x)=∫YL(a,y) PY∣X=x( ⁣dy)=E[L(a,Y)∣X=x].r(a, \vb{x}) = \int_{\mathcal{Y}} L(a, y)\, P_{Y\given X=\vb{x}}(\dd y) = \E[L(a, Y) \given X = \vb{x}].
Proof

By the disintegration property of the regular conditional distribution, every measurable g≥0g \ge 0 on X×Y\mathcal{X}\times\mathcal{Y} satisfies E[g(X,Y)]=∫X∫Yg(x,y) PY∣X=x( ⁣dy) PX( ⁣dx)\E[g(X, Y)] = \int_{\mathcal{X}} \int_{\mathcal{Y}} g(\vb{x}, y)\,P_{Y\given X=\vb{x}}(\dd y)\,P_X(\dd\vb{x}). With g(x,y)=L(f(x),y)g(\vb{x}, y) = L(f(\vb{x}), y), which is measurable because ff and LL are, we obtain R(f)=∫r(f(x),x) PX( ⁣dx)R(f) = \int r(f(\vb{x}), \vb{x})\,P_X(\dd\vb{x}). For almost every x\vb{x}, r(f(x),x)≥inf⁡ar(a,x)=r(f⋆(x),x)r(f(\vb{x}), \vb{x}) \ge \inf_a r(a, \vb{x}) = r(f^\star(\vb{x}), \vb{x}). Integrating the inequality with respect to PXP_X (both functions are nonnegative, so the integrals exist in [0,∞][0, \infty]) gives R(f)≥R(f⋆)R(f) \ge R(f^\star).

∎

The measurability assumption matters: the minimizer must be selectable as a measurable function of x\vb{x}. In every case in this lesson the minimizer is an explicit functional of PY∣X=xP_{Y\given X=\vb{x}} (its mean, a quantile), and measurability holds; the general case is a measurable selection theorem that you will not need here. The consequence is the lesson’s central idea: the best possible predictor is

f⋆(x)=T(PY∣X=x),f^\star(\vb{x}) = T\big(P_{Y\given X=\vb{x}}\big),

where TT is the functional that minimizes expected loss for a single distribution. So to know what a model learns, you only need to solve a one-variable problem: given a distribution of YY, which constant cc minimizes E[L(c,Y)]\E[L(c, Y)]?

Tasks: what the model produces in each case

Supervised tasks are distinguished by the response space Y\mathcal{Y} and, above all, by the output space A\mathcal{A} you choose for the model:

TaskY\mathcal{Y}Typical output A\mathcal{A}Security example
RegressionR\Ra real value (mean, median, quantile)days until a finding is fixed
Binary classification{−1,+1}\{-1, +1\}a score in R\R or a probability in [0,1][0, 1]is the alert a real incident?
Multiclass classification{1,…,K}\{1, \dots, K\}KK scores or a vector in the simplex ΔK−1\Delta^{K-1}malware family
Multilabel{0,1}K\{0, 1\}^KKK probabilities, one per label, which need not sum to 1which ATT&CK techniques appear in an incident
Probabilistic predictionR\R or {1,…,K}\{1, \dots, K\}a complete distribution (density, quantiles, probabilities)distribution of fix time

Three observations that are often missed:

  • The output is not the label. In classification you rarely train a model that returns the class directly: it returns a score or probability, and the class comes from comparing that output with a threshold. Separating the two lets you change the threshold when costs change without retraining.
  • Multiclass and multilabel are different. In multiclass classification the classes are mutually exclusive and the model gives a probability vector that sums to 1 (softmax regression); in multilabel classification each label is its own binary problem and the KK probabilities are independent of one another.
  • Probabilistic prediction is the richest case. If the model returns the entire distribution, every functional in this lesson can be read from it. It is trained with losses that evaluate distributions, such as the logarithmic score or CRPS. The losses in this lesson apply when you ask for only one number, so it matters which one.

Regression losses and the functional each estimates

Write the residual as u=y−cu = y - c, where cc is the prediction. The five regression losses used in practice are:

cuadraˊtica:L(c,y)=u2,absoluta:L(c,y)=∣u∣,Huber, con umbral δ>0:hδ(u)={12u2∣u∣≤δ,δ(∣u∣−12δ)∣u∣>δ,pinball (o de cuantil), con τ∈(0,1):ρτ(u)=u(τ−1[u<0]),cuadraˊtica asimeˊtrica, con τ∈(0,1):∣τ−1[u<0]∣ u2.\begin{aligned} &\text{cuadrática:} && L(c, y) = u^2, \\ &\text{absoluta:} && L(c, y) = \abs{u}, \\ &\text{Huber, con umbral } \delta > 0\text{:} && h_\delta(u) = \begin{cases} \tfrac12 u^2 & \abs{u} \le \delta, \\ \delta\big(\abs{u} - \tfrac12\delta\big) & \abs{u} > \delta, \end{cases} \\ &\text{pinball (o de cuantil), con } \tau \in (0, 1)\text{:} && \rho_\tau(u) = u\big(\tau - \ind[u < 0]\big), \\ &\text{cuadrática asimétrica, con } \tau \in (0, 1)\text{:} && \abs{\tau - \ind[u < 0]}\,u^2. \end{aligned}

All are convex functions of cc. Pinball loss weights positive residuals (underprediction) by τ\tau and negative ones (overprediction) by 1−τ1 - \tau; for τ=1/2\tau = 1/2 it is half the absolute loss. Asymmetric squared loss does the same with squares. Huber loss is quadratic near zero and linear outside [−δ,δ][-\delta, \delta], with the two pieces joined so that the function and its derivative are continuous at ±δ\pm\delta.

Before deriving anything, see which constant each chooses. The interactive computes the expected loss E[L(Y,c)]\E[L(Y, c)] in closed form for two distributions of YY (a long-tailed lognormal and a normal with a group of outliers) and marks its minimum.

InteractiveThe functional estimated by each loss
Density of Y∼LogNormal(0,1.002)Y \sim \mathrm{LogNormal}(0, 1.00^2)
01234567
Expected loss E[L(Y,c)]\E[L(Y, c)] minus its minimum, against constant cc
01234567
  • mean
  • median
  • chosen loss minimizer c⋆c^\star
Distribution of Y∣xY \mid x
1.00
Minimizer c⋆c^\star (mean)1.649
Mean EY\E Y1.649
Median1.000
P(Y≤c⋆)\Pr(Y \le c^\star)0.691
E[L(Y,c⋆)]\E[L(Y, c^\star)]4.671
The mean is at percentile 69: the tail pulls it far from the typical value.
Above, the density of YY with its mean (blue) and median (aqua); in magenta, the constant c⋆c^\star minimizing the selected loss. Below, expected loss E[L(Y,c)]\E[L(Y, c)] minus its minimum. Start with squared loss on the lognormal: the minimum is at the mean, at the 69th percentile, far from the peak. Switch to absolute loss. Then try Huber and move δ\delta from 0.05 to 5; do pinball and asymmetric squared loss with the same τ\tau coincide? Switch to “With outliers” and drag the red group right: which minimizers move with it?

The table below summarizes what you just saw; we will prove it:

LossDerivative of E[L(Y,c)]\E[L(Y, c)] with respect to ccPopulation minimizerAffected by a distant outlier?
squared2(c−EY)2(c - \E Y)mean EY\E Ywithout bound
absolute2F(c)−12F(c) - 1any medianno (only its side counts)
Huber−E[ψδ(Y−c)]-\E[\psi_\delta(Y - c)]Huber locationbounded effect
pinballF(c)−τF(c) - \tauany τ\tau quantileno
asymmetric squared2(1−τ)E(c−Y)+−2τE(Y−c)+2(1 - \tau)\E(c - Y)_+ - 2\tau\E(Y - c)_+τ\tau expectilewithout bound

Here FF is the cumulative distribution function of YY, (z)+=max⁡(z,0)(z)_+ = \max(z, 0), and ψδ(u)=max⁡(−δ,min⁡(u,δ))\psi_\delta(u) = \max(-\delta, \min(u, \delta)) is the derivative of hδh_\delta. The derivatives involving FF hold as written when FF is continuous at cc; with atoms we must use one-sided derivatives, exactly as in the exercise proofs.

Squared loss: the mean

If EY2<∞\E Y^2 < \infty, adding and subtracting EY\E Y gives

E(Y−c)2=E(Y−EY)2+2(EY−c) E(Y−EY)+(EY−c)2=Var⁡Y+(EY−c)2,\E(Y - c)^2 = \E(Y - \E Y)^2 + 2(\E Y - c)\,\E(Y - \E Y) + (\E Y - c)^2 = \Var Y + (\E Y - c)^2,

because the cross term has E(Y−EY)=0\E(Y - \E Y) = 0. The first term does not depend on cc, and the second is minimized, at zero, by c=EYc = \E Y, the unique minimizer. Applied to the conditional distribution, squared loss estimates the conditional expectation E[Y∣X=x]\E[Y \given X = \vb{x}]. Notice the price: Var⁡Y\Var Y is the error no constant can eliminate, and the excess over it grows with the square of the distance to the mean.

Absolute and pinball losses: the median and quantiles

If FF has density pp, differentiate under the integral in Eρτ(Y−c)=τ∫c∞(y−c)p(y) ⁣dy+(1−τ)∫−∞c(c−y)p(y) ⁣dy\E\rho_\tau(Y - c) = \tau\int_c^\infty (y - c)p(y)\dd y + (1 - \tau)\int_{-\infty}^c (c - y)p(y)\dd y:

 ⁣d ⁣dcEρτ(Y−c)=−τ(1−F(c))+(1−τ)F(c)=F(c)−τ.\frac{\dd}{\dd c}\E\rho_\tau(Y - c) = -\tau\big(1 - F(c)\big) + (1 - \tau)F(c) = F(c) - \tau.

The derivative increases with cc (the function is convex) and vanishes where F(c)=τF(c) = \tau: the minimizer is the τ\tau quantile, F−1(τ)F^{-1}(\tau), the quantile function evaluated at τ\tau. With τ=1/2\tau = 1/2 we obtain the median. The second derivative is the density p(c)p(c): the less mass around the quantile, the flatter the expected loss near the minimum and the harder it is to locate from data. This is the same pp that appears in the asymptotic variance of the sample quantile, τ(1−τ)/(n p(F−1(τ))2)\tau(1 - \tau)/\big(n\,p(F^{-1}(\tau))^2\big): tail quantiles, where density is low, are estimated less accurately.

The derivation above assumes a density. The result is more general: for any YY with E∣Y∣<∞\E\abs{Y} < \infty, the minimizers of Eρτ(Y−c)\E\rho_\tau(Y - c) are exactly the τ\tau quantiles, namely the values of cc with P(Y<c)≤τ≤P(Y≤c)\Pr(Y < c) \le \tau \le \Pr(Y \le c), which can form an interval. You will prove this in the exercises using one-sided derivatives and a subgradient. This underlies Koenker and Bassett’s (1978) quantile regression, which estimates conditional quantiles by minimizing empirical pinball loss, and quantile forecasting.

Huber: a robust compromise

hδh_\delta is differentiable with hδ′=ψδh_\delta' = \psi_\delta, and ∣ψδ∣≤δ\abs{\psi_\delta} \le \delta, so differentiation under the integral is justified by dominated convergence and

 ⁣d ⁣dcEhδ(Y−c)=−E[ψδ(Y−c)].\frac{\dd}{\dd c}\E h_\delta(Y - c) = -\E\big[\psi_\delta(Y - c)\big].

The function c↦Eψδ(Y−c)c \mapsto \E\psi_\delta(Y - c) is continuous and non-increasing, goes from δ\delta to −δ-\delta, and is strictly decreasing wherever P(∣Y−c∣<δ)>0\Pr(\abs{Y - c} < \delta) > 0. The minimizer, the Huber location, is a root of Eψδ(Y−c)=0\E\psi_\delta(Y - c) = 0: the point where the residuals, clipped to ±δ\pm\delta, balance. An outlier at distance 100 weighs as much in the equation as one at distance δ\delta. Both extremes are familiar:

  • δ→∞\delta \to \infty: ψδ(u)=u\psi_\delta(u) = u throughout the relevant support and the equation becomes E(Y−c)=0\E(Y - c) = 0: the mean.
  • δ→0\delta \to 0: ψδ(u)/δ→sign⁡(u)\psi_\delta(u)/\delta \to \operatorname{sign}(u) and the equation approaches Esign⁡(Y−c)=0\E\operatorname{sign}(Y - c) = 0, that is, P(Y>c)=P(Y<c)\Pr(Y > c) = \Pr(Y < c): the median.

Huber (1964) introduced this loss to estimate location when a fraction ε\eps of the data may come from an arbitrary distribution, and proved that his estimator minimizes asymptotic variance in the worst case under that contamination model. This is the Huber estimator you already know as an M-estimator. An important practical detail: δ\delta is measured in the units of YY, so the estimator is not scale-equivariant unless δ\delta scales with the data. A common choice is δ=1.345 σ^\delta = 1.345\,\hat\sigma, where σ^\hat\sigma is a robust scale, because this value gives 95% asymptotic efficiency relative to the mean on normal data (a lab cell calculates it).

Asymmetric squared loss: the expectile

With E∣Y∣<∞\E\abs{Y} < \infty (and EY2<∞\E Y^2 < \infty for finite expected loss), differentiate the expected loss G(c)=τE(Y−c)+2+(1−τ)E(c−Y)+2G(c) = \tau\E(Y - c)_+^2 + (1 - \tau)\E(c - Y)_+^2:

G′(c)=−2τ E(Y−c)++2(1−τ) E(c−Y)+\begin{aligned} G'(c) &= -2\tau\,\E(Y - c)_+ \\ &\quad + 2(1 - \tau)\,\E(c - Y)_+ \end{aligned}
The derivative of z+2z_+^2 is 2z+2z_+, which is continuous, so differentiation under the integral is justified using ∣Y∣+∣c∣\abs{Y} + \abs{c} as a dominating function near cc.
1/3

The function g(c)=(1−τ)E(c−Y)+−τE(Y−c)+g(c) = (1 - \tau)\E(c - Y)_+ - \tau\E(Y - c)_+ has derivative (1−τ)F(c)+τ(1−F(c))>0(1 - \tau)F(c) + \tau(1 - F(c)) > 0, so it is strictly increasing, goes from −∞-\infty to +∞+\infty, and has a unique root: the expectile eτe_\tau, introduced by Newey and Powell (1987) as a least-squares version of quantile regression. At τ=1/2\tau = 1/2 it is the mean. The difference from a quantile is fundamental: a quantile only looks at how much mass is on each side, while an expectile also looks at how far away it is. That is why for LogNormal(0,1)\mathrm{LogNormal}(0, 1) the 0.90.9 expectile (3.7703.770) exceeds the 0.90.9 quantile (3.6023.602), and why a distant outlier moves expectiles but not quantiles.

What a loss elicits

All of the above has a precise name.

Under this definition, squared loss elicits the mean (for distributions with finite variance), pinball elicits τ\tau quantiles, asymmetric squared loss elicits expectiles, and Huber elicits its location. Gneiting (2011) characterized consistent losses for the most widely used functionals: a loss is consistent for the mean if and only if it is a Bregman function, L(c,y)=ϕ(y)−ϕ(c)−ϕ′(c)(y−c)L(c, y) = \phi(y) - \phi(c) - \phi'(c)(y - c) with convex ϕ\phi, and is consistent for a quantile if and only if it is generalized piecewise linear, with pinball as the basic case. The first characterization has a practical consequence: ϕ(y)=y2\phi(y) = y^2 gives squared loss, but ϕ(y)=−log⁡y\phi(y) = -\log y gives L(c,y)=y/c−log⁡(y/c)−1L(c, y) = y/c - \log(y/c) - 1, which also elicits the mean and penalizes relatively (in financial econometrics it is used to compare volatility forecasts under the name QLIKE). Choosing the mean does not require squared error.

Not every functional is elicitable. Gneiting cites the example most relevant to finance: conditional value at risk (expected shortfall) is not, despite its popularity, while VaR, a quantile, is. You will see the consequences for evaluating risk forecasts in elicitability of risk measures. Gneiting’s argument has a second part relevant to any project: if a forecaster is asked for a functional (the median, the 0.9 quantile), the metric used to evaluate them must be consistent for that functional. Otherwise, evaluation rewards those who predict something else.

Classification: the optimal threshold and irreducible error

In binary classification with 0-1 loss, L(a,y)=1[a≠y]L(a, y) = \ind[a \neq y], risk is the probability of error. Let p(x)=P(Y=1∣X=x)p(\vb{x}) = \Pr(Y = 1 \given X = \vb{x}). If you answer 1 at x\vb{x}, you are wrong with probability 1−p(x)1 - p(\vb{x}); if you answer 0, with probability p(x)p(\vb{x}). By pointwise reduction, the best rule answers 1 exactly when p(x)>1/2p(\vb{x}) > 1/2, and its error

R⋆=E[min⁡{p(X), 1−p(X)}]R^\star = \E\big[\min\{p(X),\ 1 - p(X)\}\big]

is the problem’s irreducible error: no classifier that only looks at x\vb{x} can do better, however much data you have. It is positive whenever there is a region of positive probability where both classes coexist (0<p<10 < p < 1), which in real data occurs because of label noise or because x\vb{x} does not contain all the information determining YY. This rule is the Bayes predictor and R⋆R^\star its risk; both are studied in depth in the learning-theory error decomposition.

If errors have unequal costs, with cost cFNc_{FN} for a false negative and cFPc_{FP} for a false positive, the same argument compares cFP(1−p)c_{FP}(1 - p) with cFN pc_{FN}\,p: answer 1 when

p(x)>cFPcFP+cFN.p(\vb{x}) > \frac{c_{FP}}{c_{FP} + c_{FN}}.

If missing an incident costs nine times as much as a wasted review, the threshold falls from 1/21/2 to 0.10.1. This is why it is useful for the model to return p(x)p(\vb{x}) rather than the class: the threshold is a business decision that can change without touching the model, and the metrics lesson covers it as a cost-sensitive threshold.

InteractiveOptimal threshold and irreducible error
π0f0(x)\pi_0 f_0(x) and π1f1(x)\pi_1 f_1(x); shaded: your rule's error
−4−20246
P(Y=1∣x)P(Y = 1 \mid x) and level 0.500 where the Bayes rule changes its decision
10
  • class 0: π0f0\pi_0 f_0 and its false positives
  • class 1: π1f1\pi_1 f_1 and its false negatives
  • where the Bayes rule says 1
  • your threshold tt
Class 0 (blue) and class 1 (orange)
2.00
1.00
1.00
0.50
1.00
Your threshold tt and its error1.60, 0.1997
Bayes boundary (one point)1.00
Bayes error (irreducible)0.1587
Excess from your threshold0.0410
Threshold on P(Y=1∣x)P(Y = 1 \mid x)0.500
Any threshold other than the optimum adds area. Move tt to the curves’ intersection.
Two classes with Gaussian densities f0f_0 and f1f_1, weighted by their prior probabilities. Your rule says 1 if x>tx > t; the shaded areas show its errors (false positives in blue, false negatives in orange). The magenta bar marks where the Bayes rule says 1. Drag tt: the total area is smallest where the curves cross, and what remains is the irreducible error. Choose “Different variances”: the Bayes rule says 1 on both sides of an interval and no single threshold reaches the optimum. Increase the cost of false negatives and see the level on P(Y=1∣x)P(Y = 1 \mid x) fall and the boundary move.

The interactive model has closed-form boundaries. With X∣Y=k∼N(μk,σk2)X \given Y = k \sim \Normal(\mu_k, \sigma_k^2) and priors πk\pi_k, log⁡(cFNπ1f1(x))−log⁡(π0f0(x))\log\big(c_{FN}\pi_1 f_1(x)\big) - \log\big(\pi_0 f_0(x)\big) is a degree-2 polynomial in xx with leading coefficient 12σ02−12σ12\tfrac{1}{2\sigma_0^2} - \tfrac{1}{2\sigma_1^2}. If the variances are equal, it is linear and there is one threshold, the midpoint of the means shifted by σ2log⁡(π0/(cFNπ1))/(μ1−μ0)\sigma^2\log\big(\pi_0/(c_{FN}\pi_1)\big)/(\mu_1 - \mu_0). If they differ, the quadratic has two roots (or none, if one class dominates over all R\R) and, when roots exist, the more dispersed class wins in both tails. With μ0=0\mu_0 = 0, μ1=2\mu_1 = 2, σ=1\sigma = 1 and equal priors, Bayes error is Φ(−1)=0.1587\Phi(-1) = 0.1587: almost one in six cases is misclassified by the best possible rule. You will check this by numerical integration in the lab.

Classification losses as functions of the margin

Minimizing empirical 0-1 loss is a bad idea for two reasons. One is practical: as a function of the parameters it is piecewise constant, so its gradient is zero almost everywhere and does not indicate where to move. The other is more fundamental: even for half-spaces in Rd\R^d, finding the one minimizing the number of sample errors is NP-hard, including approximately (Ben-David, Eiron and Long, 2003). The way forward is to train with a convex surrogate loss and retain the sign of the score.

With labels y∈{−1,+1}y \in \{-1, +1\} (in this section, not {0,1}\{0, 1\}) and a score f(x)∈Rf(\vb{x}) \in \R whose sign is the predicted class, the margin m=y f(x)m = y\,f(\vb{x}) is positive when the prediction is correct and grows with confidence in that correct prediction. The most common classification losses are functions ϕ(m)\phi(m) of the margin:

Lossϕ(m)\phi(m)Where it appears
0-11[m<0]\ind[m < 0]the error you care about
hingemax⁡(0,1−m)\max(0, 1 - m)SVM (soft margin)
logisticlog⁡(1+e−m)\log(1 + e^{-m})logistic regression and networks
exponentiale−me^{-m}AdaBoost
squared(1−m)2=(y−f)2(1 - m)^2 = (y - f)^2least squares on ±1\pm 1 labels

The equality in the last row uses y2=1y^2 = 1: (y−f)2=y2−2yf+f2=1−2m+m2=(1−m)2(y - f)^2 = y^2 - 2yf + f^2 = 1 - 2m + m^2 = (1 - m)^2, because m2=y2f2=f2m^2 = y^2 f^2 = f^2. Logistic loss, written with probability q=σ(f)q = \sigmoid(f), is the cross-entropy between the label and qq.

InteractiveClassification losses as functions of the margin
Loss ϕ(m)\phi(m)
123−3−2−10123
Push −ϕ′(m)-\phi'(m) on the point (positive: increase its margin)
−2−1123m = 1exponential: 4.5 ↑
  • 0-1
  • Hinge
  • logistic (base 2)
  • Exponential
  • Squared
−1.50
Loss ϕ(m)\phi(m) | push −ϕ′(m)-\phi'(m)
0-11.00 | 0.00
Hinge2.50 | 1.00
Logistic2.45 | 1.18
Exponential4.48 | 4.48
Squared6.25 | 5.00
Misclassified: 0-1 loss is 1 and its derivative is 0, so it gives no direction for moving the model.
Above, the five losses against margin mm (logistic loss in base 2, divided by ln⁡2\ln 2, so it passes through (0,1)(0, 1) like the others; this does not change its minimizer). Below, the push −ϕ′(m)-\phi'(m): the point's contribution to the gradient that increases its margin. Drag the point. Select “Wrong label”: how many times more does that point push than one at the boundary for each loss? Select “Very confident”: which loss tries to reduce an already large margin?

The lower curves explain the character of each loss:

  • Exponential: −ϕ′(m)=e−m-\phi'(m) = e^{-m} grows without bound. A point with margin −3-3 pushes e3≈20e^3 \approx 20 times as much as one at the boundary. If its label is wrong, the model will distort the boundary to accommodate it. Long and Servedio (2010) proved that this problem is unavoidable for all boosting algorithms that minimize a convex potential: with random label noise, there are datasets those algorithms cannot learn even though they would be trivial without noise.
  • Logistic: −ϕ′(m)=σ(−m)≤1-\phi'(m) = \sigmoid(-m) \le 1. Misclassified points push at most twice as hard as one at the boundary (σ(3)/σ(0)=1.91\sigmoid(3)/\sigmoid(0) = 1.91), while correctly classified ones barely push.
  • Hinge: it pushes every point with m<1m < 1 with constant force and stops as soon as m≥1m \ge 1. Only points near the boundary or misclassified points, the support vectors, determine the solution.
  • Squared: −ϕ′(m)=2(1−m)-\phi'(m) = 2(1 - m) is negative for m>1m > 1. It penalizes points classified too well and pulls them toward m=1m = 1, an absurd behavior for classification: a few points far away on their correct side can drag a linear model’s boundary until it makes mistakes that logistic loss does not, even when the data are separable.

Which transformation of p(x) does each recover?

By pointwise reduction, the population minimizer is obtained by minimizing the conditional risk of score ff at each x\vb{x}:

Cp(f)=p ϕ(f)+(1−p) ϕ(−f),p=p(x).C_p(f) = p\,\phi(f) + (1 - p)\,\phi(-f), \qquad p = p(\vb{x}).
Proof

You will derive the logistic result in a guided exercise; the exponential result follows from the same argument. Squared loss is regression of Y∈{−1,+1}Y \in \{-1, +1\}: by the previous section its minimizer is E[Y∣x]=p−(1−p)=2p−1\E[Y \given \vb{x}] = p - (1 - p) = 2p - 1. For hinge loss, if f∈[−1,1]f \in [-1, 1] both positive parts are active and Cp(f)=p(1−f)+(1−p)(1+f)=1+(1−2p)fC_p(f) = p(1 - f) + (1 - p)(1 + f) = 1 + (1 - 2p)f, linear in ff: with p>1/2p > 1/2 its minimum on the interval is at f=1f = 1, with value 2(1−p)2(1 - p). If f>1f > 1, Cp(f)=(1−p)(1+f)>2(1−p)C_p(f) = (1 - p)(1 + f) > 2(1 - p). If f<−1f < -1, Cp(f)=p(1−f)>2p>2(1−p)C_p(f) = p(1 - f) > 2p > 2(1 - p). The p<1/2p < 1/2 case is symmetric, and for p=1/2p = 1/2, Cp≡1C_p \equiv 1 on [−1,1][-1, 1] and is larger outside.

∎

The exponential and logistic results are at the heart of the statistical view of boosting by Friedman, Hastie and Tibshirani (2000): AdaBoost estimates half the log-odds, and pp is recovered as σ(2F)\sigmoid(2F). The hinge result is due to Lin (2002): the SVM targets the Bayes rule directly, without going through the probability.

InteractiveWhat each classification loss learns
True probability p(x)=P(Y=1∣x)p(x) = P(Y = 1 \mid x) (drag the points)
0.00.51.0−3−2−10123
Population minimizer f⋆(x)f^\star(x) of each loss and true log-odds
−4−2−10124
  • true log-odds
  • Logistic
  • Exponential
  • Hinge
  • Squared
Lower panel scale
1.50
p(x)=P(Y=1∣x)p(x) = P(Y = 1 \mid x)0.860
log-odds log⁡p1−p\log\frac{p}{1 - p}1.819
f⋆f^\star Logistic1.819
f⋆f^\star Exponential0.910
f⋆f^\star Hinge1.000
f⋆f^\star Squared0.721
How to recover ppσ(2f⋆)=p\sigma(2f^\star) = p
Exponential loss recovers half the log-odds. Read through the sigmoid it gives 0.713 instead of 0.860: use σ(2f)\sigma(2f).
Above, the true probability p(x)=P(Y=1∣x)p(x) = P(Y = 1 \mid x): drag its control points. Below, the population minimizer f⋆(x)f^\star(x) of the selected loss, with true log-odds dashed. Exponential loss lies at half; hinge jumps between −1-1 and +1+1 at p=1/2p = 1/2 and forgets everything else. Change the scale to σ(f⋆)\sigma(f^\star), what you would see if you read the output as log-odds: only logistic returns pp. Choose “High overlap”: hinge changes sign several times while pp barely moves away from 1/21/2.

All four losses produce the Bayes rule when taking the sign, because all four f⋆f^\star have the sign of 2p−12p - 1. This property, that the minimizer’s sign matches the Bayes rule, is called classification calibration, and Bartlett, Jordan and McAuliffe (2006) gave a simple characterization for convex losses: convex ϕ\phi is classification-calibrated if and only if it is differentiable at 0 with ϕ′(0)<0\phi'(0) < 0. Everything else distinguishes the losses:

  • Logistic and exponential retain all of pp through an invertible transformation. Logistic gives a probability directly; exponential does too if you know to use σ(2f)\sigmoid(2f).
  • Squared is also invertible (p=(1+f)/2p = (1 + f)/2), but nothing forces a least-squares model to stay in [−1,1][-1, 1] (a linear model leaves it once x\vb{x} moves far enough away, and then (1+f)/2(1 + f)/2 is not a probability), and its sensitivity to points with m>1m > 1 distorts the boundary.
  • Hinge discards all information about pp except the sign. To obtain probabilities from an SVM, a calibration model such as Platt scaling must be fitted afterward.

The theory quantifying how much is lost in 0-1 error by minimizing a surrogate (the ψ\psi transform of Bartlett, Jordan and McAuliffe) appears in margins and surrogate losses.

Loss, metric, and cost: three distinct objects

Every real project involves three functions that are easy to confuse:

  1. Training loss is what the algorithm optimizes. It must be optimizable (convex or at least differentiable) and determines, as you have seen, which functional the model estimates.
  2. Evaluation metric is what you report and use to compare models: MAE, AUC, precision at kk. It need not be optimizable. These are studied in the evaluation metrics lesson.
  3. Real cost is what the organization loses for each decision: analyst hours, undetected incidents, missed deadlines. It can almost never be written exactly, but is what the other two should approximate.

Return to the alerts. The goal is for analysts, who review about kk alerts a day, to miss as few real incidents as possible. A coherent design:

  • Output: a probability p^(x)\hat p(\vb{x}) per alert. It ranks the queue and, given costs, helps decide which alerts to close without review.
  • Loss: logistic. It elicits p(x)p(\vb{x}) and is a proper scoring rule that rewards honest probabilities.
  • Metric: recall at kk (how many real incidents fall among the kk alerts reviewed), which measures the team’s actual work. Supplement it with a measure of calibration if probabilities are used for decisions.
  • Cost: set the threshold for closing alerts without review to cFP/(cFP+cFN)c_{FP}/(c_{FP} + c_{FN}), and the size of kk from the hours budget.

When the loss and metric ask for different functionals, the model is suboptimal for the metric even if perfectly trained. The simplest case: if you report MAE, the best prediction is the conditional median, while a model trained with squared error estimates the mean. In the lab, with LogNormal(0,1)\mathrm{LogNormal}(0, 1) data, predicting the mean instead of the median worsens test MAE by 11% (1.2541.254 versus 1.1281.128), and predicting the median worsens MSE by 9% (5.4215.421 versus 4.9574.957): each prediction wins under the metric that elicits it. When the metric is not optimizable (recall at kk is piecewise constant, like 0-1 loss), train with a surrogate targeting the same object (here, probability, which ranks alerts in the same order as any increasing transformation of it) and use the metric to choose models and tune hyperparameters.

Implementation from scratch

Empirical minimizers of regression losses

The empirical version of all the above: given a sample y1,…,yny_1, \dots, y_n, which constant minimizes 1n∑iL(c,yi)\frac1n\sum_i L(c, y_i)? The cell implements the five losses and their subgradients, minimizes them using subgradient descent (step ηt=η0/t\eta_t = \eta_0/\sqrt{t} and averaging the iterates from the second half, which guarantees convergence for non-differentiable convex functions) and SciPy’s minimize_scalar, and compares them with NumPy statistics on two samples: a lognormal and a normal with 5% outliers.

[ ]Regression losses and their empirical minimizersBrowser
import numpy as np
from scipy.optimize import minimize_scalar

# Pérdidas como funciones del residuo u = y - c y su (sub)derivada respecto a u.
# El gradiente respecto a la constante c es el de u cambiado de signo.
def cuadratica(u):       return u**2
def d_cuadratica(u):     return 2 * u
def absoluta(u):         return np.abs(u)
def d_absoluta(u):       return np.sign(u)                    # subgradiente: en u = 0 elige 0
def huber(u, d):         return np.where(np.abs(u) <= d, 0.5 * u**2, d * (np.abs(u) - 0.5 * d))
def d_huber(u, d):       return np.clip(u, -d, d)
def pinball(u, t):       return u * (t - (u < 0))
def d_pinball(u, t):     return t - (u < 0)                    # subgradiente: en u = 0 elige t
def asimetrica(u, t):    return np.abs(t - (u < 0)) * u**2
def d_asimetrica(u, t):  return 2 * np.abs(t - (u < 0)) * u

def descenso_subgradiente(y, d_perdida, pasos=1000):
    """Minimiza (1/n) sum L(y_i - c) en c con paso eta0/sqrt(t) y promedio de la segunda mitad."""
    eta0 = 2 * np.std(y)
    c, suma, k = 0.0, 0.0, 0
    for t in range(1, pasos + 1):
        g = -np.mean(d_perdida(y - c))                        # subgradiente respecto a c
        c -= eta0 / np.sqrt(t) * g
        if t > pasos // 2:
            suma += c; k += 1
    return suma / k

rng = np.random.default_rng(0)
n = 4000
muestras = {
    "lognormal(0, 1)": rng.lognormal(0.0, 1.0, n),
    "normal + 5 % de outliers en 8": np.where(rng.random(n) < 0.05, rng.normal(8, 0.5, n), rng.normal(0, 1, n)),
}
tau, delta = 0.9, 1.0
for nombre, y in muestras.items():
    print(nombre)
    casos = [
        ("cuadrática", d_cuadratica, cuadratica, f"np.mean        {np.mean(y):.4f}"),
        ("absoluta", d_absoluta, absoluta, f"np.median      {np.median(y):.4f}"),
        ("Huber δ = 1", lambda u: d_huber(u, delta), lambda u: huber(u, delta), ""),
        ("pinball τ = 0.9", lambda u: d_pinball(u, tau), lambda u: pinball(u, tau), f"np.quantile    {np.quantile(y, tau):.4f}"),
        ("asimétrica τ = 0.9", lambda u: d_asimetrica(u, tau), lambda u: asimetrica(u, tau), ""),
    ]
    for nom, dL, L, ref in casos:
        c_sg = descenso_subgradiente(y, dL)
        c_sp = minimize_scalar(lambda c: np.mean(L(y - c)), bounds=(y.min(), y.max()),
                               method="bounded", options={"xatol": 1e-9}).x
        print(f"  {nom:20s} subgradiente {c_sg:8.4f}   scipy {c_sp:8.4f}   {ref}")

y = muestras["lognormal(0, 1)"]
ys = np.sort(y)
print("\norden estadístico 3600 y 3601 de la lognormal:", np.round(ys[3599:3601], 4))

# entrenar con una pérdida y evaluar con otra, en una muestra de prueba independiente
prueba = rng.lognormal(0.0, 1.0, 100_000)
for nombre, c in [("media (entrenada con MSE)", y.mean()), ("mediana (entrenada con MAE)", np.median(y))]:
    print(f"predecir la {nombre:28s} c = {c:.3f}   MSE de prueba {np.mean((prueba - c)**2):.3f}   "
          f"MAE de prueba {np.mean(np.abs(prueba - c)):.4f}")

Everything matches the theory, with two subtleties worth reading in the output.

  • Squared loss follows outliers; absolute loss does not. In the contaminated sample, the mean is 0.3840.384 and the median 0.0640.064; Huber with δ=1\delta = 1 gives 0.0820.082, much closer to the median, because the outliers at distance 8 enter its equation clipped to 1. Asymmetric squared loss with τ=0.9\tau = 0.9 (2.4702.470) lies well above the 0.90.9 quantile (1.5711.571): the expectile does see how far away the outliers are.
  • The empirical pinball minimizer is not unique. With n=4000n = 4000 and τ=0.9\tau = 0.9, nτ=3600n\tau = 3600 is an integer and every point between the 3600th and 3601st order statistics minimizes empirical pinball loss (the function is linear between them with zero slope). SciPy and the subgradient method return points in that interval; np.quantile defaults to a particular interpolation. The same happens with the median when nn is even.
  • Each prediction wins with its own metric. On 100,000 new test points, the training-sample mean (1.6191.619) has the lowest MSE (4.9574.957 versus 5.4215.421) and the median (0.9680.968) the lowest MAE (1.1281.128 versus 1.2541.254). Neither is “the right one”: they answer different questions.

Now the expectile, using the fixed-point algorithm suggested by the last line of the derivation (iteratively reweighted asymmetric least squares), and the Huber location as δ\delta varies. Finally, Huber efficiency on normal data and the population values for LogNormal(0,1)\mathrm{LogNormal}(0, 1), which the first interactive shows in its initial state.

[ ]Expectiles, Huber between median and mean, and population valuesBrowser
import numpy as np
from scipy import stats, integrate, optimize

def expectil(y, tau, tol=1e-12, max_iter=200):
    """Punto fijo c = sum(w y) / sum(w), con w = tau por encima de c y 1 - tau por debajo."""
    c = y.mean()
    for it in range(1, max_iter + 1):
        w = np.where(y > c, tau, 1 - tau)
        c_nuevo = np.sum(w * y) / np.sum(w)
        if abs(c_nuevo - c) < tol:
            return c_nuevo, it
        c = c_nuevo
    return c, max_iter

for nombre, y in muestras.items():
    print(nombre)
    for t in [0.1, 0.5, 0.9, 0.99]:
        e, it = expectil(y, t)
        print(f"  τ = {t:4}:  expectil {e:7.3f} ({it:2d} iteraciones)   cuantil {np.quantile(y, t):7.3f}")

y = muestras["normal + 5 % de outliers en 8"]
print("\nHuber en la muestra contaminada (mediana %.3f, media %.3f):" % (np.median(y), y.mean()))
for d in [0.01, 0.1, 0.5, 1, 2, 5, 20]:
    c = optimize.minimize_scalar(lambda c: np.mean(huber(y - c, d)), bounds=(-2, 9), method="bounded",
                                 options={"xatol": 1e-9}).x
    print(f"  δ = {d:5}:  {c:.3f}")

# eficiencia asintótica de Huber frente a la media en datos N(0, 1): (E psi')^2 / E psi^2
k = 1.345
Ed = 2 * stats.norm.cdf(k) - 1
Epsi2 = Ed - 2 * k * stats.norm.pdf(k) + 2 * k**2 * stats.norm.sf(k)
print(f"\neficiencia de Huber con δ = {k}σ en la normal: {Ed**2 / Epsi2:.4f}")

# valores poblacionales de LogNormal(0, 1)
Y = stats.lognorm(1.0)
C = lambda c: integrate.quad(lambda v: (v - c) * Y.pdf(v), c, np.inf)[0]   # E(Y - c)+
P = lambda c: c - Y.mean() + C(c)                                         # E(c - Y)+
e90 = optimize.brentq(lambda c: 0.9 * C(c) - 0.1 * P(c), 0.01, 20)
hub = optimize.brentq(lambda c: Y.mean() - c - C(c + 1) + P(c - 1), 0.1, 5)   # E psi_1(Y - c) = 0
print(f"LogNormal(0, 1): media {Y.mean():.4f} (percentil {100 * Y.cdf(Y.mean()):.1f}), mediana {Y.median():.4f}, "
      f"cuantil 0.9 {Y.ppf(0.9):.4f}, expectil 0.9 {e90:.4f}, Huber δ = 1 {hub:.4f}")

The fixed-point method converges in a few iterations: the first-order condition is piecewise linear in cc, and each iteration is a Newton step on it. Expectiles and quantiles coincide only by chance; in the lognormal, the 0.990.99 expectile lies below the 0.990.99 quantile and the 0.90.9 expectile above it, whereas in the contaminated sample the 0.90.9 expectile is pulled by outliers. The Huber table moves monotonically from median to mean as δ\delta increases, as the analysis of the two extremes predicts.

What each classification loss learns

Now the experiment from the classification section with data. Generate x∼Unif⁡(−3,3)x \sim \Unif(-3, 3) and Y∈{−1,+1}Y \in \{-1, +1\} with true log-odds η(x)=2.5sin⁡(1.3x)+0.4x\eta(x) = 2.5\sin(1.3x) + 0.4x, and fit a flexible model f(x)=∑jβjbj(x)f(x) = \sum_j \beta_j b_j(x) with 13 Gaussian functions plus a constant, using each loss, by gradient descent. First, compute irreducible error by numerical integration.

[ ]Irreducible error by numerical integrationBrowser
import numpy as np
from scipy import integrate, stats, optimize

def eta_verdadero(x):
    return 2.5 * np.sin(1.3 * x) + 0.4 * x
def p_verdadera(x):
    return 1 / (1 + np.exp(-eta_verdadero(x)))

# x ~ U(-3, 3): R* = E min(p, 1 - p) = (1/6) * integral en [-3, 3]
bayes, _ = integrate.quad(lambda x: min(p_verdadera(x), 1 - p_verdadera(x)) / 6, -3, 3, limit=200)
print(f"error de Bayes del problema del laboratorio: {bayes:.4f}")

# las dos gaussianas del interactivo (prioris iguales)
def error_bayes(mu0, s0, mu1, s1, pi1=0.5):
    f = lambda x: min((1 - pi1) * stats.norm.pdf(x, mu0, s0), pi1 * stats.norm.pdf(x, mu1, s1))
    return integrate.quad(f, -30, 30, limit=400, points=[mu0, mu1])[0]
def error_umbral(t, mu0, s0, mu1, s1, pi1=0.5):         # regla «decir 1 si x > t»
    return (1 - pi1) * stats.norm.sf(t, mu0, s0) + pi1 * stats.norm.cdf(t, mu1, s1)

print(f"varianzas iguales  (0, 1) frente a (2, 1): {error_bayes(0, 1, 2, 1):.4f}   Φ(-1) = {stats.norm.cdf(-1):.4f}")
r = error_bayes(0, 1, 1.5, 2)
mejor = optimize.minimize_scalar(lambda t: error_umbral(t, 0, 1, 1.5, 2), bounds=(-3, 5), method="bounded")
print(f"varianzas distintas (0, 1) frente a (1.5, 2): Bayes {r:.4f}   mejor umbral único t = {mejor.x:.3f} con error {mejor.fun:.4f}")
# fronteras de Bayes: log f1(x) - log f0(x) = 0 es una cuadrática en x
mu0, s0, mu1, s1 = 0, 1, 1.5, 2
coef = [1 / (2 * s0**2) - 1 / (2 * s1**2), mu1 / s1**2 - mu0 / s0**2,
        mu0**2 / (2 * s0**2) - mu1**2 / (2 * s1**2) + np.log(s0 / s1)]
print("fronteras de la regla de Bayes:", np.round(np.sort(np.roots(coef)), 3))

The lab problem has an irreducible error of 0.1900.190: no classifier can go below it. In the interactive’s unequal-variance scenario, the Bayes rule (two boundaries) has error 0.26860.2686 and the best single threshold, at t=1.19t = 1.19, has error 0.27770.2777: it misses the left-tail region, x<−2.19x < -2.19, where the more dispersed class 1 becomes the most likely again. This is the difference the interactive shows when no position of tt reaches the optimum.

To make gradient descent converge in a few iterations, orthonormalize the basis over the sample with a QR factorization: in the columns of Z=n Q\mat{Z} = \sqrt{n}\,\mat{Q} the problem is well conditioned and a fixed step works for all smooth losses. For hinge loss, which is not differentiable at m=1m = 1, use a subgradient with a decreasing step and averaging of iterates.

[ ]Four losses, four learned functionsBrowser
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(1)
n = 4000
x = rng.uniform(-3, 3, n)
y = np.where(rng.random(n) < p_verdadera(x), 1.0, -1.0)

centros = np.linspace(-3, 3, 13)
def base(x):                                   # constante + 13 gaussianas de anchura 0.5
    return np.column_stack([np.ones_like(x)] + [np.exp(-0.5 * ((x - c) / 0.5) ** 2) for c in centros])

Phi = base(x)
Q, R = np.linalg.qr(Phi)
Z = Q * np.sqrt(n)                             # Z.T @ Z / n = I
R_inv = np.linalg.inv(R) * np.sqrt(n)          # para evaluar en puntos nuevos: base(x) @ R_inv

# derivada de phi(m) respecto al margen m = y f
d_phi = {
    "logística":   lambda m: -1 / (1 + np.exp(m)),
    "exponencial": lambda m: -np.exp(-m),
    "bisagra":     lambda m: -(m < 1).astype(float),
    "cuadrática":  lambda m: -2 * (1 - m),
}

def ajustar(dphi, pasos=400, eta=0.5, subgradiente=False):
    beta = np.zeros(Z.shape[1])
    media, k = np.zeros_like(beta), 0
    for t in range(1, pasos + 1):
        g = Z.T @ (dphi(y * (Z @ beta)) * y) / n          # gradiente del riesgo empírico
        beta -= (eta / np.sqrt(t) if subgradiente else eta) * g
        if subgradiente and t > pasos // 2:
            media += beta; k += 1
    return (media / k if subgradiente else beta), np.linalg.norm(g)

xs = np.linspace(-3, 3, 601)
Zs = base(xs) @ R_inv
p, eta = p_verdadera(xs), eta_verdadero(xs)
objetivo = {"logística": eta, "exponencial": eta / 2, "bisagra": np.sign(2 * p - 1), "cuadrática": 2 * p - 1}
a_prob = {"logística": lambda f: 1 / (1 + np.exp(-f)), "exponencial": lambda f: 1 / (1 + np.exp(-2 * f)),
          "cuadrática": lambda f: np.clip((1 + f) / 2, 0, 1)}

ajustes = {}
for nombre, dphi in d_phi.items():
    es_bisagra = nombre == "bisagra"
    beta, gnorm = ajustar(dphi, pasos=1000 if es_bisagra else 400, eta=1.0 if es_bisagra else 0.5, subgradiente=es_bisagra)
    f = Zs @ beta
    ajustes[nombre] = f
    err = np.mean(np.where(f >= 0, 1 - p, p))          # error 0-1 exacto: x uniforme en la rejilla
    linea = f"{nombre:12s} error 0-1 {err:.4f} (Bayes {bayes:.4f})   f en [{f.min():5.2f}, {f.max():5.2f}]"
    if nombre in a_prob:
        linea += f"   |p̂ - p| medio {np.mean(np.abs(a_prob[nombre](f) - p)):.3f}   |σ(f) - p| medio {np.mean(np.abs(1 / (1 + np.exp(-f)) - p)):.3f}"
    else:
        cerca = np.mean(np.abs(np.abs(f) - 1) < 0.25)
        linea += f"   fracción de la rejilla con |f| a menos de 0.25 de 1: {cerca:.2f}"
    print(linea)

fig, ax = plt.subplots(1, 4, figsize=(13, 3), sharex=True)
for a, (nombre, f) in zip(ax, ajustes.items()):
    a.plot(xs, np.clip(objetivo[nombre], -4, 4), "k--", lw=1, label="minimizador poblacional")
    a.plot(xs, np.clip(f, -4, 4), lw=2, label="ajuste")
    a.set_title(nombre); a.set_ylim(-4, 4); a.axhline(0, color="gray", lw=0.5)
ax[0].legend(fontsize=7); plt.tight_layout(); plt.show()

The output confirms the theorem with finite data. All four losses give almost the same 0-1 error (between 0.19140.1914 and 0.19280.1928, versus Bayes error 0.18990.1899), because all produce the correct sign where pp moves away from 1/21/2: the choice of loss barely matters for classification. But what they learned differs. Logistic reaches ±3\pm 3, like the log-odds; exponential stays at half, around ±1.5\pm 1.5; squared remains in [−1,1][-1, 1]; and hinge bunches around ±1\pm 1 (on 73% of the grid, ∣f∣\abs{f} is within 0.250.25 of 1). The probability column makes this clear: with their correct transformations (σ(f)\sigmoid(f), σ(2f)\sigmoid(2f), (1+f)/2(1 + f)/2), the three invertible losses recover pp with mean absolute error 0.020.02, but applying σ(f)\sigmoid(f) to the exponential or squared output out of habit raises error to 0.120.12 and 0.170.17. There is nothing to recover from hinge.

Finally, compare with scikit-learn: LogisticRegression minimizes the same log loss (with an L2 penalty made negligible here by a large C) on the same basis. If our descent has converged, the two functions should match.

[ ]Logistic regression from scratch versus scikit-learnBrowser
import numpy as np
from sklearn.linear_model import LogisticRegression

beta, gnorm = ajustar(d_phi["logística"], pasos=400)
lr = LogisticRegression(C=1e6, max_iter=5000, tol=1e-10).fit(Phi[:, 1:], y)    # la constante la pone sklearn
f_sk = lr.decision_function(base(xs)[:, 1:])
print(f"norma del gradiente al terminar: {gnorm:.1e}")
print(f"máx |f_nuestra - f_sklearn| en la rejilla: {np.max(np.abs(Zs @ beta - f_sk)):.1e}")
print(f"probabilidad en x = 1: nuestra {1 / (1 + np.exp(-(base(np.array([1.0])) @ R_inv @ beta)[0])):.4f}   "
      f"sklearn {lr.predict_proba(base(np.array([1.0]))[:, 1:])[0, 1]:.4f}   verdadera {p_verdadera(1.0):.4f}")

They match: the logistic problem is convex and strictly convex for these data (which are not separable), so it has a unique optimum, and two different algorithms (our gradient descent and scikit-learn’s L-BFGS) reach it. The difference from the true probability at x=1x = 1 is no longer optimization error: it is estimation error from finite nn and a finite basis.

The professional version

Libraries refer to losses by name, and it helps to know what functional each name elicits:

Library and parameterLossEstimates
LinearRegression, loss="squared_error" in GBDTs and SGDRegressorsquaredconditional mean
loss="absolute_error" in GradientBoostingRegressor and HistGradientBoostingRegressorabsoluteconditional median
QuantileRegressor(quantile=τ), loss="quantile" with alpha=τ or quantile=τ in GBDTspinballconditional τ\tau quantile
HuberRegressor(epsilon=1.35), loss="huber" in SGDRegressor and GradientBoostingRegressorHuberHuber location (HuberRegressor also estimates scale)
LogisticRegression, loss="log_loss" in SGDClassifier and GBDTslogisticlog-odds, and hence pp
GradientBoostingClassifier(loss="exponential")exponentialhalf the log-odds
LinearSVC, SVC, loss="hinge" in SGDClassifierhingeonly the sign of p−1/2p - 1/2
PyTorch: MSELoss, L1Loss, HuberLoss(delta), BCEWithLogitsLoss, CrossEntropyLosssquared, absolute, Huber, logistic, multiclass logisticmean, median, Huber, log-odds, probabilities

PyTorch does not provide pinball loss; it can be written in one line, torch.maximum(tau * u, (tau - 1) * u).mean() with u = y - pred, the same function as u(τ−1[u<0])u(\tau - \ind[u < 0]). The asymmetric squared loss for expectiles is not in scikit-learn either.

The next cell checks the regression rows with a model whose conditional functionals are all known straight lines: Y=1+0.5x+(0.5+x) εY = 1 + 0.5x + (0.5 + x)\,\varepsilon with ε∼Exp(1)\varepsilon \sim \mathrm{Exp}(1). Because noise scale grows with xx, the τ\tau quantile of YY given xx is 1+0.5x+(0.5+x) qτ1 + 0.5x + (0.5 + x)\,q_\tau, with qτ=−log⁡(1−τ)q_\tau = -\log(1 - \tau) the exponential quantile, and the mean follows from Eε=1\E\varepsilon = 1. Three functionals, three lines with different slopes, and each estimator should find its own.

[ ]Each estimator finds its lineBrowser
import numpy as np
from sklearn.linear_model import LinearRegression, QuantileRegressor

rng = np.random.default_rng(3)
n = 2000
x = rng.uniform(0, 3, n)
y = 1 + 0.5 * x + (0.5 + x) * rng.exponential(1.0, n)
X = x[:, None]

modelos = {
    "media (cuadrática)":       (LinearRegression(), 1.0),
    "mediana (pinball 0.5)":    (QuantileRegressor(quantile=0.5, alpha=0, solver="highs"), np.log(2)),
    "cuantil 0.9 (pinball 0.9)": (QuantileRegressor(quantile=0.9, alpha=0, solver="highs"), np.log(10)),
}
for nombre, (modelo, q) in modelos.items():
    modelo.fit(X, y)
    print(f"{nombre:26s} ajuste {modelo.intercept_:.3f} + {modelo.coef_[0]:.3f} x   "
          f"verdad {1 + 0.5 * q:.3f} + {0.5 + q:.3f} x")

# fracción de puntos por debajo de cada recta ajustada
for nombre, (modelo, q) in modelos.items():
    print(f"  fracción de puntos bajo la recta de {nombre.split(' (')[0]}: {np.mean(y <= modelo.predict(X)):.3f}")

The three fitted lines approach the true ones, with the estimation error expected from n=2000n = 2000 and a tailed distribution. The most direct check is the last: the 0.9 quantile line leaves 90% of points below it, the median line half, and the mean line substantially more than half, because with exponential noise the mean is above the median.

Connections

  • Learning theory formalizes risk, the Bayes predictor, error decomposition and surrogate consistency (the ψ\psi transform, margin bounds), used here as tools.
  • Logistic loss is the cross-entropy between label and predicted probability, and its multiclass version is the last layer of any classification network, including a GPT.
  • Pinball loss underlies quantile forecasting, and conditional quantiles are finance’s VaR.
  • A loss eliciting probability does not guarantee that a particular model estimates it well: measuring and correcting that is calibration, in lessons 21 and 22 of this module.

Common mistakes

Exercises

ProofThe mean and median as minimizers
Prove: Let YY be a real random variable. If EY2<∞\E Y^2 < \infty, the unique minimizer of c↦E(Y−c)2c \mapsto \E(Y - c)^2 is c=EYc = \E Y. If E∣Y∣<∞\E\abs{Y} < \infty, the minimizers of c↦E∣Y−c∣c \mapsto \E\abs{Y - c} are exactly the medians of YY, namely the mm with P(Y≤m)≥1/2\Pr(Y \le m) \ge 1/2 and P(Y≥m)≥1/2\Pr(Y \ge m) \ge 1/2.
0
Start with squared loss, then absolute loss. Let μ=EY\mu = \E Y and F(c)=P(Y≤c)F(c) = \Pr(Y \le c).

Step 1 of 4. How do you prove the squared-loss part?

ProofPinball loss elicits the quantile
Prove: Let YY be real with E∣Y∣<∞\E\abs{Y} < \infty, τ∈(0,1)\tau \in (0, 1) and ρτ(u)=u(τ−1[u<0])\rho_\tau(u) = u(\tau - \ind[u < 0]). Then cc minimizes g(c)=Eρτ(Y−c)g(c) = \E\rho_\tau(Y - c) if and only if P(Y<c)≤τ≤P(Y≤c)\Pr(Y < c) \le \tau \le \Pr(Y \le c), that is, if cc is a τ\tau quantile of YY.
0
gg is finite because ρτ(u)≤∣u∣\rho_\tau(u) \le \abs{u}, and convex because c↦ρτ(y−c)c \mapsto \rho_\tau(y - c) is convex for each yy.

Step 1 of 3. What is the right derivative of c↦ρτ(y−c)c \mapsto \rho_\tau(y - c) for fixed yy?

NumericThe best deadline with 0.9 pinball loss
The time YY (in days) to fix a type of finding follows Exp(1)\mathrm{Exp}(1). Which constant cc minimizes expected pinball loss Eρ0.9(Y−c)\E\rho_{0.9}(Y - c)? Give three decimal places.
NumericAn expectile by hand
Let Y∼Unif⁡(0,1)Y \sim \Unif(0, 1). Calculate the 0.80.8 expectile, the minimizer of E[∣0.8−1[Y<c]∣ (Y−c)2]\E\big[\abs{0.8 - \ind[Y < c]}\,(Y - c)^2\big]. Give three decimal places.
QuizChoose the loss from the question
You will train a gradient boosting model that returns, for each security finding, a fix deadline met in 90% of cases with those features. Which loss do you train it with?
ProofLogistic loss estimates log-odds
Prove: Let p∈(0,1)p \in (0, 1). The function Cp(f)=plog⁡(1+e−f)+(1−p)log⁡(1+ef)C_p(f) = p\log(1 + e^{-f}) + (1 - p)\log(1 + e^{f}) has a unique minimizer in R\R, namely f⋆=log⁡p1−pf^\star = \log\frac{p}{1 - p}.
0
This is the conditional risk of logistic loss ϕ(m)=log⁡(1+e−m)\phi(m) = \log(1 + e^{-m}) at a point with P(Y=1∣x)=pP(Y = 1 \mid \vb{x}) = p. Write σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z}).

Step 1 of 3. What is Cp′(f)C_p'(f)?

QuizReading AdaBoost output
A boosting model trained with exponential loss e−yF(x)e^{-y F(\vb{x})}, with y∈{−1,+1}y \in \{-1, +1\}, has reached its population minimizer. At a point it returns F(x)F(\vb{x}). Which expression gives p(x)=P(Y=1∣x)p(\vb{x}) = P(Y = 1 \mid \vb{x})?
NumericThe probability hidden in AdaBoost
With the model from the previous exercise, at one point F(x)=0.8F(\vb{x}) = 0.8. What probability p(x)p(\vb{x}) does this imply? Give three decimal places.
NumericThe error nobody can eliminate
The two classes are equally likely and X∣Y=0∼N(0,1)X \mid Y = 0 \sim \Normal(0, 1), X∣Y=1∼N(2,1)X \mid Y = 1 \sim \Normal(2, 1). What is the smallest classification error any rule based on xx can achieve? Give four decimal places.
NumericThe threshold when errors have different costs
Missing a real incident (false negative) costs 9 times as much as reviewing an alert that was not one (false positive). Given a model that provides well-calibrated p(x)=P(incidente∣x)p(\vb{x}) = P(\text{incidente} \mid \vb{x}), above which value of pp should you send the alert for review?
QuizWhat an SVM output says
A linear SVM trained with hinge loss scores two alerts: f(x1)=0.3f(\vb{x}_1) = 0.3 and f(x2)=−2.5f(\vb{x}_2) = -2.5. Which statement is justified by what hinge loss estimates?
CodeVectorized Huber loss and location by reweighted least squares
Implement three functions. huber_loss(u, delta): Huber loss hδh_\delta elementwise over an array. huber_grad(u, delta): its derivative ψδ(u)\psi_\delta(u), also vectorized. huber_location(y, delta, tol=1e-10, max_iter=500): the minimizer of 1n∑ihδ(yi−c)\frac1n\sum_i h_\delta(y_i - c) using iteratively reweighted least squares: with ri=yi−cr_i = y_i - c, weights wi=min⁡(1,δ/∣ri∣)w_i = \min(1, \delta/\abs{r_i}) (and wi=1w_i = 1 if ri=0r_i = 0), and update c←∑iwiyi/∑iwic \leftarrow \sum_i w_i y_i / \sum_i w_i until cc changes by less than tol. Start at the median. Do not use Python loops over elements.
import numpy as np

def huber_loss(u, delta):
  u = np.asarray(u, dtype=float)
  # tu código: 0.5 u^2 si |u| <= delta; delta (|u| - delta/2) si no
  return np.zeros_like(u)

def huber_grad(u, delta):
  u = np.asarray(u, dtype=float)
  # tu código: la derivada de huber_loss
  return np.zeros_like(u)

def huber_location(y, delta, tol=1e-10, max_iter=500):
  y = np.asarray(y, dtype=float)
  c = np.median(y)
  # tu código: pesos w = min(1, delta / |y - c|) y c = sum(w y) / sum(w), hasta converger
  return c
Shift+Enter to run

Summary

Key idea
Training by minimizing a loss asks for a particular functional of the conditional distribution of YY given x\vb{x}: squared loss asks for the mean, absolute loss the median, pinball a quantile, asymmetric squared loss an expectile, logistic the log-odds, exponential half of them, and hinge only the sign. Choose the loss based on what you need to predict.
  • A supervised problem is defined by the output space, predictor family, and loss. Because risk separates pointwise, the best possible predictor applies to each PY∣X=xP_{Y\given X=\vb{x}} the functional minimizing expected loss.
  • Squared loss estimates the mean and is sensitive to tails; absolute loss estimates the median; Huber is a compromise between them with δ\delta in units of YY; pinball estimates any quantile; asymmetric squared loss estimates expectiles, which unlike quantiles depend on tail distance.
  • A functional is elicitable if some loss has it as its unique minimizer. The mean, quantiles, and expectiles are elicitable; expected shortfall is not. The evaluation metric must be consistent for the requested functional.
  • With 0-1 loss, the best rule thresholds P(Y=1∣x)P(Y = 1 \given \vb{x}) at 1/21/2, or at cFP/(cFP+cFN)c_{FP}/(c_{FP} + c_{FN}) with costs, and class overlap imposes irreducible error.
  • Calibrated convex surrogate losses give the Bayes rule when taking the sign, but differ in all other respects: logistic preserves probability, exponential preserves it with a factor of 2 and explosively penalizes incorrect labels, squared loss pushes very well classified points backward, and hinge retains only the sign.
  • The loss you optimize, the metric you report, and the cost that matters are three different objects: align them, and when the metric is not optimizable, train with a surrogate targeting the same functional.