Quantile Regression › Formula
Machine Learning from ScratchAll chapters Quantile Regression › FormulaSection view · Sections in this chapter4 / 10 ↓
Reading tools Definitions, links & notes
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
A regression model for the mean answers the question "what is the average response at this ?" A regression model for a quantile answers a sharper question: "what cutoff has at most a fraction of responses strictly below it and at least a fraction at or below it at this ?" To make that question precise we need three ingredients: a definition of a conditional quantile, a loss function whose minimizer is that quantile, and a finite-sample optimization problem we can solve. The first two are population statements; the third is what turns the idea into an algorithm.
We begin with notation. Let be a response variable and let the full predictor vector be , with for the intercept. There are nonconstant predictors and entries in the design vector. The cumulative distribution function of is , and the -quantile of , for , is
The infimum handles distributions with flat regions or jumps; where is continuous and strictly increasing it agrees with the ordinary inverse; otherwise it remains a generalized inverse. Conditioning on the predictors gives the target:
where:
- : the conditional cumulative distribution function of given
- : the value of that conditional CDF evaluated at a candidate response value
- : the infimum, the greatest lower bound of the set of response values satisfying the inequality
- : the conditional -quantile of at a given predictor value , the smallest response value whose conditional CDF reaches at least
For intuition, consider the case where is normal with mean and standard deviation . Then
where:
- : the quantile function of the standard normal distribution, evaluated at probability , which is the same -value used for confidence intervals in the z-test
- : the conditional mean of given
- : the conditional standard deviation of given
At we get , because . At we get . So if we assume normality, the conditional quantile function is just the mean function shifted by a multiple of the conditional standard deviation. Ordinary least squares estimates and, when it assumes constant variance, treats as a single number. Quantile regression estimates directly, which lets and both vary with , and lets the shape vary too.
A quantile is a local summary of a distribution: it depends on where probability mass accumulates near the cut, not just on a global average. That local character explains two features that will reappear throughout the chapter. First, different quantiles can respond to the predictors in different ways, so a single slope is not enough. Second, precision depends on the density near the selected cutoff and on the predictor design. Low normal-tail density makes extreme levels difficult in our Gaussian example, but there is no universal ordering of quantile variances. The pinball loss below encodes exactly this local, asymmetric view of the data.
Conditional quantiles and pinball loss
To estimate a quantile we need a loss function minimized at that quantile. In the following expectation calculations assume for squared error and for pinball loss. For the density-based derivatives, assume the distribution has a continuous density near the candidate cutoff. Start with the familiar case. Minimizing the expected squared error over the candidate value ,
leads to the mean. Differentiating with respect to (the finite second moment allows the locally integrable derivative to pass through the expectation) gives
which is zero exactly when . Setting the derivative to zero and checking that the second derivative, , confirms a minimum. Squared error is married to the mean.
Now replace squared error with the asymmetric absolute-value loss known as the pinball loss, or check loss. Here is the signed residual between an observation and a candidate value , and is the target quantile level:
where:
- : the residual, the signed difference between the observation and the candidate value,
- : the target quantile level in
- : the pinball loss at level for residual
- : the candidate value at which the pinball loss is being evaluated
For , the positive-residual branch is steeper: its slope magnitude is , compared with on the negative side. A compact way to write the same function is
where:
- : the residual, the signed difference between the observation and the candidate value,
- : the target quantile level in
- : the indicator function, equal to 1 when its argument is true and 0 otherwise
- : the candidate value at which the pinball loss is being evaluated, so that the loss is a function of and of
- : the pinball loss at level for residual
Check the two branches: if the indicator is zero and we get ; if the indicator is one and we get , which is positive because and . At both slopes have magnitude , and , so the pinball loss is just half the absolute error.
The asymmetry is the whole point. For a high quantile, say , a positive residual (an observation above the fitted value) is penalized by slope , while a negative residual is penalized by slope . For one unrestricted sample cutoff that minimizes this loss, at most 90 percent of observations lie strictly below it and at least 90 percent lie at or below it. For a low quantile the push goes the other way. This is how a single loss function encodes a target probability level. The left branch has slope (magnitude ) and the right branch has slope . These magnitudes are equal only when . Any other makes the two arms differ in slope, and the loss is asymmetric.
To see that this loss is minimized by the -quantile, let be the probability density function of and write the expected loss at a candidate value , where is the candidate value being scored, is the density of , and is the pinball loss defined above. We obtain
The first integral collects the observations below , where the residual is negative and the loss uses the branch; the second collects observations above .
where:
- : the candidate value being scored as a quantile
- : the probability density function of
- : the pinball loss at level , defined above
- : the expected pinball loss at the candidate value
Now differentiate with respect to . The finite first moment makes the expected loss finite; the residual-loss derivatives are bounded by 1 in magnitude, which justifies differentiation at continuity points of the CDF. Both integrands vanish at the boundary because each factor contains , so the Leibniz rule gives no boundary contribution and we only need the derivative of the integrands.
The derivative of with respect to is , and that of is . At either moving integration endpoint , the factor is zero, so each boundary contribution vanishes. Recognizing the remaining integrals as probabilities gives:
where:
- : the cumulative distribution function of evaluated at
The two terms combine: , leaving . Setting this to zero gives . When the CDF is strictly increasing at this cutoff, it selects the unique ; a flat region can give multiple minimizing values. The second derivative is , so is convex and this stationary point is a global minimum. The pinball loss is therefore the loss whose minimizer is the quantile, exactly as squared error is the loss whose minimizer is the mean.
For a finite sample, define and let be the fraction strictly below . The subgradient interval of the average pinball loss, as a function of , is . A minimum occurs exactly when this interval contains zero, giving the counting rule:
In words: the number of observations strictly below the estimate is at most , and the number at or below it is at least ; dividing by , at most a fraction of the data lie strictly below the estimate and at least a fraction lie at or below it. Ties at exactly are what allow both inequalities to hold when is not an integer, so the two sides can disagree by the mass pinned at .
The figure below makes the asymmetry visible. Each curve is a pinball loss for a different . The two constant residual slopes, together with the kink at zero, give the quantile counting condition derived above.
PythonIn [3]Expand
u_grid = np.linspace(-2.5, 2.5, 401)
pinball_levels = (0.1, 0.5, 0.9)
pinball_curves = {
level: np.where(u_grid >= 0, level * u_grid, (level - 1) * u_grid)
for level in pinball_levels
}
squared_comparison = 0.5 * u_grid**2PythonIn [4]Expand
import matplotlib.pyplot as plt
from book_plot_style import PALETTE, polish_axes, use_book_style
use_book_style()
fig, ax = plt.subplots(figsize=(6.0, 4.8))
for tau_level, color, line_style in zip(
pinball_levels,
[PALETTE["primary"], PALETTE["amber"], PALETTE["teal"]],
["-", "-.", ":"],
):
ax.plot(
u_grid,
pinball_curves[tau_level],
color=color,
linewidth=1.1,
linestyle=line_style,
label=rf"$\tau = {tau_level}$",
)
ax.plot(
u_grid,
squared_comparison,
color=PALETTE["muted"],
linewidth=1.6,
linestyle="--",
label="squared error (scaled)",
)
ax.axvline(0.0, color=PALETTE["axis"], linewidth=0.8, alpha=0.4)
ax.set_title("Pinball loss versus squared error")
ax.set_xlabel(r"Residual $u = y - q$")
ax.set_ylabel(r"Loss $\rho_\tau(u)$")
ax.set_ylim(-0.6, 2.6)
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.18), ncol=2)
polish_axes(ax)
plt.show()VisualizationOut [4]Expand

Linear quantile regression as an optimization problem
Now we restrict attention to linear quantile functions. For a chosen , we model
The convention that absorbs the intercept , so that with a -dimensional parameter vector.
Here:
- : the coefficient vector at quantile level , of length , indexed from to
- : the intercept at level , multiplying the constant
- : the coefficient on predictor at level , for
- : the -th nonconstant predictor, for
- : the observed predictors, to which the constant is prepended
- : the full predictor vector with the prepended constant, so that is the fitted -quantile
The notation emphasizes that the coefficients depend on : each quantile level gets its own line. The estimate is the minimizer of the average pinball loss over the sample,
Compare this to the least-squares objective, which is a smooth quadratic in and, for a full-column-rank design, admits the mathematical solution that we derived in ordinary least squares. Here the objective is a sum of piecewise linear functions of . It is convex (a sum of convex functions is convex) but it has kinks wherever a residual is exactly zero, and some optima have zero residuals. Flat sets of optimal coefficients can also contain points with no zero residuals. At a kink the derivative does not exist, so "set the gradient to zero and solve" does not work. We need the machinery of convex optimization.
The standard route is to convert the problem into a linear program, which we can then hand to a mature solver. The trick is to split each residual into its positive and negative parts. Define, for every observation, the positive and negative parts of the residual:
where:
- : the observed response for the -th observation
- : the fitted quantile at the -th predictor vector
- : the positive part of the residual, nonzero only when the observation lies above the fit
- : the negative part of the residual, nonzero only when the observation lies below the fit
Both are non-negative, and their difference reconstructs the signed residual: . In the linear program we drop the max definitions and treat and as the unknowns; the optimal solution automatically sets at most one of the pair strictly positive, since subtracting from both preserves their difference and lowers the cost by . Now check that the pinball loss can be written as a weighted sum of them. Note that if then and , while if then and . If the residual is positive then equals it, , and
If the residual is negative then , , and
using in the middle step. Either way the identity holds, and the identity is linear in the unknowns . That is precisely why the problem becomes a linear program: we minimize a linear function subject to linear constraints and non-negativity.
Written out in full, for a fixed we solve
where:
- : the coefficient vector, unrestricted in sign
- : the positive and negative parts of the -th residual, both constrained to be non-negative
- : the target quantile level
- : the -th predictor vector, including the intercept entry
- : the -th observed response
To pass this to a solver we stack everything into one vector. Let be the design matrix whose -th row is , let denote the identity matrix, let be a column of ones, let be a column of zeros, and let be the stacked unknown vector defined below. Collect the unknowns as . Then the program reads
subject to the equality constraint and the variable-bound restrictions
where:
- : the stacked vector of unknowns, of length
- : the linear cost vector
- : the design matrix
- : the identity matrix
- : the observed response vector
The constraint is the residual decomposition in matrix form, and enforces non-negativity of the split residuals.
Reading the block structure: the first block produces the fitted values, adding and subtracting reconciles them with the observed , and the cost vector puts weight on positive residuals (observations above the fitted line, that is, under-predictions) and weight on negative residuals (observations below the fitted line, that is, over-predictions). The single equation per observation is exactly the residual decomposition we derived. The problem has unknowns and equality constraints. That is larger than a least-squares solve. The two identity blocks contain only nonzero entries; at fixed predictor count the block matrix becomes sparse as grows, and a sparse representation lets solvers exploit this structure.
The dual shows how the fitted score limits sensitivity to extreme responses at fixed predictors. The dual of the program above is
where:
- : the dual variable vector, one multiplier per observation
- : the dual multiplier for the -th observation, confined to the interval
- : the observed response vector
- : the design matrix
Each observation gets a multiplier that is capped between and . At the solution, for observations with positive residual (points above the fitted line) and for observations with negative residual (points below the fitted line), with taking any value in when the residual is exactly zero. The constraint is the first-order condition: the fitted line is positioned so that the signed, capped residuals balance against every column of the design matrix. Every multiplier is confined to the interval , whose bound on the magnitude is . Because is bounded independently of , an extreme response cannot push its own multiplier beyond this cap. The equilibrium condition balances the capped scores against the design columns; it does not guarantee a bound on finite-sample coefficient changes.
For the intercept column, , stationarity gives . Let , and . At nonzero residuals the dual values are fixed at or ; at zero residuals they may take any value in . The available zero-residual values balance the intercept precisely when
Here counts negative residuals, counts ties at the fitted value, and is the target count. This is the same counting inequality derived for a sample quantile. It does not require exactly a fraction of residuals to be negative. The full vector condition also needs valid zero-residual multipliers that satisfy . We will read those multipliers from the LP result rather than treating an arbitrary endpoint of each subgradient interval as an ordinary gradient.
Mathematical properties
These properties are not decorative. They tell us what quantile regression preserves, what it gives up, and where its finite-sample behavior can differ from the population ideal.
- Monotone equivariance. Population conditional quantiles commute with continuous strictly increasing transformations on the response domain. A selected empirical order statistic has the same property. A general linear quantile-regression estimator need not commute with nonlinear transformations because the transformed function may leave the linear model family.
- Median reduction. At the pinball loss is half the absolute error, so the estimator is least absolute deviations regression. For independent Laplace errors centered at zero with a common fixed positive scale, its regression coefficients are maximum likelihood estimates.
- No ordering guarantee across . Because each is optimized separately, and for are not constrained to produce ordered fitted values at any given . Population quantiles are ordered. Appropriate consistency assumptions can recover that order in the limit, but separate finite-sample fits impose no ordering constraint.
- Asymptotic normality. For independent identically distributed rows, a correctly specified linear conditional quantile, bounded predictors with nonsingular second-moment matrix, and a positive continuous conditional density with adequate local smoothness near that quantile, the usual regular quantile-regression limit applies. Define the density-weighted design moment and the plain design moment by
where:
- : the conditional density of given , evaluated at the quantile
- : the true conditional -quantile function
- : a predictor vector drawn from the population distribution (the expectation is taken over )
- : the density-weighted design moment; density affects precision through the full sandwich covariance, together with the predictor design and
- : the unweighted design moment
Then as , where is the variance of the pinball-loss score, is the sandwich matrix (bread times meat times bread), and and are defined immediately above. The density term records the local information near the quantile. At fixed and predictor distribution, multiplying all conditional densities at the quantile by the same factor divides the asymptotic covariance by ; more general precision comparisons depend on the whole density-weighted design. In distributions such as the normal example, low tail density can increase this covariance; the formula does not imply that every distribution has larger variance at more extreme levels.
- Under these regular population conditions, the influence function is bounded as varies at a fixed predictor vector. It need not be bounded as varies: high-leverage predictors multiply the capped scores. This population statement does not bound every finite-sample coefficient change.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!