Quantile regression: choose which errors cost more
分位数回归
Derive asymmetric loss and solve a small two-parameter model exactly, keeping ties and quantile crossing visible.
quantile-regressionAsk about a tail, not only an average
A fictional machine produces an output y as a setting x changes. Five recorded pairs are (0,0), (1,1), (2,2), (3,3) and (4,10). Four follow y=x; the last is much higher. A mean model and an upper-quantile model answer different questions. Neither becomes the other merely by changing the label on a plot.
Quantile regression targets a chosen position in the conditional response distribution. A conditional median describes its middle; a 0.9 quantile describes an upper threshold. A fitted quantile is a response value, not a probability, and fitting it does not make the threshold correct for future data.
At quantile level τ, predicting below an observed value incurs weight τ; predicting above it incurs weight 1−τ. At τ=0.9, underprediction by one unit costs nine times as much as overprediction by one unit. The Koenker–Bassett original paper, §3 formulates regression quantiles through this asymmetric absolute loss.
The asymmetry chooses the quantile
For residual u=y−q, define the pinball or check loss:
Both branches are nonnegative. At τ=1/2 this is half the absolute residual, giving the same minimizers as least absolute deviations. Squared loss, by contrast, targets the mean when the relevant expectation exists.
For a fixed input x and a response with finite conditional absolute expectation, minimizing expected pinball loss over a free scalar q gives the quantile condition:
Where the conditional CDF is continuous, the derivative of the expected loss with respect to q is F(q)−τ: increasing q reduces the cost while too much mass lies above it, and increases the cost after passing the target. With atoms, the left and right derivatives give the inequality instead. A quantile need not be unique. For two equally likely values 0 and 2, every number in [0,2] minimizes median loss.
Linear quantile regression restricts that scalar to a linear function of features. Our one-feature model includes an intercept:
If the true conditional quantile is curved, the best line is a restricted approximation. There is no requirement that exactly τ of a finite sample lie strictly below a fitted line: observations can lie on it, and conditioning matters. An upper conditional quantile also differs from taking one upper quantile of all responses while ignoring x.
The objective is convex and piecewise linear, usually nondifferentiable where a residual is zero. Writing each residual as uᵢ−vᵢ with uᵢ,vᵢ≥0 gives a linear program:
For an optimal residual decomposition, positive and negative parts do not overlap, because removing the same positive amount from both lowers the cost. The factor 1/n does not change minimizers. This is one route to practical solvers; the fixed statsmodels 0.14.4 API instead documents an iteratively reweighted least-squares implementation. The exact small solver below uses neither library nor iteration.
Check every relevant corner in two dimensions
With an intercept and at least two distinct x values, the design has rank two. For , an optimal solution exists among lines through two observations with distinct x. The original paper’s Theorem 3.1 gives the more general full-rank result and describes the full solution set as the convex hull of the optimal basic solutions. Here, each pair solves two linear equations, so we can enumerate these candidates exactly.
The geometric reason is also useful: the zero-residual lines partition coefficient space into regions where the loss is linear. Full column rank and strictly positive weights make sublevel sets bounded. A minimum can be attained at a corner, at an intersection of two independent zero-residual lines. Convexity alone would not imply that an arbitrary list of candidate lines contains an optimum; the rank and corner argument matters.
This complete Python 3.10+ program accepts integers or Fraction values, including for τ. It rejects floats, booleans, malformed rows, τ=0 or 1, and a constant x design. Duplicate rows are allowed and contribute their full multiplicity. It returns every distinct optimal candidate in vertices, and chooses the lexicographically smallest (intercept,slope) for prediction. That is an explicit tie convention, not a uniqueness claim. predict expects an unchanged result from fit and allows empty input.
from fractions import Fraction as F
from itertools import combinations
def number(value):
if type(value) not in (int, F):
raise ValueError('Use integers or Fractions, not floats or Booleans.')
return F(value)
def prepare(rows):
if type(rows) not in (list, tuple) or not rows:
raise ValueError('Provide a nonempty list or tuple of (x, y) rows.')
result = []
for row in rows:
if type(row) not in (list, tuple) or len(row) != 2:
raise ValueError('Each row must contain x and y.')
result.append(tuple(map(number, row)))
return tuple(result)
def pinball(residual, tau):
# Internal helper; residual is rational and 0 < tau < 1.
return tau * residual if residual >= 0 else (tau - 1) * residual
def fit(rows, tau=F(1, 2)):
data = prepare(rows)
tau = number(tau)
if not 0 < tau < 1:
raise ValueError('tau must be strictly between zero and one.')
if len({x for x, _ in data}) < 2:
raise ValueError('Intercept plus slope requires two distinct x values.')
candidates = set()
for (x1, y1), (x2, y2) in combinations(data, 2):
if x1 != x2:
slope = (y2 - y1) / (x2 - x1)
candidates.add((y1 - slope * x1, slope))
best, vertices = None, []
for intercept, slope in candidates:
cost = sum(pinball(y - intercept - slope * x, tau) for x, y in data)
if best is None or cost < best:
best, vertices = cost, [(intercept, slope)]
elif cost == best:
vertices.append((intercept, slope))
vertices = tuple(sorted(vertices))
return dict(beta=vertices[0], vertices=vertices,
mean_loss=best / len(data), tau=tau,
candidate_count=len(candidates))
def predict(model, xs):
# model is an unchanged result from fit; no interpolation between quantiles.
if type(xs) not in (list, tuple):
raise ValueError('Prediction features must be a list or tuple.')
intercept, slope = model['beta']
return tuple(intercept + slope * number(x) for x in xs)
if __name__ == '__main__':
rows = ((0, 0), (1, 1), (2, 2), (3, 3), (4, 10))
for tau in (F(1, 4), F(1, 2), F(3, 4)):
model = fit(rows, tau)
print('tau / beta / mean loss:', str(tau),
tuple(map(str, model['beta'])), str(model['mean_loss']))
tie = fit(((0, 0), (0, 2), (1, 0), (1, 2)))
print('optimal vertices:', tuple(tuple(map(str, b)) for b in tie['vertices']))
print('chosen prediction at 1/2:', str(predict(tie, (F(1, 2),))[0]))
Actual output:
tau / beta / mean loss: 1/4 ('0', '1') 3/10
tau / beta / mean loss: 1/2 ('0', '1') 3/5
tau / beta / mean loss: 3/4 ('0', '5/2') 9/20
optimal vertices: (('0', '0'), ('0', '2'), ('2', '-2'), ('2', '0'))
chosen prediction at 1/2: 0
For the five original points, the median line is y=x. Its only nonzero residual is 6, so its mean pinball loss is (6/2)/5=3/5. At τ=3/4, y=2.5x is selected. The nonzero residuals are −1.5, −3 and −4.5; their total weighted loss is 9/4, or 9/20 per row. The upper fit need not minimize the median objective.
The second dataset has responses 0 and 2 at both x=0 and x=1. Any line whose values at both settings lie in [0,2] is optimal for median loss. Four extreme coefficient pairs are printed. Their convex combinations are also optimal, including the constant line y=1. The returned prediction zero is a chosen representative from this set.
There are O(n²) candidate lines, each scored on n rows: O(n³) rational arithmetic operations and O(n²) stored candidates/solutions. Prediction of m features costs O(m+1) operations and output storage. Exact rational bit costs can grow; this exhaustive two-parameter method is intended for small examples. It is not a scalable replacement for a linear-programming or other specialized solver.
A fitted tail is not a coverage certificate
The example lines cross when extrapolated left of x=0: at x=−1, the fitted 0.75 quantile is −2.5, below the fitted median −1. Separately fitting quantiles imposes no ordering constraint. Crossing can also arise within a prediction domain on other data, so check it where the model will be used.
Quantile regression can describe changing conditional spread without specifying a Gaussian error law, but it still relies on an appropriate feature representation and sampling process. Extreme quantiles have less tail information. Missing groups, distribution changes and selective observation can spoil calibration. Neither a low training pinball loss nor an apparently plausible 90% curve proves conditional 90% coverage.
Absolute rather than squared residuals reduce the growth of the response-side penalty. This does not grant immunity to outliers: a high-leverage x can still strongly influence a slope. Compare held-out pinball loss at the same τ, inspect exceedance rates across relevant groups, and report sampling uncertainty. Prediction quantiles, confidence intervals for coefficients and prediction intervals are different objects. This program estimates no uncertainty and imposes no cross-quantile constraints.
Use the asymmetry and the ties
1. At τ=0.9, what are the losses for underprediction by 2 and overprediction by 2?
Answer: The residuals are 2 and −2, giving losses 1.8 and 0.2. The larger underprediction cost pushes the target upward; neither number is a probability.
2. For responses 0 and 2 with equal weights, which constants minimize median loss?
Answer: Every q in [0,2]. The total loss there is 1; moving outside the interval increases it. A routine that returns one endpoint and one that returns the midpoint can both solve the same unregularized objective.
3. Why does the program reject a constant x column, even though a median response still exists?
Answer: The intercept and slope are not separately identified, and there are no two distinct-x observations to define a candidate corner. An intercept-only solver would be appropriate. This is the stated two-parameter algorithm’s boundary, not nonexistence of response quantiles.
4. At x=−1, the example predicts median −1 and upper quartile −2.5. Does relabeling or sorting those numbers validate the fitted models?
Answer: No. The crossing exposes a limitation of separate fits and extrapolation. Sorting can enforce pointwise order as a postprocessing choice, but changes the predictions and does not establish conditional coverage. Evaluate the revised procedure on independent data.
Read the objective before comparing implementations
Koenker and Bassett’s paper appeared in Econometrica, January 1978. Its §3 defines the optimization problem; Theorem 3.1 supports the finite corner construction used here. The historical robustness motivation does not make every design or tail estimate robust. Only the cited original sections and publication header were used, not the paper’s full asymptotic analysis.
The fixed statsmodels documentation identifies median regression as the LAD special case and states its IRLS solver approach. Library tolerances and inference options therefore differ from this chapter’s exact enumeration. No upstream program, data or results table was copied or executed. Continue with robust regression, linear regression and generalization to compare the target, estimator and evidence of future performance.
Make a prediction, then check
At x=−1 the example predicts median −1 and upper quartile −2.5. What does this show?
Learning objectives
- Explain conditional quantiles, asymmetric loss and nonunique quantiles.
- Express the linear objective as an LP and explain when full-rank basic-solution enumeration applies.
- Run the exact two-parameter solver and check multiple optima, crossing and limits of out-of-sample coverage.
Prerequisites & connections
Explore related knowledge →References
- Regression Quantiles
Roger Koenker and Gilbert Bassett, Jr. · 1978 - statsmodels 0.14.4 — QuantReg
statsmodels developers
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Five author tests pass: all returned vertices across 18 fits have exact dual-feasibility and primal-dual equality certificates, with additional rational coefficient probes. Certificates establish global optimality over coefficient space, not a second copy of candidate fitting.
- Checked four-vertex nonuniqueness and optimal midpoints, replication/order invariance, response scaling/affine shift, negation with complementary tau, extrapolation crossing, 100-digit integer/rational ranges, rejected inputs and model immutability. Full stdout matches both languages.
- Both locales align on 4 displays, 6 stable anchors and 4 answered exercises; strict MDX/KaTeX and actual React HTML pass. Explicit conditions: 0<tau<1, full column rank, finite conditional absolute expectation, two-parameter enumeration and rational bit costs. No outlier-immunity or conditional-coverage promise.
- Ran all five author tests successfully. Independently constructed the three-dimensional primal epigraph as the maximum of all pinball supporting affine functions, solved plane triples using exact rational elimination, and checked every halfspace. Fifteen small fits at tau 1/4, 1/2 and 3/4 matched all optimal coefficient vertices, the selected lexicographic vertex and mean loss. This does not reuse the pair-line algorithm or author dual certificates.
- Read complete bilingual prose, code, exercises and metadata. Checked residual sign, conditional-quantile atom/nonuniqueness condition, full-rank and interior-tau requirements, coercivity/basic solutions, convex-hull interpretation, crossing example, repeated-row multiplicity and exact-input validation. Cubic arithmetic/quadratic storage bounds explicitly exclude rational bit costs.
- Strict MDX/KaTeX evaluation and actual React HTML passed for both languages: four display equations, six stable anchors and four answered exercises. All rendered math annotations match across languages; author test verifies identical code and stdout. Final five file hashes match the frozen manifest.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points existing topics to their complete articles, retaining pending directory entries. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
- Publication-format correction: algorithm articles use the existing concept template; kind changed from algorithm to concept. Prose, mathematics and program unchanged.
- Corrected review source keys: both URLs exactly match the read sources; aligned the independent reviewer alias IDs with canonical metadata IDs without changing citations or locators.
Source locations checked:
- Regression Quantiles · Root web read original scan at Sydney URL: header lines 1–5 and 15–24 identifies Econometrica 46(1), January 1978, pp.33–50; section 3 lines 248–305, printed pp.38–39, defines asymmetric loss for 0<tau<1 and full-rank optimal basic solutions/convex hull. OCR mathematical symbols are imperfect: formulas and the two-dimensional derivation were reconstructed and verified algebraically, not copied from OCR. Berkeley copy returned 502. No complete paper, visual scan audit or asymptotic proof claimed.
- statsmodels 0.14.4 — QuantReg · Root actually read official v0.14.4 QuantReg API via web, lines 107–146: IRLS solver, model inputs, q=0.5 LAD special case; line 231 marks Oct 03 2024 update. No package execution, copied code, data, confidence intervals or results tables.
- Regression Quantiles · Actually read university-hosted 19-page original scan text, including JSTOR cover metadata (Econometrica 46(1), January 1978, pp. 33–50) and §3 printed pp. 38–39 (PDF pages 7–8). Theorem 3.1 assumes full column rank and describes existence of an optimal basic regression quantile and the convex hull of optimal basic solutions. OCR symbols were imperfect; theorem prose and article algebra were checked separately. No full asymptotic or visual scan audit claimed.
- statsmodels 0.14.4 — QuantReg · Actually read pinned 0.14.4 class/API page: IRLS description, endog/exog, q=.5 LAD note and fit method; page update October 3, 2024. No third-party library code was copied or executed.
Related topics