AI Wiki中文/EN

Robust regression: bounded residual scores and their limits

稳健回归

Solve a small Huber model exactly, compare outliers with leverage points, and inspect the full minimizing interval and its dual certificate.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

One extreme reading can move the whole fit

Five fictional calibration readings are 0, 1, 1, 2 and 100. We fit one common level. Ordinary least squares chooses their mean, 104/5=20.8. Four readings are near one, yet the estimate sits far above them. Replacing 100 by 10000 moves the mean to 2000.8.

With the Huber loss and a cutoff of one response unit, the fitted level is 4/3 in both cases. The remote observation still contributes to the fit; making its already large residual a hundred times larger no longer increases that contribution. This is a constructed illustration of a specified loss, not proof that the remote reading is erroneous.

Robust regression asks how a fitted relationship changes when some observations depart from its intended data model. A method needs a stated kind of departure: extreme responses, unusual predictor values, heavy tails and recording errors need not affect it in the same way. This chapter develops Huber M-estimation, then uses a high-leverage counterexample to show the boundary of its protection. Official scikit-learn guide, version 1.7.2, §1.1.16.4.

Bound the residual score, not the entire observation

Let r be predicted response minus observed response. For a fixed cutoff c>0, define the Huber loss and its derivative:

ρc(r)={12r2,∣r∣≤c,c∣r∣−12c2,∣r∣>c,ψc(r)=ρc′(r)=max⁡(−c,min⁡(c,r)).\rho_c(r)=\begin{cases}\tfrac12r^2,&|r|\le c,\\c|r|-\tfrac12c^2,&|r|>c,\end{cases}\qquad\psi_c(r)=\rho_c'(r)=\max(-c,\min(c,r)).

The loss and first derivative join continuously at ±c. Near zero, the loss is quadratic; beyond the cutoff, it grows linearly. The derivative is bounded, but the loss itself is not. An extreme residual is downweighted, not deleted. The official statsmodels Huber criterion uses this half-square normalization. Version 0.14.4, rho definition.

An M-estimator minimizes a sum of chosen losses. For an ordinary regression vector β, fixed residual scale σ and design row xᵢ, its estimating equation contains xᵢψ((xᵢᵀβ−yᵢ)/σ). Bounding ψ controls the residual part; it does not bound xᵢ. The term “influence” must therefore say what is being perturbed. A bounded residual score alone is not a claim of uniformly bounded statistical influence under arbitrary predictor contamination.

The executable model has one unknown coefficient β and known numeric multipliers aᵢ. It predicts aᵢβ. Setting every aᵢ=1 gives location estimation; using varying aᵢ gives a line through the origin. It does not fit a separate intercept and slope together:

J(β)=1n∑iρc(aiβ−yi),nJ′(β)=G(β)=∑iaiψc(aiβ−yi).J(\beta)=\frac1n\sum_i\rho_c(a_i\beta-y_i),\qquad nJ'(\beta)=G(\beta)=\sum_i a_i\psi_c(a_i\beta-y_i).

For a single location observation, the contribution to G has magnitude at most c. For a regression observation it is at most |aᵢ|c. That distinction explains why a very large predictor can dominate even with clipped residuals. No normal-error assumption is needed to define or minimize this convex objective; statistical guarantees would require additional assumptions.

The cutoff has units

Here c is measured in response units and is fixed by the caller. If residuals are standardized by a fixed positive scale σ and the dimensionless cutoff is κ, the corresponding raw cutoff is c=κσ. Changing the units of all responses requires changing c too. The code neither estimates σ nor adds a coefficient penalty.

This differs from scikit-learn’s HuberRegressor, which jointly fits a residual scale and uses an L2 penalty. Its epsilon and this program’s c are not interchangeable parameters. A library default is not a universal cutoff for arbitrary data. Version 1.7.2 API, objective and scale.

Why the exact minimizers form an interval

G is continuous and nondecreasing. Between residual breakpoints, every unclipped contribution has slope aᵢ² and every clipped contribution has slope zero. If at least one aᵢ is nonzero, its limiting signs are:

lim⁡β→−∞G(β)=−c∑i∣ai∣<0,lim⁡β→+∞G(β)=c∑i∣ai∣>0.\lim_{\beta\to-\infty}G(\beta)=-c\sum_i|a_i|<0,\qquad\lim_{\beta\to+\infty}G(\beta)=c\sum_i|a_i|>0.

Therefore the zero set is a nonempty bounded closed interval, possibly a single point. Convexity makes it exactly the set of global minimizers. Huber loss is not globally strictly convex: with location readings −10 and 10 and c=1, every level in [−9,9] minimizes the loss. Reporting one value without acknowledging that interval would hide nonuniqueness.

Find the whole interval without a stopping tolerance

The score changes slope only when a nonzero multiplier’s residual reaches ±c. Collect those rational breakpoints, sort them and evaluate G at each:

B={yi−cai,yi+cai:ai≠0},β∗=bL−G(bL)bR−bLG(bR)−G(bL).B=\left\{\frac{y_i-c}{a_i},\frac{y_i+c}{a_i}:a_i\ne0\right\},\qquad\beta^*=b_L-G(b_L)\frac{b_R-b_L}{G(b_R)-G(b_L)}.

If some breakpoints have score zero, the first and last are the interval endpoints. Otherwise exactly one adjacent pair brackets a sign change, and G is affine between them; the displayed interpolation gives its unique root. Negative multipliers are handled by sorting both breakpoints. Rows with aᵢ=0 contribute a constant loss and no score; all-zero multipliers are rejected because they identify no coefficient.

The complete Python 3.10+ program accepts nonempty list/tuple collections of (multiplier, response) pairs. Values and cutoff are integers or exact Fraction objects; Booleans and floats are rejected. It returns the complete minimizing interval, its midpoint as a deterministic chosen coefficient, the average loss and the unnormalized score. No iteration budget, approximate convergence status or floating-point tolerance is involved.

# Python 3.10+; one coefficient only, fixed Huber cutoff, exact fractions.
from fractions import Fraction as F


def exact(value):
    if type(value) not in (int, F):
        raise ValueError('use integers or Fractions, not Booleans or floats')
    return F(value)


def sequence(value):
    if type(value) not in (list, tuple):
        raise ValueError('expected list or tuple')
    return value


def prepare(rows):
    data = []
    for row in sequence(rows):
        if len(sequence(row)) != 2:
            raise ValueError('row: (known multiplier, response)')
        data.append(tuple(exact(v) for v in row))
    if not data or not any(a for a, y in data):
        raise ValueError('need a nonempty sample and a nonzero multiplier')
    return tuple(data)


def clip(r, c):
    return max(-c, min(c, r))


def rho(r, c):
    # Internal scalar helper with c > 0 and exact r, c.
    return r*r/2 if abs(r) <= c else c*abs(r)-c*c/2


def score(data, beta, c):
    # Unnormalized derivative; divide by n for the average-loss gradient.
    return sum((a*clip(a*beta-y, c) for a, y in data), F())


def fit(rows, cutoff=1):
    data, c = prepare(rows), exact(cutoff)
    if c <= 0:
        raise ValueError('cutoff must be strictly positive')
    knots = sorted({(y+s*c)/a for a, y in data if a for s in (-1, 1)})
    values = tuple(score(data, b, c) for b in knots)
    zeros = [b for b, value in zip(knots, values) if value == 0]
    if zeros:
        lower, upper = zeros[0], zeros[-1]
    else:
        j = next(j for j, value in enumerate(values) if value > 0)
        left, right = knots[j-1], knots[j]
        lower = upper = left-values[j-1]*(right-left)/(values[j]-values[j-1])
    beta = (lower+upper)/2
    loss = sum((rho(a*beta-y, c) for a, y in data), F())/len(data)
    return dict(coefficient=beta, minimizers=(lower, upper), loss=loss,
                score=score(data, beta, c), cutoff=c)


def least_squares(rows):
    data = prepare(rows)
    return sum((a*y for a, y in data), F())/sum(a*a for a, y in data)


def predict(model, multipliers):
    # model is an unchanged result of fit; this is not a generic model loader.
    return tuple(exact(a)*model['coefficient'] for a in sequence(multipliers))


if __name__ == '__main__':
    for extreme in (100, 10000):
        location = tuple((1,y) for y in (0,1,1,2,extreme))
        model = fit(location)
        print('extreme / OLS / Huber:', extreme, least_squares(location), model['coefficient'])
    flat = fit(((1,-10),(1,10)))
    print('flat minimizers / chosen:', tuple(map(str,flat['minimizers'])), flat['coefficient'])
    leverage = ((1,1),(2,2),(100,1000))
    fitted = fit(leverage)
    print('leverage OLS / Huber:', least_squares(leverage), fitted['coefficient'])
    print('leverage score:', fitted['score'])
    print('predictions at 1,2:', tuple(map(str,predict(fitted,(1,2)))))
    print('empty prediction:', predict(fitted,()))

Actual output:

extreme / OLS / Huber: 100 104/5 4/3
extreme / OLS / Huber: 10000 10004/5 4/3
flat minimizers / chosen: ('-9', '9') 0
leverage OLS / Huber: 6667/667 99997/10000
leverage score: 0
predictions at 1,2: ('99997/10000', '99997/5000')
empty prediction: ()

predict accepts an unchanged fit result and a list/tuple of known multipliers. It does not update the coefficient; empty prediction returns an empty tuple. Inputs are copied, so later edits to the caller’s lists do not alter the fitted result.

There are at most 2n breakpoints. This transparent implementation sorts them in O(n log(n+1)) comparisons and recomputes an O(n) score at each, giving O(n²+n log(n+1)) rational arithmetic work and O(n) stored values. Prediction of m multipliers takes O(m+1) work and output space. These are operation/storage counts, not bit-cost bounds: exact fractions with large numerators and denominators require more time and memory. More efficient sweeps are possible; this program favors an inspectable calculation for a small one-parameter model.

An independent certificate of global optimality

The tests do not merely repeat the breakpoint algorithm. Huber loss has this scalar dual representation:

ρc(r)=max⁡∣u∣≤c(ur−12u2),J(β)≥1n∑i(−uiyi−12ui2)if ∣ui∣≤c (∀i), ∑iaiui=0.\rho_c(r)=\max_{|u|\le c}\left(ur-\tfrac12u^2\right),\qquad J(\beta)\ge\frac1n\sum_i\left(-u_i y_i-\tfrac12u_i^2\right)\quad\text{if }|u_i|\le c\ (\forall i),\ \sum_i a_i u_i=0.

The scalar maximum occurs at clipped r. For any feasible u, summing the inequality cancels β, giving a lower bound valid for every coefficient. The tests build feasible dual values at the returned endpoints and midpoint and verify equality with a separately evaluated primal loss. Equality certifies global optimality. Convexity covers the interval between the endpoints; the score argument above establishes that no other minimizers lie outside it.

A high-leverage point can still set the slope

Consider the line-through-origin observations (a,y)=(1,1),(2,2),(100,1000). The first two lie on slope one. With c=1, the Huber optimum is 99997/10000≈9.9997, close to the slope demanded by the third point. At that solution, the first two clipped score contributions are 1 and 2; the third is 100×(−0.03)=−3. They cancel exactly.

Thus Huber fits this high-leverage contamination poorly relative to the intended slope-one relationship. The small remaining residual at the influential point does not establish its reliability. The example is specific to this fixed one-parameter design and cutoff; it is not a ranking of robust methods across datasets.

A large residual is not automatically a data error. It can reveal a missing regime, a wrong functional form or a genuinely rare outcome. Robust fitting should not become an excuse to discard inconvenient observations. Inspect provenance, predictor geometry and the intended loss; compare performance on independent data and on the departures that matter for the application.

Other choices include absolute-loss regression, methods that select a consensus subset, and estimators designed for contaminated predictors. Their assumptions and objectives differ. Huber’s positive tail weights do not reject a point outright; redescending losses can do that, but may introduce nonconvex optimization. This program does not implement those methods or certify any contamination fraction.

Iteratively reweighted least squares is a common numerical route to M-estimation. For fixed c, Huber uses weight one within the cutoff and c/|r| outside, with weight one at r=0. The weights depend on the current residuals, so one weighted fit is generally not the final answer. Our exact one-dimensional solver avoids that iteration; it is not a replacement for a multivariable robust-regression library. statsmodels 0.14.4, IRLS weights.

State what was made less sensitive

  1. Why does changing the remote location reading from 100 to 10000 leave the Huber result unchanged here? Was that observation removed?

Answer: At β=4/3 its residual remains far beyond c=1, so its score contribution stays −1. The other four contributions still balance it. Its loss changes and its score is nonzero; it was not removed. OLS instead uses an unbounded residual score and its mean changes from 104/5 to 10004/5.

  1. What are all the Huber location estimates for readings −10 and 10 with c=1? Why does the program print zero?

Answer: Every value in [−9,9] has zero total score and the same minimum loss. Zero is the midpoint chosen by this interface, not a uniquely identified estimate. Outside that interval the objective increases.

  1. Responses are converted to units ten times larger while multipliers stay unchanged. How should c and the fitted interval change?

Answer: Multiply c and both interval endpoints by ten. The same standardized residual pattern is preserved, and the raw Huber loss scales by one hundred. Keeping c fixed would define a different robust objective.

  1. Why does clipping the residual score not protect the slope in the (1,1),(2,2),(100,1000) example?

Answer: Each slope score is aᵢψ(rᵢ), so the third observation multiplies its residual contribution by 100. The optimum near 10 balances that term against the first two, despite being far from their slope-one relationship. Residual robustness and resistance to predictor contamination are different requirements.

Match the loss, scale and optimization problem

The versioned statsmodels 0.14.4 Huber criterion and weight documentation specify the half-square loss and the corresponding IRLS weights. Its broader robust-model guide lists several M-estimation norms and separates scale estimation. Those descriptions guide terminology here; no upstream implementation, dataset or output table is copied.

The scikit-learn 1.7.2 guide and HuberRegressor API describe a different optimization problem with jointly fitted scale and an L2 penalty. Its response-scaling convention is the reason we explicitly identify this program’s fixed, dimensioned cutoff. Neither package was executed for the comparisons above. An attempted original Huber-paper PDF retrieval failed, so no historical theorem or archival reading is attributed to that unread document.

All calibration data, the leverage example, exact solver and exercises are original. Tests combine global dual certificates, interval boundaries, unit transformations, zero multipliers, exact loss joins and the executed failure examples. Continue with linear regression for least squares and the planned quantile regression for a different loss and prediction target.

Make a prediction, then check

Huber clips each residual score to a fixed magnitude. Does that guarantee resistance to arbitrarily large predictor values?

Choose one answer

Learning objectives

  • Explain why OLS is sensitive to extreme responses and distinguish a bounded Huber residual score from protection against leverage.
  • Solve a fixed-cutoff one-parameter Huber problem exactly, including its full minimizing interval and nonunique fits.
  • Check global optimality with a dual certificate and state scale, units, contamination and implementation limits.

Prerequisites & connections

Explore related knowledge →

References

  1. statsmodels 0.14.4 — HuberT criterion and IRLS weights
    statsmodels developers
  2. scikit-learn 1.7.2 — Huber regression and HuberRegressor
    scikit-learn contributors

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.

  • Eight tests passed. Fifty-four small signed/zero-multiplier cases yield 162 exact Fenchel dual certificate comparisons at returned endpoints and midpoints. A positive-part primal formula is independent of the code’s rho branch; dual feasibility and equality certify global optimality. The full zero-interval argument is separately proved rather than inferred from finite probes.
  • Executed location outliers 100, 10000 and 10^100 retain Huber level 4/3 while OLS follows the changing mean. Verified flat minimizers [-9,9], negative-multiplier singleton, constant-loss zero rows, loss continuity, large-cutoff OLS agreement, tiny exact fractions, response-unit and parameter transformations, repetitions, no mutation and empty predictions. Seven malformed datasets, five cutoffs and three prediction inputs are rejected.
  • Original leverage counterexample returns OLS 6667/667 and Huber 99997/10000 with exact score zero: the latter remains far from the first two observations’ slope 1. Fixed raw cutoff, no fitted scale/penalty, single unknown coefficient, complete minimizer interval and midpoint convention are explicit. No general contamination fraction or multivariable-library equivalence claimed.
  • Both languages have six stable anchors, five identical display formulas, identical full Python/seven output lines and four answers. Strict MDX/KaTeX and actual React HTML pass; the dual lower-bound formula explicitly states both box feasibility and score balance. Reread under pinned Humanizer guidance. Tests load code/output through article_text. AI author checks only, review written pending independent cross-review; no repository, browser or whole-site work.
  • All eight author tests passed under Python 3.12.4. Read complete bilingual MDX, standalone program, tests and metadata. Final five hashes match sha256.json; the complete Python and seven-line output agree between languages and standalone example.
  • Independent reference enumerates each residual’s negative-tail, central or positive-tail region, constructs linear feasibility inequalities in the coefficient, and minimizes that region’s quadratic/linear polynomial directly. It neither collects/evaluates score breakpoints nor uses the author’s Fenchel certificates. Seventy-two complete fit dictionaries match across 36 small cases and sign/reversal variants; 420 feasible polynomial regions were checked. Optimal regional intervals merge without gaps, giving the full minimizing interval.
  • Checked C1 loss joins, monotone continuous score and opposite finite tail limits under at least one nonzero multiplier; these establish a nonempty bounded global-minimizer interval. Verified zero-score breakpoint endpoints versus an interior affine root, negative/zero multipliers, flat minima and the midpoint convention. The scalar dual lower bound includes both box feasibility and score balance, and its equality proves global optimality.
  • Verified fixed-cutoff response units, distinction from fitted-scale packages, bounded residual score versus leverage, exact location and leverage counterexamples, full interval versus one chosen coefficient, input rejection/preservation and empty prediction. O(n²+n log(n+1)) fit operation count, O(n) storage and O(m+1) prediction bounds cover their stated valid domains; exact-fraction bit costs are explicitly separate.
  • Independently compiled strict MDX/KaTeX and rendered actual React HTML. Both languages have five identical displayed TeX formulas, six required anchors and four answers. Decoded MathML annotations match the formulas; no KaTeX error or stray Markdown emphasis outside code. Formula conditions, program, output and exercises correspond across languages.
  • 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.

Source locations checked:

  • statsmodels 0.14.4 — HuberT criterion and IRLS weights · Actually opened /v0.14.4/rlm.html lines 137–139 and 168–205 on M-estimation norms and separate scale functions; HuberT.html lines 100–128; HuberT.rho.html lines 83–99 for the exact half-square/linear criterion; and HuberT.weights.html lines 83–101 for weights 1 or t/abs(z). The linked psi subpage returned Cache miss; the derivative here is derived from rho, not claimed read there. No statsmodels source code or model fitting executed.
  • scikit-learn 1.7.2 — Huber regression and HuberRegressor · Actually opened official 1.7.2 guide through web, lines 845–860, including its concomitant-scale objective and differently normalized loss. Read the same-version HuberRegressor API lines 618–646: fitted coefficients/intercept/scale, scaling response versus features, positive tail influence and L2 penalty. Did not adopt the guide’s default-efficiency number as an unconditional guarantee. Original Huber 1964 PDF attempts returned an iframe/Internal Error or a non-retryable failure, so that paper is neither a reference card nor a claimed historical read.
  • statsmodels 0.14.4 — HuberT criterion and IRLS weights · Independently opened HuberT main card, lines 100–132, and rlm.html, lines 137–139 and 189–209: Huber M-estimation, IRLS methods, separate scale functions and October 3, 2024 update. Direct rho/weights subpage requests failed with non-retryable tool errors. The main card’s source link successfully opened the same-version official _modules/statsmodels/robust/norms.html; actually read HuberT lines 295–380, including rho, psi and weights docstrings and implementations. Independently confirms half-square normalization, continuous clipped derivative and positive tail weights. No library source copied into any artifact or executed.
  • scikit-learn 1.7.2 — Huber regression and HuberRegressor · Independently opened official 1.7.2 guide §1.1.16.4, lines 845–860, and the same-version HuberRegressor API, lines 618–646. Read fitted scale/intercept/coefficients, L2 penalty, nonzero outlier contribution and feature-scale qualification. The chapter correctly distinguishes this from its unpenalized one-coefficient objective with fixed raw cutoff. No default-efficiency claim imported; no scikit-learn execution. The original Huber historical paper is not claimed as read by this review.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.