AI & Machine Learning Master Course — 047. Robust regression
Smartyfy AI & Machine Learning Master Course
Course ID: smartyfy-ai-ml-master-200
Lesson 047: Robust regression
Prerequisites: Lesson 046. Learning outcome: Evaluate estimators that reduce sensitivity to unusual residuals.
1. A large residual can dominate squared error
One parcel may have a duration typed in the wrong unit. Another may genuinely experience an exceptional disruption. Both can create large residuals, but they require different responses. Correct a verified measurement error from an authoritative source; do not erase a legitimate difficult case merely because it damages a score.
Squared error gives rapidly increasing influence to large residual magnitudes. Robust regression changes the fitting criterion or procedure to reduce sensitivity to certain unusual observations. Its usefulness depends on what kind of contamination or heavy-tailed variation is plausible. “Robust” does not mean immune to every outlier, distribution shift, or feature-space anomaly.
2. The Huber compromise
A classical Huber loss with threshold δ uses half the squared residual when |e|≤δ. Beyond that threshold it uses δ times (|e|−δ/2). The pieces meet continuously with matching slopes. Small residuals receive a smooth quadratic treatment, while large residuals grow linearly rather than quadratically.
With δ=1, errors 0.5, 1, 3 produce losses 0.125, 0.5, 2.5. Half-squared loss would assign 4.5 to error 3. The derivative with respect to residual is capped in magnitude at δ, reducing the leverage of a very large vertical error on the optimization. This does not eliminate feature leverage: an extreme input can still affect parameter gradients through its feature value.
Scikit-learn HuberRegressor fits a scale parameter as well as coefficients and an intercept, and uses epsilon on scaled residuals. It also supports an L2 coefficient penalty. Therefore the simple fixed-δ function printed in this lesson illustrates the loss shape; it is not a line-by-line reproduction of that estimator's full scale-adjusted objective.

3. Other robust strategies make different assumptions
Absolute-error regression limits the growth of residual loss but is not a universal remedy for high-leverage inputs. RANSAC repeatedly fits candidate subsets and looks for a sufficiently large set of observations consistent with a model under a residual threshold. It is useful only when that consensus assumption matches the problem.
A RANSAC outlier label means disagreement with the selected model and threshold. It does not prove a record is erroneous. Minority operating regimes may be real and important, so a procedure that focuses on the dominant regime can exclude precisely the cases the application must serve. Inspect omitted cases and define the target population before choosing a robust fitting policy.
Preprocessing also matters. An outlier-sensitive scaler can distort features before the robust estimator receives them. Compare a suitable robust scaling choice when justified, fitting its statistics on training data. Scaling, estimator thresholds, and any removal rules belong inside the development procedure, not in an undocumented cleanup step before evaluation.
4. Evaluate against the population you actually care about
If the intended deployment includes rare disruptions, evaluate on them rather than presenting only clean cases. A robust central predictor can improve typical-case error while underpredicting valid extreme outcomes. Report relevant tail errors and groups alongside the chosen overall metric. The best objective depends on the decision costs established earlier.
Choose robustness hyperparameters using development data and preserve a final assessment. Avoid a circular workflow that labels every badly predicted point an outlier and then removes it from the test score. Any exclusion rule must be justified independently of whether the outcome flatters the model and described in the evaluation report.
CPU lab: one deliberately corrupted training outcome
The example creates ten nearly linear training observations, then adds thirty units to one target at x=5. Three separate validation inputs follow the clean known formula. This deliberately constructed contamination setup favors robustness; it does not represent every real parcel population.
Using NumPy 2.3.5 and scikit-learn 1.8.0, ordinary least squares has slope about 2.1770, intercept 3.2036, and clean-validation MAE 2.9410. Huber regression has slope 1.9930, intercept 1.0370, and MAE 0.0182. The result shows reduced sensitivity to the inserted vertical corruption. It does not establish resilience to arbitrary high-leverage features or prove that unusual real outcomes should be ignored.
import numpy as np
from sklearn.linear_model import LinearRegression, HuberRegressor
from sklearn.metrics import mean_absolute_error
x=np.arange(10,dtype=float)[:,None]
y=1+2*x[:,0]+np.array([.1,-.1,.05,0,-.05,.1,-.1,.05,0,-.05])
y[5]+=30
x_valid=np.array([1.5,3.5,7.5])[:,None]
y_valid=1+2*x_valid[:,0]
for model in [LinearRegression(),HuberRegressor(epsilon=1.35,alpha=0.,max_iter=1000)]:
model.fit(x,y)
print(type(model).__name__,'slope/intercept/validation MAE:',
round(model.coef_[0],4),round(model.intercept_,4),
round(mean_absolute_error(y_valid,model.predict(x_valid)),4))
def huber(e,delta=1.):
a=abs(e)
return .5*e*e if a<=delta else delta*(a-.5*delta)
print('Classical Huber loss:',[huber(e) for e in [0,.5,1,3]])
assert huber(3)==2.5
Four practice questions with worked answers
Practice 1
Calculate classical Huber loss at residual −3 with δ=1.
Answer: The magnitude exceeds one, so use 1×(3−0.5)=2.5. The loss is symmetric, giving the same value for residual+3. Its derivative with respect to residual is −1 on this negative tail, rather than continuing to grow in magnitude as under squared loss.
Practice 2
A very delayed parcel is genuine, but a robust model treats it as unusual. Should it be deleted?
Answer: No, not merely because of the model label. Determine whether it belongs to the deployment population and decision objective. If rare disruptions matter, retain them in appropriate evaluation and report performance on that regime. A fitting method’s outlier designation is not a data-quality verdict.
Practice 3
Why is robustness to large residuals different from robustness to leverage?
Answer: Residual size concerns vertical prediction error. Leverage concerns an unusual input location. Even a capped residual derivative is multiplied by feature values when forming coefficient gradients, so extreme features can still influence the fit. Inspect input geometry and use a method whose assumptions match the suspected contamination.
Practice 4
The demonstration validates only clean outcomes. What must be added for a mixed clean-and-disruption deployment?
Answer: Evaluate representative observations from both regimes, with a predeclared metric or cost weighting. Report subgroup and tail behavior so improved typical-case accuracy does not conceal failure on legitimate disruptions. Keep tuning separate from final assessment and record any exclusions or sampling adjustments.
Five multiple-choice questions
Question 1
What is the large-residual growth of classical Huber loss?
- A. Linear
- B. Constant
- C. Quadratic
Correct: A. Beyond its threshold it grows linearly, reducing sensitivity without completely ignoring residual magnitude.
Question 2
Does a fitted outlier flag establish an incorrect record?
- A. Only if the residual exceeds one
- B. No, it is relative to a model and rule
- C. Yes, by definition
Correct: B. A legitimate rare process or model misspecification can also produce a large residual.
Question 3
What does HuberRegressor epsilon apply to?
- A. The number of selected features
- B. A scaled residual threshold
- C. A fixed percentage of rows to delete
Correct: B. The estimator jointly estimates scale, so its threshold is not simply a raw-unit deletion rule.
Question 4
Which evaluation would exaggerate robustness?
- A. Removing test rows because this model predicts them badly
- B. Using a fixed representative holdout
- C. Reporting both typical and extreme cases
Correct: A. Outcome-dependent exclusion changes the assessed population and favors the model circularly.
Question 5
What does RANSAC seek?
- A. A consensus set consistent with candidate models
- B. The conditional mean under every distribution
- C. The minimum coefficient norm only
Correct: A. Its subset-and-consensus procedure requires assumptions distinct from ordinary penalized least squares.
Common pitfalls
Do not confuse robust loss with verified data cleaning. Do not suppress convergence warnings or assume feature scaling is irrelevant. Avoid declaring one estimator universally best from a demonstration whose contamination mechanism was chosen to favor it.
Summary
Robust regression limits sensitivity under specific assumptions. Understand the loss shape, distinguish residual outliers from leverage, inspect real data mechanisms, and evaluate every population the deployed system must serve.