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 given 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 be a random pair with unknown joint distribution on . represents the features (usually ) and the response. You observe a sample with .
A predictor is a measurable function . The set of possible outputs need not match : for labels , the model often returns a score or a probability in . A loss is a function measuring the cost of answering when the truth is . Its average under is the risk, and its sample average is the empirical risk:
Training means choosing from a family (lines, trees, networks) by minimizing empirical risk plus a regularization term that penalizes complexity:
This is the principle of empirical risk minimization, and when approximates 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 and the conditional distribution of given , 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 given and then over . To write it this way we need the regular conditional distribution , which exists whenever is a Polish space (in particular or a finite set). Define the conditional risk of answering at :
Proof
By the disintegration property of the regular conditional distribution, every measurable on satisfies . With , which is measurable because and are, we obtain . For almost every , . Integrating the inequality with respect to (both functions are nonnegative, so the integrals exist in ) gives .
∎The measurability assumption matters: the minimizer must be selectable as a measurable function of . In every case in this lesson the minimizer is an explicit functional of (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
where 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 , which constant minimizes ?
Tasks: what the model produces in each case
Supervised tasks are distinguished by the response space and, above all, by the output space you choose for the model:
| Task | Typical output | Security example | |
|---|---|---|---|
| Regression | a real value (mean, median, quantile) | days until a finding is fixed | |
| Binary classification | a score in or a probability in | is the alert a real incident? | |
| Multiclass classification | scores or a vector in the simplex | malware family | |
| Multilabel | probabilities, one per label, which need not sum to 1 | which ATT&CK techniques appear in an incident | |
| Probabilistic prediction | or | 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 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 , where is the prediction. The five regression losses used in practice are:
All are convex functions of . Pinball loss weights positive residuals (underprediction) by and negative ones (overprediction) by ; for it is half the absolute loss. Asymmetric squared loss does the same with squares. Huber loss is quadratic near zero and linear outside , with the two pieces joined so that the function and its derivative are continuous at .
Before deriving anything, see which constant each chooses. The interactive computes the expected loss in closed form for two distributions of (a long-tailed lognormal and a normal with a group of outliers) and marks its minimum.
The table below summarizes what you just saw; we will prove it:
| Loss | Derivative of with respect to | Population minimizer | Affected by a distant outlier? |
|---|---|---|---|
| squared | mean | without bound | |
| absolute | any median | no (only its side counts) | |
| Huber | Huber location | bounded effect | |
| pinball | any quantile | no | |
| asymmetric squared | expectile | without bound |
Here is the cumulative distribution function of , , and is the derivative of . The derivatives involving hold as written when is continuous at ; with atoms we must use one-sided derivatives, exactly as in the exercise proofs.
Squared loss: the mean
If , adding and subtracting gives
because the cross term has . The first term does not depend on , and the second is minimized, at zero, by , the unique minimizer. Applied to the conditional distribution, squared loss estimates the conditional expectation . Notice the price: 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 has density , differentiate under the integral in :
The derivative increases with (the function is convex) and vanishes where : the minimizer is the quantile, , the quantile function evaluated at . With we obtain the median. The second derivative is the density : 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 that appears in the asymptotic variance of the sample quantile, : tail quantiles, where density is low, are estimated less accurately.
The derivation above assumes a density. The result is more general: for any with , the minimizers of are exactly the quantiles, namely the values of with , 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
is differentiable with , and , so differentiation under the integral is justified by dominated convergence and
The function is continuous and non-increasing, goes from to , and is strictly decreasing wherever . The minimizer, the Huber location, is a root of : the point where the residuals, clipped to , balance. An outlier at distance 100 weighs as much in the equation as one at distance . Both extremes are familiar:
- : throughout the relevant support and the equation becomes : the mean.
- : and the equation approaches , that is, : the median.
Huber (1964) introduced this loss to estimate location when a fraction 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: is measured in the units of , so the estimator is not scale-equivariant unless scales with the data. A common choice is , where 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 (and for finite expected loss), differentiate the expected loss :
The function has derivative , so it is strictly increasing, goes from to , and has a unique root: the expectile , introduced by Newey and Powell (1987) as a least-squares version of quantile regression. At 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 the expectile () exceeds the quantile (), 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 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, with convex , 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: gives squared loss, but gives , 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, , risk is the probability of error. Let . If you answer 1 at , you are wrong with probability ; if you answer 0, with probability . By pointwise reduction, the best rule answers 1 exactly when , and its error
is the problem’s irreducible error: no classifier that only looks at can do better, however much data you have. It is positive whenever there is a region of positive probability where both classes coexist (), which in real data occurs because of label noise or because does not contain all the information determining . This rule is the Bayes predictor and its risk; both are studied in depth in the learning-theory error decomposition.
If errors have unequal costs, with cost for a false negative and for a false positive, the same argument compares with : answer 1 when
If missing an incident costs nine times as much as a wasted review, the threshold falls from to . This is why it is useful for the model to return 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.
The interactive model has closed-form boundaries. With and priors , is a degree-2 polynomial in with leading coefficient . If the variances are equal, it is linear and there is one threshold, the midpoint of the means shifted by . If they differ, the quadratic has two roots (or none, if one class dominates over all ) and, when roots exist, the more dispersed class wins in both tails. With , , and equal priors, Bayes error is : 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 , 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 (in this section, not ) and a score whose sign is the predicted class, the margin is positive when the prediction is correct and grows with confidence in that correct prediction. The most common classification losses are functions of the margin:
| Loss | Where it appears | |
|---|---|---|
| 0-1 | the error you care about | |
| hinge | SVM (soft margin) | |
| logistic | logistic regression and networks | |
| exponential | AdaBoost | |
| squared | least squares on labels |
The equality in the last row uses : , because . Logistic loss, written with probability , is the cross-entropy between the label and .
The lower curves explain the character of each loss:
- Exponential: grows without bound. A point with margin pushes 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: . Misclassified points push at most twice as hard as one at the boundary (), while correctly classified ones barely push.
- Hinge: it pushes every point with with constant force and stops as soon as . Only points near the boundary or misclassified points, the support vectors, determine the solution.
- Squared: is negative for . It penalizes points classified too well and pulls them toward , 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 at each :
Proof
You will derive the logistic result in a guided exercise; the exponential result follows from the same argument. Squared loss is regression of : by the previous section its minimizer is . For hinge loss, if both positive parts are active and , linear in : with its minimum on the interval is at , with value . If , . If , . The case is symmetric, and for , on 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 is recovered as . The hinge result is due to Lin (2002): the SVM targets the Bayes rule directly, without going through the probability.
All four losses produce the Bayes rule when taking the sign, because all four have the sign of . 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 is classification-calibrated if and only if it is differentiable at 0 with . Everything else distinguishes the losses:
- Logistic and exponential retain all of through an invertible transformation. Logistic gives a probability directly; exponential does too if you know to use .
- Squared is also invertible (), but nothing forces a least-squares model to stay in (a linear model leaves it once moves far enough away, and then is not a probability), and its sensitivity to points with distorts the boundary.
- Hinge discards all information about 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 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:
- 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.
- Evaluation metric is what you report and use to compare models: MAE, AUC, precision at . It need not be optimizable. These are studied in the evaluation metrics lesson.
- 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 alerts a day, to miss as few real incidents as possible. A coherent design:
- Output: a probability per alert. It ranks the queue and, given costs, helps decide which alerts to close without review.
- Loss: logistic. It elicits and is a proper scoring rule that rewards honest probabilities.
- Metric: recall at (how many real incidents fall among the 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 , and the size of 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 data, predicting the mean instead of the median worsens test MAE by 11% ( versus ), and predicting the median worsens MSE by 9% ( versus ): each prediction wins under the metric that elicits it. When the metric is not optimizable (recall at 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 , which constant minimizes ? The cell implements the five losses and their subgradients, minimizes them using subgradient descent (step 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.
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 and the median ; Huber with gives , much closer to the median, because the outliers at distance 8 enter its equation clipped to 1. Asymmetric squared loss with () lies well above the quantile (): the expectile does see how far away the outliers are.
- The empirical pinball minimizer is not unique. With and , 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.quantiledefaults to a particular interpolation. The same happens with the median when is even. - Each prediction wins with its own metric. On 100,000 new test points, the training-sample mean () has the lowest MSE ( versus ) and the median () the lowest MAE ( versus ). 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 varies. Finally, Huber efficiency on normal data and the population values for , which the first interactive shows in its initial state.
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 , and each iteration is a Newton step on it. Expectiles and quantiles coincide only by chance; in the lognormal, the expectile lies below the quantile and the expectile above it, whereas in the contaminated sample the expectile is pulled by outliers. The Huber table moves monotonically from median to mean as increases, as the analysis of the two extremes predicts.
What each classification loss learns
Now the experiment from the classification section with data. Generate and with true log-odds , and fit a flexible model with 13 Gaussian functions plus a constant, using each loss, by gradient descent. First, compute irreducible error by numerical integration.
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 : no classifier can go below it. In the interactive’s unequal-variance scenario, the Bayes rule (two boundaries) has error and the best single threshold, at , has error : it misses the left-tail region, , where the more dispersed class 1 becomes the most likely again. This is the difference the interactive shows when no position of 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 the problem is well conditioned and a fixed step works for all smooth losses. For hinge loss, which is not differentiable at , use a subgradient with a decreasing step and averaging of iterates.
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 and , versus Bayes error ), because all produce the correct sign where moves away from : the choice of loss barely matters for classification. But what they learned differs. Logistic reaches , like the log-odds; exponential stays at half, around ; squared remains in ; and hinge bunches around (on 73% of the grid, is within of 1). The probability column makes this clear: with their correct transformations (, , ), the three invertible losses recover with mean absolute error , but applying to the exponential or squared output out of habit raises error to and . 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.
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 is no longer optimization error: it is estimation error from finite 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 parameter | Loss | Estimates |
|---|---|---|
LinearRegression, loss="squared_error" in GBDTs and SGDRegressor | squared | conditional mean |
loss="absolute_error" in GradientBoostingRegressor and HistGradientBoostingRegressor | absolute | conditional median |
QuantileRegressor(quantile=τ), loss="quantile" with alpha=τ or quantile=τ in GBDTs | pinball | conditional quantile |
HuberRegressor(epsilon=1.35), loss="huber" in SGDRegressor and GradientBoostingRegressor | Huber | Huber location (HuberRegressor also estimates scale) |
LogisticRegression, loss="log_loss" in SGDClassifier and GBDTs | logistic | log-odds, and hence |
GradientBoostingClassifier(loss="exponential") | exponential | half the log-odds |
LinearSVC, SVC, loss="hinge" in SGDClassifier | hinge | only the sign of |
PyTorch: MSELoss, L1Loss, HuberLoss(delta), BCEWithLogitsLoss, CrossEntropyLoss | squared, absolute, Huber, logistic, multiclass logistic | mean, 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 . 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: with . Because noise scale grows with , the quantile of given is , with the exponential quantile, and the mean follows from . Three functionals, three lines with different slopes, and each estimator should find its own.
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 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 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
Step 1 of 4. How do you prove the squared-loss part?
Step 1 of 3. What is the right derivative of for fixed ?
Step 1 of 3. What is ?
huber_loss(u, delta): Huber loss elementwise over an array. huber_grad(u, delta): its derivative , also vectorized. huber_location(y, delta, tol=1e-10, max_iter=500): the minimizer of using iteratively reweighted least squares: with , weights (and if ), and update until 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 cSummary
- A supervised problem is defined by the output space, predictor family, and loss. Because risk separates pointwise, the best possible predictor applies to each 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 in units of ; 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 at , or at 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.