Robust generalized linear models¶
Use logistic models for two classes and Poisson models for nonnegative count
responses. All four estimators expose coef_, intercept_, robustness
weights_, cov_params_, std_errors_, normal z_values_ and p_values_,
and an R-style summary(). Logistic estimators also provide classes_,
predict_proba and decision_function. Their predict returns class labels;
Poisson predict returns the fitted mean.
Estimator |
Criterion |
Protection |
|---|---|---|
|
Huberized, Fisher-corrected quasi-score |
Bounded residual influence |
|
The same score for Poisson means |
Bounded residual influence |
|
Bianco–Yohai corrected deviance |
Large deviances; leverage trimming with |
|
Bisquare loss of transformed counts |
Zero weight for gross residual outliers |
Mallows uses maximum likelihood as its starting fit. x_weights="mcd" also
bounds leverage influence using robust predictor distances; it needs continuous
predictors with nonsingular robust scatter. x_weights="hat" uses ordinary
leverage. BY defaults to trimming observations beyond the 97.5% robust distance
cutoff before fitting. MT uses n_trials random starting subsets, so set
random_state for reproducibility. These methods find local solutions and do
not certify global optimality.
Example¶
>>> import numpy as np
>>> from robustmodels.glm import MallowsPoissonRegressor
>>> rng = np.random.default_rng(0)
>>> X = rng.normal(size=(200, 1))
>>> y = rng.poisson(np.exp(1 + 0.5 * X[:, 0]))
>>> y[:10] = 40
>>> fit = MallowsPoissonRegressor().fit(X, y)
>>> round(fit.intercept_, 2), fit.coef_.round(2).tolist()
(1.07, [0.54])
>>> bool((fit.weights_[:10] < 0.2).all())
True
>>> fit.predict(X[:3]).shape
(3,)
Defining equations and inference assumptions¶
MallowsPoissonRegressor accepts a known offset in both fit and
predict. For strictly positive observation times t, pass
offset=np.log(t). The model is E[Y|X,t] = t * exp(intercept + X @ coef).
Supply the corresponding offset again when predicting counts for new
exposure times. Without an offset, predict returns the mean at unit
exposure per row.
Mallows solves a Huberized Pearson estimating equation with its conditional model expectation subtracted. For a fixed design, the covariance uses the conditional score variance and sensitivity for each observation. Independent tests evaluate Poisson expectations directly and differentiate them numerically; BY tests verify that its corrected binary score has zero expectation at the nominal probability. Cantoni and Ronchetti and Croux and Haesbroeck provide the defining theory.
MTPoissonRegressor minimizes a transformed-count criterion with ordinary
bisquare loss. Its ideal correction m(mu) minimizes
E[rho(sqrt(Y) - m)] for Poisson Y; the code approximates that function by
a cubic Hermite spline and a continuous value extension above mean 100.
The first grid interval is searched explicitly, because an interior minimum
near zero can be missed by testing only interior grid nodes. Direct Poisson
summation checks the correction equation at small means, rather than using
another program’s output as its target.
This is an MT-style computational variant. The consistency argument
requires a uniquely defined, strictly increasing correction, correct model
specification and identification. The specific smooth-loss family in
Valdora and Yohai, section 4 uses exponent 4, whereas
ordinary bisquare uses exponent 3. The source theorem’s differentiability
assumptions therefore do not automatically apply to this implementation.
c<=1 is rejected because the correction can remain flat at zero for small
means. c>1 is a necessary guard here, not a proof of uniqueness, global
monotonicity or every asymptotic assumption for all accepted constants.
The spline has approximation error; local optimization does not certify a
global minimum. Standard errors require a locally identified regular solution.
Numerical conventions and software correspondence¶
x_weights="hat"usessqrt(1 - h_ii), as the Mallows source; robustbase uses(1 - h_ii)^2under that name. The conditional Mallows sandwich also uses an observation-specific mean correction rather than an averaged one.Weighted BY fits the trimmed subset. robustbase’s
WBYuses trimming for initialization and then minimizes an unweighted criterion. These are different procedures, and numerical equality is not an acceptance condition.Linear predictors used to evaluate means are clipped to
[-30, 30]for numerical stability. Mallows scoring steps change each predictor by at most 5. The MT gradient differentiates its implemented clipped objective. A final MT solution touching the numerical cap, or a Mallows Poisson solution above+30, reportsconverged_=False, aRuntimeWarningand unavailable inference (NaN). Below-30, and at either cap of the logistic model, an observation’s Mallows score is of ordersqrt(V(mu)), about3e-7, so the cap does not change the fit; a well-fitted leverage point there keeps its inference.Separated logistic data can lack finite coefficients. Check
converged_and the emitted warnings. A small gradient alone does not establish existence or identification. The usual normal inference is asymptotic.An all-zero Poisson response with an intercept has no finite intercept and raises
ValueError. Collinear designs and samples without residual degrees of freedom are also rejected.
The validation notes document independent checks, corrected counterexamples and the remaining scientific limits. Software correspondence is collected in the migration guide.
Reference¶
- class MallowsLogisticRegression(*, c=1.345, x_weights='none', fit_intercept=True, max_iter=100, tol=1e-08)[source]¶
Robust logistic regression by Mallows quasi-likelihood.
Solves
sum((psi_c(r_i) - E[psi_c(r_i)]) w(x_i) sqrt(V(mu_i)) x_i) = 0, withr_i = (y_i - mu_i) / sqrt(V(mu_i))the Pearson residuals,psi_cHuber’s function andE[psi_c(r_i)]its expectation under the model, which makes the estimator Fisher consistent. Large residuals have bounded influence; the weightsw(x_i)bound the influence of leverage points. Fisher scoring starts from the maximum likelihood fit, as R’sglmrob(method = "Mqle"). The estimator bounds the influence function, but its breakdown point is not high.- Parameters:
c (float, default 1.345) – Huber tuning constant; larger values are closer to maximum likelihood.
x_weights ({"none", "hat", "mcd"}, default "none") – Weights on the regressors.
"hat"issqrt(1 - h_ii)withh_iithe leverages (Cantoni & Ronchetti 2001; robustbase computes(1 - h_ii)^2under the same name)."mcd"is1 / sqrt(1 + 8 max(0, (d_i^2 - p) / sqrt(2 p)))withd_irobust distances from a deterministicMCD, as robustbase’s"covMcd"; it needs continuous regressors.fit_intercept (bool, default True) – Add an intercept.
max_iter (int, default 100) – Maximum Fisher scoring steps; a
RuntimeWarningreports non-convergence.tol (float, default 1e-8) – Relative change of the coefficients at which the iterations stop.
- coef_¶
Slopes.
- Type:
ndarray of shape (n_features,)
- intercept_¶
Intercept; 0 without
fit_intercept.- Type:
float
- cov_params_¶
Asymptotic covariance matrix of
[intercept_, *coef_]:M^-1 Q M^-1 / nwithQthe variance of the estimating function. Cantoni & Ronchetti (and robustbase) subtract the squared mean of the correction terms instead of each squared term, which gives slightly larger standard errors.- Type:
ndarray of shape (p, p)
- std_errors_, z_values_, p_values_
Standard errors, z statistics and two-sided normal p-values.
- Type:
ndarray of shape (p,)
- weights_¶
Robustness weights
min(1, c / |r_i|) w(x_i).- Type:
ndarray of shape (n_samples,)
- n_iter_¶
Fisher scoring steps.
- Type:
int
- classes_¶
Class labels.
- Type:
ndarray of shape (2,)
References
Cantoni, E. and Ronchetti, E. (2001). Robust inference for generalized linear models. Journal of the American Statistical Association, 96(455), 1022-1030.
Examples
>>> import numpy as np >>> from robustmodels.glm import MallowsLogisticRegression >>> rng = np.random.default_rng(0) >>> X = rng.normal(size=(200, 1)) >>> y = rng.binomial(1, 1 / (1 + np.exp(-1 - 2 * X[:, 0]))) >>> y[np.argsort(X[:, 0])[-5:]] = 0 # five misclassified observations >>> fit = MallowsLogisticRegression().fit(X, y) >>> round(fit.intercept_, 2), fit.coef_.round(2).tolist() (0.76, [1.64])
- decision_function(X)¶
Linear predictor
X @ coef_ + intercept_(log odds ofclasses_[1]).
- fit(X, y)¶
Fit to
Xof shape (n_samples, n_features) andy. Returnsself.
- predict(X)¶
Most probable class.
- predict_proba(X)¶
Probabilities of
classes_[0]andclasses_[1], one row per observation.
- summary(feature_names=None)¶
Coefficient table as R’s
summary(glmrob).- Parameters:
feature_names (sequence of str, optional) – Names of the columns of
X;x0, x1, ...by default.- Returns:
Estimates, standard errors, z values and two-sided normal p-values.
- Return type:
str
- class MallowsPoissonRegressor(*, c=1.345, x_weights='none', fit_intercept=True, max_iter=100, tol=1e-08)[source]¶
Robust Poisson regression by Mallows quasi-likelihood.
Solves
sum((psi_c(r_i) - E[psi_c(r_i)]) w(x_i) sqrt(V(mu_i)) x_i) = 0, withr_i = (y_i - mu_i) / sqrt(V(mu_i))the Pearson residuals,psi_cHuber’s function andE[psi_c(r_i)]its expectation under the model, which makes the estimator Fisher consistent. Large residuals have bounded influence; the weightsw(x_i)bound the influence of leverage points. Fisher scoring starts from the maximum likelihood fit, as R’sglmrob(method = "Mqle"). The estimator bounds the influence function, but its breakdown point is not high.- Parameters:
c (float, default 1.345) – Huber tuning constant; larger values are closer to maximum likelihood.
x_weights ({"none", "hat", "mcd"}, default "none") – Weights on the regressors.
"hat"issqrt(1 - h_ii)withh_iithe leverages (Cantoni & Ronchetti 2001; robustbase computes(1 - h_ii)^2under the same name)."mcd"is1 / sqrt(1 + 8 max(0, (d_i^2 - p) / sqrt(2 p)))withd_irobust distances from a deterministicMCD, as robustbase’s"covMcd"; it needs continuous regressors.fit_intercept (bool, default True) – Add an intercept.
max_iter (int, default 100) – Maximum Fisher scoring steps; a
RuntimeWarningreports non-convergence.tol (float, default 1e-8) – Relative change of the coefficients at which the iterations stop.
- coef_¶
Slopes.
- Type:
ndarray of shape (n_features,)
- intercept_¶
Intercept; 0 without
fit_intercept.- Type:
float
- cov_params_¶
Asymptotic covariance matrix of
[intercept_, *coef_]:M^-1 Q M^-1 / nwithQthe variance of the estimating function. Cantoni & Ronchetti (and robustbase) subtract the squared mean of the correction terms instead of each squared term, which gives slightly larger standard errors.- Type:
ndarray of shape (p, p)
- std_errors_, z_values_, p_values_
Standard errors, z statistics and two-sided normal p-values.
- Type:
ndarray of shape (p,)
- weights_¶
Robustness weights
min(1, c / |r_i|) w(x_i).- Type:
ndarray of shape (n_samples,)
- n_iter_¶
Fisher scoring steps.
- Type:
int
References
Cantoni, E. and Ronchetti, E. (2001). Robust inference for generalized linear models. Journal of the American Statistical Association, 96(455), 1022-1030.
Examples
>>> import numpy as np >>> from robustmodels.glm import MallowsPoissonRegressor >>> rng = np.random.default_rng(0) >>> X = rng.normal(size=(200, 1)) >>> y = rng.poisson(np.exp(1 + 0.5 * X[:, 0])) >>> y[:10] = 40 # ten outliers >>> fit = MallowsPoissonRegressor().fit(X, y) >>> round(fit.intercept_, 2), fit.coef_.round(2).tolist() (1.07, [0.54])
- fit(X, y, *, offset=None)[source]¶
Fit the count model with an optional known additive log-mean offset.
Pass a finite scalar or one value per row. For exposure times
t, useoffset=np.log(t)with strictly positive exposures.
- predict(X, *, offset=None)[source]¶
Return expected counts with the supplied offset, or unit exposure by default.
- summary(feature_names=None)¶
Coefficient table as R’s
summary(glmrob).- Parameters:
feature_names (sequence of str, optional) – Names of the columns of
X;x0, x1, ...by default.- Returns:
Estimates, standard errors, z values and two-sided normal p-values.
- Return type:
str
- class BYLogisticRegression(*, c=0.5, weighted=True, fit_intercept=True, max_iter=1000)[source]¶
Bianco-Yohai estimator of logistic regression (Croux & Haesbroeck 2003).
Minimizes
sum(rho(d_i) + G(F_i) + G(1 - F_i)), withd_ithe deviance of observationi,F_iits fitted probability andGthe correction that makes the estimator Fisher consistent (Bianco & Yohai 1996).rhois the function of Croux & Haesbroeck, linear up tocand with derivativeexp(-sqrt(t))after it, for which the estimator exists whenever maximum likelihood does. Withweighted=True(the weighted Bianco-Yohai estimator) the sum runs over the observations whose robust distance in theXspace is at most the 0.975 chi-square quantile, which also protects against bad leverage points; it needs continuous regressors. R’sglmrob(method = "WBY")uses those weights only for the starting value and then minimizes the unweighted criterion.- Parameters:
c (float, default 0.5) – Tuning constant of
rho.weighted (bool, default True) – Leave out the leverage points flagged by a deterministic
MCDwithalpha=0.75.fit_intercept (bool, default True) – Add an intercept.
max_iter (int, default 1000) – Maximum BFGS iterations; a
RuntimeWarningreports non-convergence.
- coef_¶
Slopes.
- Type:
ndarray of shape (n_features,)
- intercept_¶
Intercept; 0 without
fit_intercept.- Type:
float
- cov_params_¶
Asymptotic (sandwich) covariance matrix of
[intercept_, *coef_].- Type:
ndarray of shape (p, p)
- std_errors_, z_values_, p_values_
Standard errors, z statistics and two-sided normal p-values.
- Type:
ndarray of shape (p,)
- weights_¶
psi(d_i) / psi(0), the weight of each deviance, and 0 for the leverage points left out.- Type:
ndarray of shape (n_samples,)
- objective_¶
Mean of the minimized criterion.
- Type:
float
- classes_¶
Class labels.
- Type:
ndarray of shape (2,)
References
Bianco, A. M. and Yohai, V. J. (1996). Robust estimation in the logistic regression model. In Robust Statistics, Data Analysis, and Computer Intensive Methods, Lecture Notes in Statistics 109, 17-34. Springer.
Croux, C. and Haesbroeck, G. (2003). Implementing the Bianco and Yohai estimator for logistic regression. Computational Statistics & Data Analysis, 44(1-2), 273-295.
Examples
>>> import numpy as np >>> from robustmodels.glm import BYLogisticRegression >>> rng = np.random.default_rng(0) >>> X = rng.normal(size=(200, 1)) >>> y = rng.binomial(1, 1 / (1 + np.exp(-1 - 2 * X[:, 0]))) >>> X[:5], y[:5] = 8, 0 # five bad leverage points >>> fit = BYLogisticRegression().fit(X, y) >>> round(fit.intercept_, 2), fit.coef_.round(2).tolist() (0.91, [1.88])
- decision_function(X)¶
Linear predictor
X @ coef_ + intercept_(log odds ofclasses_[1]).
- predict(X)¶
Most probable class.
- predict_proba(X)¶
Probabilities of
classes_[0]andclasses_[1], one row per observation.
- summary(feature_names=None)¶
Coefficient table as R’s
summary(glmrob).- Parameters:
feature_names (sequence of str, optional) – Names of the columns of
X;x0, x1, ...by default.- Returns:
Estimates, standard errors, z values and two-sided normal p-values.
- Return type:
str
- class MTPoissonRegressor(*, c=2.1, x_weights='none', fit_intercept=True, n_trials=500, max_iter=500, random_state=None)[source]¶
MT-estimator of Poisson regression (Valdora & Yohai 2014).
The square root stabilizes the variance of a Poisson count, so the estimator is an M-estimator on that scale: it minimizes
sum(w(x_i) rho(sqrt(y_i) - m(mu_i)))withrhoTukey’s bisquare andm(mu)the value that minimizesE[rho(sqrt(Y) - m)]forYPoisson with meanmu. This defining correction is Fisher consistent; its implementation here uses a numerical spline approximation. Becauserhois bounded, gross outliers get weight 0. The search starts from subsamples: each gives a fit, the half of the data with the smallest deviances is refit by maximum likelihood, and the candidate with the smallest criterion is improved with BFGS, as R’sglmrob(method = "MT").mis a cubic Hermite spline with implicit derivatives at its nodes, extended beyond a mean of 100 bysqrt(mu) + a / sqrt(mu)(robustbase switches tosqrt(mu)there, with a small jump). The search does not certify a global minimum.- Parameters:
c (float, greater than 1, default 2.1) – Bisquare tuning constant on the square-root scale, where the standard deviation is about 1/2. Values at most 1 are excluded: the expected loss then has a flat location at zero for sufficiently small means, violating the increasing-transformation requirement. This necessary bound alone does not establish uniqueness or the other asymptotic regularity assumptions for every larger tuning constant.
x_weights ({"none", "hat", "mcd"}, default "none") – Weights on the regressors, as in
MallowsPoissonRegressor.fit_intercept (bool, default True) – Add an intercept.
n_trials (int, default 500) – Random starting subsamples.
max_iter (int, default 500) – Maximum BFGS iterations; a
RuntimeWarningreports non-convergence.random_state (int, numpy.random.Generator, numpy.random.RandomState or None) – Seed of the subsamples.
- coef_¶
Slopes.
- Type:
ndarray of shape (n_features,)
- intercept_¶
Intercept; 0 without
fit_intercept.- Type:
float
- cov_params_¶
Empirical score/Jacobian sandwich covariance of
[intercept_, *coef_]. Asymptotic inference requires a locally identified regular solution. At the numerical predictor cap the covariance is unavailable (NaNs) and the fit is reported as non-converged.- Type:
ndarray of shape (p, p)
- std_errors_, z_values_, p_values_
Standard errors, z statistics and two-sided normal p-values.
- Type:
ndarray of shape (p,)
- weights_¶
Bisquare weights of
sqrt(y_i) - m(mu_i)timesw(x_i).- Type:
ndarray of shape (n_samples,)
- objective_¶
Minimized criterion.
- Type:
float
References
Valdora, M. and Yohai, V. J. (2014). Robust estimators for generalized linear models. Journal of Statistical Planning and Inference, 146, 31-48.
Examples
>>> import numpy as np >>> from robustmodels.glm import MTPoissonRegressor >>> rng = np.random.default_rng(0) >>> X = rng.normal(size=(200, 1)) >>> y = rng.poisson(np.exp(1 + 0.5 * X[:, 0])) >>> y[:30] = 40 # thirty outliers >>> fit = MTPoissonRegressor(n_trials=50, random_state=0).fit(X, y) >>> round(fit.intercept_, 2), fit.coef_.round(2).tolist() (0.97, [0.57]) >>> int((fit.weights_[:30] == 0).sum()) 30
- predict(X)¶
Fitted mean
exp(X @ coef_ + intercept_).
- summary(feature_names=None)¶
Coefficient table as R’s
summary(glmrob).- Parameters:
feature_names (sequence of str, optional) – Names of the columns of
X;x0, x1, ...by default.- Returns:
Estimates, standard errors, z values and two-sided normal p-values.
- Return type:
str