Robust regression

Robust linear and nonlinear regression estimators, in robustmodels.regression.

Choosing an estimator

Class

Needs

Random

Notes

MMRegressor

n > p

Yes

The default choice: 50% breakdown and 95% Gaussian efficiency under normal errors

LTSRegressor

n > p

Yes

Least trimmed squares, then reweighted least squares; marks the observations it uses

SRegressor

n > p

Yes

Minimizes a robust residual scale; 50% breakdown but only 29% efficiency

Here n is the number of observations and p the number of coefficients, including the intercept. MM starts from the S-estimator and keeps its breakdown point while reaching high efficiency, so it is usually preferred to S alone. LTS is simple to interpret: it fits the h observations with the smallest squared residuals.

Use

All classes are scikit-learn regressors: parameters go to the constructor, fit(X, y) returns the estimator, and predict(X) gives fitted values.

>>> import numpy as np
>>> from sklearn.linear_model import LinearRegression
>>> from robustmodels.regression import LTSRegressor
>>> rng = np.random.default_rng(0)
>>> X = rng.normal(size=(100, 1))
>>> y = 1 + 2 * X[:, 0] + rng.normal(scale=0.5, size=100)
>>> y[:20] += 15  # twenty outliers
>>> lts = LTSRegressor(random_state=0).fit(X, y)
>>> round(lts.intercept_, 2), lts.coef_.round(2).tolist()
(0.95, [2.04])
>>> ols = LinearRegression().fit(X, y)
>>> round(float(ols.intercept_), 2), ols.coef_.round(2).tolist()
(4.04, [1.17])

The true line is 1 + 2x. Least squares is pulled towards the outliers; the robust fits follow the bulk of the data:

>>> from robustmodels.regression import MMRegressor
>>> mm = MMRegressor(random_state=0).fit(X, y)
>>> round(mm.intercept_, 2), mm.coef_.round(2).tolist()
(0.96, [2.04])

Every fitted estimator has:

Attribute or method

Meaning

coef_, intercept_

Final coefficients

scale_

Robust scale of the residuals

predict(X), score(X, y)

Fitted values and R², as in scikit-learn

LTSRegressor also has support_, the observations used for the final fit, the least trimmed squares fit (raw_coef_, raw_intercept_, raw_scale_, raw_support_) and the subset size h_. SRegressor and MMRegressor have n_iter_, and MMRegressor keeps its starting S fit in s_coef_ and s_intercept_; its scale_ is the S scale.

Standard errors and tests

MMRegressor estimates the covariance matrix of its coefficients with the formula of Croux, Dhaene & Hoorelbeke (2003), the default of R’s lmrob, and reports t statistics and two-sided p-values with n - p degrees of freedom. summary() prints them as summary(lmrob):

>>> print(mm.summary(["x"]))
               Estimate  Std. Error   t value  Pr(>|t|)
(Intercept)      0.9607     0.05451    17.626  3.77e-32
x                 2.035     0.04985    40.826  2.51e-63
Residual scale: 0.682

The values are also attributes: cov_params_, std_errors_, t_values_ and p_values_, ordered as [intercept_, *coef_]. These standard errors remain valid when the error variance changes with X (heteroskedasticity); when it does not, they are somewhat less efficient than classical ones. In the tests, 95% intervals cover the true coefficients about 94% of the time with normal errors and 95% with heteroskedastic errors (n = 100).

mm_test(model, X, y, columns) tests that the slopes of some columns are zero, as R’s anova.lmrob. The default test="deviance" refits the reduced model with the scale of the full one and compares the robust losses (Ronchetti 1982); test="wald" uses cov_params_. Both compare with a chi-square distribution:

>>> from robustmodels.regression import mm_test
>>> result = mm_test(mm, X, y, [0])  # is the slope zero?
>>> result.df, result.pvalue < 1e-10
(1, True)

The deviance test assumes symmetric errors of constant variance; the Wald test inherits the heteroskedasticity-robust covariance. In the tests both keep a nominal 5% level with normal and t3 errors (n = 60), and they agree with anova.lmrob up to robustbase’s rounded constants.

Detecting outliers

Divide the residuals by scale_ and flag those above 2.24 in absolute value, the cutoff used by the reweighting step (the 98.75% normal quantile):

>>> flagged = np.abs(y - lts.predict(X)) > 2.24 * lts.scale_
>>> np.flatnonzero(flagged).tolist() == list(range(20))
True

The twenty planted outliers are found. Residuals reveal vertical outliers and bad leverage points. An observation that is extreme in X but follows the line (a good leverage point) has a small residual; robust distances of X, for example from robustmodels.covariance.MCD, identify it.

For a combined residual and leverage diagnostic, use plots.outlier_map. It distinguishes vertical outliers from good and bad leverage, using a residual cutoff of 2.5.

Comparing fits

Whether a conclusion depends on a few observations is often the question that matters. plots.coefficient_plot draws the estimates and confidence intervals of several fits side by side, with least squares as the reference. Here eight observations with large values of the third variable make it look important to least squares; the robust fits agree that it is not.

import numpy as np
from robustmodels import plots
from robustmodels.rank import RankRegressor
from robustmodels.regression import MMRegressor
from robustmodels.shape import ScoreMatchingRegressor

rng = np.random.default_rng(4)
X = rng.normal(size=(150, 3))
y = 1 + X @ [2.0, -1.0, 0.0] + rng.standard_t(2, 150)
y[:8] += 25 * X[:8, 2]  # eight observations tie y to the third variable
fits = [MMRegressor().fit(X, y), RankRegressor().fit(X, y), ScoreMatchingRegressor().fit(X, y)]
plots.coefficient_plot(fits, labels=["MM", "Rank", "Score matching"], X=X, y=y,
                       feature_names=["dose", "age", "site"])

(png, svg)

Coefficient estimates with 95% intervals from MM, rank and score matching fits and least squares.

Reproducibility

FAST-LTS and FAST-S draw random starting subsets. Pass random_state to get the same result on every run.

With scikit-learn

The estimators work with clone, get_params, set_params, pipelines and model selection tools:

>>> from sklearn.base import clone
>>> clone(lts).set_params(alpha=0.75).fit(X, y).h_
75

Here alpha is the coverage of the h-subset, as in MCD and R’s ltsReg, not a regularization strength.

Numerical limits and sources

FAST-LTS takes two concentration steps from each random elemental start, then iterates the ten best to convergence. Exhaustive small problems check the trimmed objective independently; the finite random search does not certify a global optimum. The intercept is a column of ones, without the intercept adjustment step of Rousseeuw & Van Driessen (2006), as in ltsReg’s default.

For data in general position the raw estimator has breakdown point close to (n - h + 1) / n, about 50% at alpha = 0.5. The scale uses consistency factors for normal errors and the small-sample factors of Pison, Van Aelst & Willems (2002), which are empirical approximations. The consistency factors assume that the trimmed observations are normal tails: with outliers present, scale_ overestimates the error standard deviation (0.73 instead of 0.5 in the example above), as in ltsReg.

FAST-S refines every random start a few steps and the five best to convergence; refinement stops when the coefficients change by less than 1e-7 relative. The number of starts and refined candidates affects the local solution selected. The S scale divides by n - p, as lmrob, to reduce small-sample bias, and is consistent at the normal model; like the LTS scale, it overestimates the error standard deviation when outliers are present. The bisquare constants are computed from their defining normal expectations (about 1.5476 for 50% breakdown and 4.6851 for 95% efficiency).

The MM-estimator keeps the S scale fixed and converges to a local minimum of its loss near the S fit. Its breakdown point is that of the S-estimator, and 95% is the asymptotic efficiency of the coefficients under normal errors; the tests check both efficiencies by simulation.

Sources: LTS, FAST-LTS, small-sample corrections, S-estimators, FAST-S, MM-estimators, the n - p scale and MM standard errors.

Nonlinear robust regression

NonlinearMRegressor(model, start) fits y = model(X, *params) with Huber iteratively reweighted nonlinear least squares. Supply a callable that returns one finite value per row and a finite initial parameter vector. params_, scale_, weights_, cov_params_ and std_errors_ describe the final fit; predict(X) evaluates the fitted curve. converged_ reports outer-loop convergence, and iteration exhaustion emits a RuntimeWarning.

>>> from robustmodels.regression import NonlinearMRegressor
>>> def decay(X, a, b):
...     return a * np.exp(-b * X[:, 0])
>>> rng = np.random.default_rng(0)
>>> X = rng.uniform(0, 5, size=(80, 1))
>>> y = decay(X, 10, 0.7) + rng.normal(scale=0.3, size=80)
>>> y[:8] += 15
>>> fit = NonlinearMRegressor(decay, [5, 1]).fit(X, y)
>>> fit.params_.round(2).tolist()
[10.29, 0.71]

The scale is the median absolute final residual divided by 0.6745, an approximation to the normal 0.75 quantile. The covariance uses Huber’s asymptotic formula with the model Jacobian. It assumes a correctly specified model with independent, symmetric, homoscedastic errors and a full-column-rank Jacobian; it is not heteroscedasticity-robust. A rank-deficient final Jacobian raises ValueError because the parameters are not locally identifiable. The implementation is checked against an analytic exponential Jacobian. A zero median residual scale emits an exact-fit warning and returns zero covariance; standard errors in that degenerate case do not support ordinary inference. Robust residual weights protect against vertical outliers; leverage points and poor starting parameters can still dominate the fit.

Reference

class MMRegressor(*, breakdown=0.5, efficiency=0.95, fit_intercept=True, n_trials=500, max_iter=500, random_state=None)[source]

MM-estimator of regression (Yohai 1987).

Starts from the SRegressor fit and keeps its scale fixed while iteratively reweighted least squares lowers a bisquare loss with a larger tuning constant. This keeps the breakdown point of the S-estimator and reaches the requested Gaussian efficiency, as R’s lmrob by default. The final loss is a local minimum near the S fit; it is not a global search.

Parameters:
  • breakdown (float in (0, 0.5], default 0.5) – Breakdown point of the initial S-estimator.

  • efficiency (float in (0, 1), default 0.95) – Asymptotic Gaussian efficiency of the coefficients. The final tuning constant must not be smaller than the initial one; lower values raise ValueError.

  • fit_intercept (bool, default True) – Add an intercept.

  • n_trials (int, default 500) – Random starting subsets of the S-estimator.

  • max_iter (int, default 500) – Maximum steps of each iterative stage (S refinement and MM); a RuntimeWarning names the stage that did not converge.

  • random_state (int, numpy.random.Generator, numpy.random.RandomState or None) – Seed of the S-estimator.

coef_

Final slopes.

Type:

ndarray of shape (n_features,)

intercept_

Final intercept; 0 without fit_intercept.

Type:

float

scale_

Residual scale of the S-estimator, kept fixed.

Type:

float

s_coef_, s_intercept_

Coefficients of the initial S-estimator.

n_iter_

Iterations of the MM stage; 0 for an exact fit.

Type:

int

cov_params_

Asymptotic covariance matrix of the coefficients, ordered as [intercept_, *coef_] with fit_intercept (Croux, Dhaene & Hoorelbeke 2003, as lmrob’s default). It is robust to heteroskedasticity; NaN for an exact fit.

Type:

ndarray of shape (p, p)

std_errors_, t_values_, p_values_

Standard errors, t statistics and two-sided p-values from a t distribution with n - p degrees of freedom, in the same order.

Type:

ndarray of shape (p,)

References

Yohai, V. J. (1987). High breakdown-point and high efficiency robust estimates for regression. The Annals of Statistics, 15(2), 642-656.

Croux, C., Dhaene, G. and Hoorelbeke, D. (2003). Robust standard errors for robust estimators. Discussion Paper 03.16, Center for Economic Studies, KU Leuven.

Examples

>>> import numpy as np
>>> from robustmodels.regression import MMRegressor
>>> rng = np.random.default_rng(0)
>>> X = rng.normal(size=(100, 1))
>>> y = 1 + 2 * X[:, 0] + rng.normal(scale=0.5, size=100)
>>> y[:20] += 15  # twenty outliers
>>> mm = MMRegressor(random_state=0).fit(X, y)
>>> round(mm.intercept_, 2), mm.coef_.round(2).tolist()
(0.96, [2.04])
fit(X, y)[source]

Fit to X of shape (n_samples, n_features) and y. Returns self.

predict(X)

Predicted values X @ coef_ + intercept_.

class LTSRegressor(*, alpha=0.5, fit_intercept=True, n_trials=500, reweighting=True, small_sample_correction=True, random_state=None)[source]

Least Trimmed Squares regression (Rousseeuw 1984).

Least squares fit to the h observations with the smallest sum of squared residuals, found with FAST-LTS (Rousseeuw & Van Driessen 2006). The residual scale is made consistent at the normal model; with outliers present, the consistency factors overestimate the error standard deviation, as in R’s ltsReg. The reweighting step then refits least squares to the observations whose standardized residual is at most 2.24 in absolute value. The raw estimator has breakdown point close to (n - h + 1) / n, about 50% for alpha = 0.5; its efficiency is low, and the reweighting step improves it. The search does not certify a global minimum. If h observations fit exactly, a RuntimeWarning reports it, the raw fit is kept and the scale is 0.

Parameters:
  • alpha (float in [0.5, 1], default 0.5) – Coverage. The subset size h = h_alpha_n(alpha, n, p), with p the number of coefficients including the intercept, goes from (n + p + 1) // 2 at 0.5 to n (least squares) at 1.

  • fit_intercept (bool, default True) – Add an intercept.

  • n_trials (int, default 500) – Random starting subsets of FAST-LTS.

  • reweighting (bool, default True) – Apply the reweighting step.

  • small_sample_correction (bool, default True) – Multiply the scale by the factors of Pison, Van Aelst & Willems (2002).

  • random_state (int, numpy.random.Generator, numpy.random.RandomState or None) – Seed of FAST-LTS.

coef_

Final slopes.

Type:

ndarray of shape (n_features,)

intercept_

Final intercept; 0 without fit_intercept.

Type:

float

scale_

Final robust scale of the residuals.

Type:

float

support_

Observations used for the final fit.

Type:

ndarray of bool, shape (n_samples,)

raw_coef_, raw_intercept_, raw_scale_

Least trimmed squares fit and its corrected scale.

raw_support_

The h-subset.

Type:

ndarray of bool, shape (n_samples,)

h_

Subset size.

Type:

int

References

Rousseeuw, P. J. (1984). Least median of squares regression. Journal of the American Statistical Association, 79(388), 871-880.

Rousseeuw, P. J. and Van Driessen, K. (2006). Computing LTS regression for large data sets. Data Mining and Knowledge Discovery, 12(1), 29-45.

Pison, G., Van Aelst, S. and Willems, G. (2002). Small sample corrections for LTS and MCD. Metrika, 55, 111-123.

Examples

>>> import numpy as np
>>> from robustmodels.regression import LTSRegressor
>>> rng = np.random.default_rng(0)
>>> X = rng.normal(size=(100, 1))
>>> y = 1 + 2 * X[:, 0] + rng.normal(scale=0.5, size=100)
>>> y[:20] += 15  # twenty outliers
>>> lts = LTSRegressor(random_state=0).fit(X, y)
>>> round(lts.intercept_, 2), lts.coef_.round(2).tolist()
(0.95, [2.04])
>>> int(lts.support_[:20].sum())  # no outlier is used
0
fit(X, y)[source]

Fit to X of shape (n_samples, n_features) and y. Returns self.

predict(X)

Predicted values X @ coef_ + intercept_.

class SRegressor(*, breakdown=0.5, fit_intercept=True, n_trials=500, n_best=5, k_steps=2, max_iter=500, random_state=None)[source]

S-estimator of regression (Rousseeuw & Yohai 1984).

Coefficients that minimize an M-estimator of the residual scale with Tukey’s bisquare loss, found with FAST-S (Salibian-Barrera & Yohai 2006). The scale s solves sum(rho(r_i / s)) / (n - p) = breakdown, with p the number of coefficients; the n - p denominator reduces small-sample bias (Maronna et al. 2019) and is also used by R’s lmrob. The bisquare constant makes the scale consistent at the normal model. At breakdown = 0.5 the Gaussian efficiency is only about 29%; use MMRegressor for efficient estimates. The search does not certify a global minimum. If more than about half of the residuals can be made zero, a RuntimeWarning reports the exact fit and the scale is 0.

Parameters:
  • breakdown (float in (0, 0.5], default 0.5) – Asymptotic breakdown point.

  • fit_intercept (bool, default True) – Add an intercept.

  • n_trials (int, default 500) – Random elemental starting subsets.

  • n_best (int, default 5) – Candidates refined to convergence.

  • k_steps (int, default 2) – Refinement steps applied to every start.

  • max_iter (int, default 500) – Maximum refinement steps for the best candidates. Refinement stops when the coefficients change by less than 1e-7 relative, as in lmrob; a RuntimeWarning reports non-convergence.

  • random_state (int, numpy.random.Generator, numpy.random.RandomState or None) – Seed of FAST-S.

coef_

Slopes.

Type:

ndarray of shape (n_features,)

intercept_

Intercept; 0 without fit_intercept.

Type:

float

scale_

M-scale of the residuals.

Type:

float

n_iter_

Refinement steps of the selected candidate; 0 for an exact fit.

Type:

int

References

Rousseeuw, P. J. and Yohai, V. J. (1984). Robust regression by means of S-estimators. In Robust and Nonlinear Time Series Analysis, Lecture Notes in Statistics 26, 256-272. Springer.

Salibian-Barrera, M. and Yohai, V. J. (2006). A fast algorithm for S-regression estimates. Journal of Computational and Graphical Statistics, 15(2), 414-427.

Maronna, R. A., Martin, R. D., Yohai, V. J. and Salibian-Barrera, M. (2019). Robust Statistics: Theory and Methods (with R), 2nd edition. Wiley.

Examples

>>> import numpy as np
>>> from robustmodels.regression import SRegressor
>>> rng = np.random.default_rng(0)
>>> X = rng.normal(size=(100, 1))
>>> y = 1 + 2 * X[:, 0] + rng.normal(scale=0.5, size=100)
>>> y[:20] += 15  # twenty outliers
>>> s = SRegressor(random_state=0).fit(X, y)
>>> round(s.intercept_, 2), s.coef_.round(2).tolist()
(1.03, [2.04])
fit(X, y)[source]

Fit to X of shape (n_samples, n_features) and y. Returns self.

predict(X)

Predicted values X @ coef_ + intercept_.

mm_test(model, X, y, columns, *, test='deviance')[source]

Test that some slopes of an MM regression are zero, as R’s anova.lmrob.

"wald" compares b' V^-1 b for the tested coefficients b, with V their block of cov_params_, with a chi-square distribution on q = len(columns) degrees of freedom. "deviance" is the robust likelihood-ratio type test of Ronchetti (1982): the reduced model is refitted as an M-estimator with the scale s of the full model, starting from the full coefficients, and 2 tau sum(rho(r_reduced / s) - rho(r_full / s)), with rho' = psi and tau = mean(psi'(r / s)) / mean(psi(r / s)^2) over the full residuals, is also compared with a chi-square on q degrees of freedom. The deviance test assumes symmetric errors of constant variance; the Wald test inherits the heteroskedasticity-robust covariance. Both are asymptotic.

Parameters:
  • model (fitted MMRegressor)

  • X (array-like of shape (n_samples, n_features)) – The data the model was fitted to.

  • y (array-like of shape (n_samples,))

  • columns (int or sequence of int) – Columns of X whose slopes are zero under the hypothesis.

  • test ({"deviance", "wald"}, default "deviance")

Returns:

statistic, df and pvalue.

Return type:

MMTestResult

References

Ronchetti, E. (1982). Robust testing in linear models: the infinitesimal approach. PhD thesis, ETH Zürich.

Hampel, F. R., Ronchetti, E. M., Rousseeuw, P. J. and Stahel, W. A. (1986). Robust Statistics: The Approach Based on Influence Functions, Section 7.3. Wiley.

Examples

>>> import numpy as np
>>> from robustmodels.regression import MMRegressor, mm_test
>>> rng = np.random.default_rng(0)
>>> X = rng.normal(size=(80, 3))
>>> y = 1 + 2 * X[:, 0] + rng.normal(size=80)
>>> y[:8] += 15  # outliers
>>> mm = MMRegressor(random_state=0).fit(X, y)
>>> round(mm_test(mm, X, y, [1, 2]).pvalue, 2), mm_test(mm, X, y, [0]).pvalue < 1e-10
(0.87, True)
class NonlinearMRegressor(model, start, *, c=1.345, max_iter=50, tol=1e-06)[source]

Huber M-estimator of nonlinear regression.

Fits y = model(X, *params) + error by iteratively reweighted nonlinear least squares: the residual scale is the median absolute residual divided by 0.6745 and the weights are Huber’s min(1, c / |r_i / scale|), as R’s nlrob by default. Large residuals have bounded influence, which protects against outliers in y; outliers in X (leverage points) can still dominate the fit, and the result depends on the starting value.

Parameters:
  • model (callable) – model(X, *params) returns the fitted values, of shape (n_samples,).

  • start (array-like of shape (n_params,)) – Starting value of the parameters.

  • c (float, default 1.345) – Huber tuning constant, in units of the residual scale.

  • max_iter (int, default 50) – Maximum reweighting steps; a RuntimeWarning reports non-convergence.

  • tol (float, default 1e-6) – Relative change of the residuals at which the iterations stop.

params_

Estimated parameters.

Type:

ndarray of shape (n_params,)

scale_

Residual scale.

Type:

float

weights_

Huber weights of the observations.

Type:

ndarray of shape (n_samples,)

cov_params_

Asymptotic covariance matrix (Huber 1981): scale_^2 (sum(psi^2) / (n - p)) / mean(psi')^2 (J'J)^-1, with J the Jacobian of the model. This formula assumes a correctly specified model with independent symmetric homoscedastic errors and a full-column-rank Jacobian. It is not heteroscedasticity-robust. A rank-deficient Jacobian raises ValueError because its parameters are not locally identifiable.

Type:

ndarray of shape (n_params, n_params)

std_errors_

Standard errors.

Type:

ndarray of shape (n_params,)

n_iter_

Reweighting steps.

Type:

int

References

Huber, P. J. (1981). Robust Statistics. Wiley.

Examples

>>> import numpy as np
>>> from robustmodels.regression import NonlinearMRegressor
>>> def decay(X, a, b):
...     return a * np.exp(-b * X[:, 0])
>>> rng = np.random.default_rng(0)
>>> X = rng.uniform(0, 5, size=(80, 1))
>>> y = decay(X, 10, 0.7) + rng.normal(scale=0.3, size=80)
>>> y[:8] += 15  # eight outliers
>>> fit = NonlinearMRegressor(decay, [5, 1]).fit(X, y)
>>> fit.params_.round(2).tolist()
[10.29, 0.71]
fit(X, y)[source]

Fit to X of shape (n_samples, n_features) and y. Returns self.

predict(X)[source]

Fitted values model(X, *params_).