Rank-based regression and exact rank tests¶
Rank-based methods in robustmodels.rank: R-estimation of the linear model
with Wilcoxon scores, its drop in dispersion test, and exact Wilcoxon tests
that condition on ties.
Rank regression¶
RankRegressor minimizes Jaeckel’s dispersion of the residuals, a weighted
sum of the residuals by their ranks. It is equivalent to least absolute
deviations on all pairwise differences, so it needs no tuning constant and no
scale estimate, and its fit is the exact minimum of a linear program. Its
Gaussian efficiency is 95.5% and it is more efficient than least squares for
heavy-tailed errors. It resists outliers in the response, not leverage points
in the predictors: for those, use MM or LTS regression.
>>> import numpy as np
>>> from robustmodels.rank import RankRegressor
>>> rng = np.random.default_rng(0)
>>> X = rng.normal(size=(100, 2))
>>> y = 1 + X @ [2.0, -1.0] + rng.standard_t(3, size=100)
>>> y[:5] += 20 # five outliers in the response
>>> fit = RankRegressor().fit(X, y)
>>> round(fit.intercept_, 2), fit.coef_.round(2).tolist()
(0.85, [2.14, -1.17])
>>> print(fit.summary())
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.8524 0.1747 4.879 4.17e-06
x0 2.138 0.1297 16.486 6.95e-30
x1 -1.168 0.1331 -8.774 5.92e-14
Drop in dispersion test: F = 97.89 on 2 and 97 degrees of freedom, p-value 5.39e-24
Robust R-squared: 0.6687
Least squares gives (1.95, 2.3, -1.34) for the same data. The standard
errors use the scale tau of Koul, Sievers and McKean (1987) for the slopes
and tau_s, from the confidence interval of the median, for the intercept.
For large samples the tau calculation selects its quantile and counts
distances in sorted rows with linear auxiliary memory. The slope fit starts
from Rfit’s BFGS minimization of the dispersion, then solves the linear
program only on the pairs whose residuals are close; the other pairs keep
their signs and enter as one linear term (Portnoy and Koenker).
The solution is accepted only when no excluded pair can change sign, so the
fit is still the exact minimum: a sample of 2,000 takes about a second
instead of minutes. With group indicators the minimum is often not unique
(as the median of an even number of values); the fit is then the minimizer
with the smallest residual sum of squares, so tau, drop_test and
rank_anova do not depend on the group labels or the contrasts.
drop_test(full, reduced) compares nested fits on the same response, the rank
analogue of the F test; summary() reports it for all slopes, with the robust
R² of Rfit. rank_anova(y, groups) is the one-way analysis of variance by
ranks (Rfit’s oneway.rfit): the drop test of the model with one center per
group.
The drop test checks that the response is the same in the same row order
and that the reduced design lies in the full design’s column space,
including the intercept. Its F calibration is approximate under independent,
identically distributed continuous errors. Inference that requires an
unidentified residual scale is reported as NaN. With one residual degree
of freedom, the small-sample factor for tau_s uses a denominator of one
in place of the zero in Rfit’s correction.
>>> from robustmodels.rank import rank_anova
>>> groups = np.repeat(["a", "b", "c"], 15)
>>> y3 = rng.standard_t(3, size=45) + np.repeat([0.0, 0.0, 1.5], 15)
>>> rank_anova(y3, groups).df
(2, 42)
An exact Kruskal-Wallis test conditional on ties would need the joint
distribution of the rank sums of all groups but one; R’s coin and
exactRankTests offer exact rank tests only for one and two samples. For small
samples, scipy.stats.permutation_test enumerates all assignments. The residual diagnostics of plots accept a fitted
RankRegressor, whose scale_ is the MAD of the residuals.
Exact tests with ties¶
rank_sum_test(x, y) (Wilcoxon–Mann–Whitney) and signed_rank_test(x, y)
(one-sample or paired Wilcoxon) compute exact p-values from the permutation
distribution of the observed midranks. That distribution depends on the ties;
tables or algorithms that assume no ties give other p-values:
>>> from scipy import stats
>>> from robustmodels.rank import rank_sum_test, signed_rank_test
>>> x, y = [1, 2, 2, 3, 3, 3, 5], [2, 3, 4, 4, 5, 6]
>>> round(rank_sum_test(x, y).pvalue, 4)
0.1166
>>> round(float(stats.mannwhitneyu(x, y, method="exact").pvalue), 4) # ignores the ties
0.1375
>>> d = [0.5, -1, 1, 2, 2, -0.5, 3, 1, 0, 1.5]
>>> round(signed_rank_test(d).pvalue, 4), round(signed_rank_test(d, zero_method="pratt").pvalue, 4)
(0.0508, 0.0547)
The two-sided p-value of the rank sum counts the assignments at least as far
from the mean as the observed one, as R’s coin and exactRankTests; the
signed-rank distribution is symmetric, so both conventions agree there. Zeros
are dropped ("wilcox", R’s default) or ranked without a sign ("pratt",
coin’s default). The distributions are computed on doubled midranks, which
are integers, so ties compare exactly. Computing the rank sum distribution
costs about m N^3 operations for samples of sizes m <= n and N = m + n.
For paired signed ranks the null shift mu is subtracted from x - y. The
test sums the three terms accurately so that a small shift remains visible
when two large terms cancel. If the final difference overflows float64,
the test raises ValueError. Rescale both samples and mu to common units
before testing in that case.
Numerical checks and sources¶
Exact p-values equal the enumeration of every assignment or sign pattern in small samples with ties and zeros, all three alternatives; they also equal scipy’s exact tests without ties and R’s
exactRankTests::wilcox.exactand coin’s exactwilcox_testandwilcoxsign_teston frozen tied data.The fit is the exact minimum of the dispersion: random perturbations never lower the pairwise loss, and with one predictor it equals the weighted median of the pairwise slopes. Rfit’s quasi-Newton minimum is never lower and agrees to about 1e-3 in the coefficients.
tautakes the 0.8 quantile of the pairwise residual differences exactly, where Rfit’s default routine solves for it numerically to an absolute tolerance of 1.2e-4, and its R version can step to a neighbouring order statistic through rounding. On Rfit’s residuals the two agree to 1e-4. The estimates converge to their population values at the normal model.Rfit standardizes the scores so that their sum of squares is
n + 1and applies small-sample corrections totauandtau_s; these are kept because in simulations (n = 20and40, normal, t3 and contaminated errors) they gave 95% intervals and 5% drop tests closer to the nominal levels than the unstandardized scores. The test suite checks the coverage and the size under t3 errors.
Sources are Jaeckel (1972), McKean and Hettmansperger (1976), Koul, Sievers and McKean (1987), Hettmansperger and McKean (2011), Kloke and McKean (2012), Streitberg and Röhmel (1986), Hothorn et al. (2006) and Pratt (1959).
Reference¶
- class RankRegressor[source]¶
Rank-based (R) estimator of linear regression with Wilcoxon scores (Jaeckel 1972).
The slopes minimize Jaeckel’s dispersion
D(b) = sum(a(R_i) e_i)of the residualse = y - X b, withR_ithe rank ofe_iand Wilcoxon scoresa(i) = sqrt(12) (i - (n + 1) / 2) / sqrt(n (n - 1)), which Rfit standardizes so thatsum(a(i)^2) = n + 1. AsDequalssqrt(3 / (n (n - 1)))times the sum of|e_i - e_j|over pairs, the fit is an L1 regression on the pairwise differences, solved exactly by linear programming (Rfit approximates it by quasi-Newton steps).Dignores the intercept, which is the median of the residuals. The Gaussian efficiency of the slopes is3 / pi = 95.5%, and they are more efficient than least squares for heavy tails; they resist outliers inybut not leverage points inX. The covariance of the coefficients istau^2 (X'X)^-1for the centred slopes and addstau_s^2 / nto the variance of the intercept, withtauestimated as Koul, Sievers & McKean (1987) andtau_sfrom the confidence interval of the median. Score standardization and small-sample corrections are Rfit’s: in simulations they gave 95% intervals and 5% tests closer to their nominal levels than the unstandardized scores. Uses then (n - 1) / 2pairs of observations, so memory grows asn^2.- coef_¶
Slopes.
- Type:
ndarray of shape (n_features,)
- intercept_¶
Median of
y - X @ coef_.- Type:
float
- scale_¶
MAD of the residuals, which standardizes them in the diagnostic plots.
- Type:
float
- dispersion_¶
Jaeckel’s dispersion of the residuals at the fit.
- Type:
float
- tau_¶
Scale parameter of the slopes;
1 / (sqrt(12) integral f^2)for error densityf.- Type:
float
- tau_s_¶
Scale parameter of the intercept,
1 / (2 f(median)).- Type:
float
- cov_params_¶
Asymptotic covariance of
[intercept_, *coef_].- Type:
ndarray of shape (n_features + 1, n_features + 1)
- std_errors_, t_values_, p_values_
Standard errors, t statistics and two-sided p-values from a t distribution with
n - p - 1degrees of freedom, as Rfit.- Type:
ndarray of shape (n_features + 1,)
References
Jaeckel, L. A. (1972). Estimating regression coefficients by minimizing the dispersion of the residuals. The Annals of Mathematical Statistics, 43(5), 1449-1458.
Koul, H. L., Sievers, G. L. and McKean, J. W. (1987). An estimator of the scale parameter for the rank analysis of linear models under general score functions. Scandinavian Journal of Statistics, 14(2), 131-141.
Hettmansperger, T. P. and McKean, J. W. (2011). Robust Nonparametric Statistical Methods, 2nd edition. CRC Press.
Kloke, J. D. and McKean, J. W. (2012). Rfit: Rank-based estimation for linear models. The R Journal, 4(2), 57-64.
Examples
>>> import numpy as np >>> from robustmodels.rank import RankRegressor >>> rng = np.random.default_rng(0) >>> X = rng.normal(size=(100, 2)) >>> y = 1 + X @ [2.0, -1.0] + rng.standard_t(3, size=100) >>> y[:5] += 20 # five outliers move least squares to (1.95, 2.3, -1.34) >>> fit = RankRegressor().fit(X, y) >>> round(fit.intercept_, 2), fit.coef_.round(2).tolist() (0.85, [2.14, -1.17])
- summary(feature_names=None)[source]¶
Coefficient table and test of all slopes, as R’s
summary(rfit).- Parameters:
feature_names (sequence of str, optional) – Names of the columns of
X;x0, x1, ...by default.- Returns:
Estimates, standard errors, t values and two-sided p-values, then the drop in dispersion test that all slopes are zero (see
drop_test()) and its robust R².- Return type:
str
- drop_test(full, reduced=None)[source]¶
Drop in dispersion test of nested rank regressions (McKean & Hettmansperger 1976).
F = ((D_reduced - D_full) / q) / (tau / 2), withDthe Jaeckel dispersions of both fits,qthe number of slopes dropped andtaufrom the full model, compared with an F distribution onqandn - p - 1degrees of freedom, as Rfit’sdrop.test. It is the rank analogue of the F test of nested linear models, with approximate calibration for independent, identically distributed continuous errors. With an unidentified residual scale, the statistic and p-value are NaN.- Parameters:
full (fitted RankRegressor)
reduced (fitted RankRegressor, optional) – Fitted to the same
ywith a subset of the columns of the full model (or of their linear combinations). By default, the model with no slopes: the test that all slopes are zero.
- Returns:
statistic,df((q, n - p - 1)) andpvalue.- Return type:
DropTestResult
References
McKean, J. W. and Hettmansperger, T. P. (1976). Tests of hypotheses based on ranks in the general linear model. Communications in Statistics - Theory and Methods, 5(8), 693-709.
Examples
>>> import numpy as np >>> from robustmodels.rank import RankRegressor, drop_test >>> rng = np.random.default_rng(1) >>> X = rng.normal(size=(60, 3)) >>> y = 2 * X[:, 0] + rng.standard_t(3, size=60) # the last two columns do not matter >>> full, reduced = RankRegressor().fit(X, y), RankRegressor().fit(X[:, :1], y) >>> round(drop_test(full, reduced).pvalue, 2), bool(drop_test(full).pvalue < 1e-6) (0.7, True)
- rank_anova(y, groups)[source]¶
Rank-based one-way analysis of variance, as Rfit’s
oneway.rfit.Fits the one-way model
y = mu_g + ewithRankRegressoron indicator columns of the groups and tests that all group centers are equal withdrop_test(). Unlike the Kruskal-Wallis test it estimates the group effects and their standard errors, and it extends to other designs throughRankRegressoranddrop_test().- Parameters:
y (array-like of shape (n_samples,)) – Response.
groups (array-like of shape (n_samples,)) – Group of each observation; at least two groups.
- Returns:
statistic,df((k - 1, n - k)) andpvalue.- Return type:
DropTestResult
References
Hettmansperger, T. P. and McKean, J. W. (2011). Robust Nonparametric Statistical Methods, 2nd edition, Section 4.2. CRC Press.
Examples
>>> import numpy as np >>> from robustmodels.rank import rank_anova >>> rng = np.random.default_rng(0) >>> groups = np.repeat(["a", "b", "c"], 15) >>> y = rng.standard_t(3, size=45) + np.repeat([0.0, 0.0, 1.5], 15) >>> result = rank_anova(y, groups) >>> result.df, round(result.pvalue, 4) ((2, 42), 0.0081)
- rank_sum_test(x, y, *, alternative='two-sided')[source]¶
Exact Wilcoxon-Mann-Whitney test, conditional on ties.
The statistic is
U = W - m (m + 1) / 2, withWthe sum of the midranks ofxin the pooled sample of sizesmandn. Under the hypothesis that both samples come from the same distribution, every assignment of the observed midranks to the samples is equally likely; the p-value is computed from that exact distribution, by the shift algorithm of Streitberg & Röhmel (1986) on doubled (integer) midranks. With ties this differs from the distribution without ties used by many programs (scipy’smannwhitneyu(method="exact")among them). The two-sided p-value isP(|W - E W| >= |w - E W|), as R’s coin and exactRankTests. The cost grows asm (m + n)^3: a few hundred observations take seconds.- Parameters:
x (array-like of shape (m,) and (n,)) – Samples; ties are allowed.
y (array-like of shape (m,) and (n,)) – Samples; ties are allowed.
alternative ({"two-sided", "less", "greater"}, default "two-sided") – “greater”:
xtends to be larger thany.
- Returns:
statistic(U) andpvalue.- Return type:
RankTestResult
References
Streitberg, B. and Röhmel, J. (1986). Exact distributions for permutation and rank tests: an introduction to some recently published algorithms. Statistical Software Newsletter, 12(1), 10-17.
Hothorn, T., Hornik, K., van de Wiel, M. A. and Zeileis, A. (2006). A Lego system for conditional inference. The American Statistician, 60(3), 257-263.
Examples
>>> from robustmodels.rank import rank_sum_test >>> result = rank_sum_test([1, 2, 2, 3, 3, 3, 5], [2, 3, 4, 4, 5, 6]) >>> result.statistic, round(result.pvalue, 4) (10.0, 0.1166)
- signed_rank_test(x, y=None, *, mu=0.0, zero_method='wilcox', alternative='two-sided')[source]¶
Exact Wilcoxon signed-rank test, conditional on ties and zeros.
The statistic
Vis the sum of the midranks of|d|over the positive differencesd = (x - y) - mu(orx - mu). Under the hypothesis thatdis symmetric about zero, each sign is equally likely given the observed midranks; the p-value is computed from that exact distribution on doubled (integer) midranks. Zero differences are dropped before ranking ("wilcox", as R’swilcox.test) or ranked with the others and given no sign ("pratt", as coin’s default). The distribution is symmetric, so the two-sided p-value doubles the smaller tail.- Parameters:
x (array-like of shape (n,)) – Sample, or first measurements of pairs.
y (array-like of shape (n,), optional) – Second measurements of the pairs.
mu (float, default 0.0) – Center under the hypothesis, subtracted from
x - y.zero_method ({"wilcox", "pratt"}, default "wilcox")
alternative ({"two-sided", "less", "greater"}, default "two-sided") – “greater”: the differences tend to be positive.
- Returns:
statistic(V) andpvalue; 1 when every difference is zero.- Return type:
RankTestResult
- Raises:
ValueError – If
muis not a finite scalar or a difference overflows float64.
References
Wilcoxon, F. (1945). Individual comparisons by ranking methods. Biometrics Bulletin, 1(6), 80-83.
Pratt, J. W. (1959). Remarks on zeros and ties in the Wilcoxon signed rank procedures. Journal of the American Statistical Association, 54(287), 655-667.
Examples
>>> from robustmodels.rank import signed_rank_test >>> result = signed_rank_test([0.5, -1, 1, 2, 2, -0.5, 3, 1, 0, 1.5]) >>> result.statistic, round(result.pvalue, 4) (39.5, 0.0508)