Shape-constrained estimation

Estimators that replace a tuning constant by a shape restriction, in robustmodels.shape: a log-concave density estimate needs no bandwidth, and regression by antitonic score matching needs no loss function.

Log-concave densities

A density is log-concave when its logarithm is concave. Normal, logistic, Laplace, gamma and beta densities with shape at least one, and uniform densities, all are. Such densities are unimodal with tails at most exponential. Among them, LogConcaveDensity finds the one of largest likelihood (Walther 2002). The estimate exists for any sample with two distinct values, needs no bandwidth, and its log density is piecewise linear, with knots at some observations (Dümbgen & Rufibach 2009).

>>> import numpy as np
>>> from robustmodels.shape import LogConcaveDensity
>>> x = np.random.default_rng(3).gamma(2, size=250)
>>> fit = LogConcaveDensity().fit(x)
>>> fit.knots_.round(3).tolist()
[0.145, 0.709, 1.272, 1.327, 1.329, 2.848, 5.934, 8.969]
>>> np.exp(fit.score_samples([0.5, 2, 5])).round(3).tolist()
[0.192, 0.291, 0.041]
>>> fit.cdf([1, 2, 4]).round(3).tolist()
[0.183, 0.528, 0.887]

The estimate is zero outside the range of the sample, has the mean of the sample and at most its variance. When the restriction is in doubt, compare it with a kernel estimate: two modes or heavier tails contradict it.

import numpy as np
from robustmodels import plots
from robustmodels.shape import LogConcaveDensity

x = np.random.default_rng(3).gamma(2, size=250)
plots.log_concave_plot(LogConcaveDensity().fit(x))

(png, svg)

Log-concave density estimate with its knots over the histogram of a gamma sample.

Regression by antitonic score matching

An M-estimator with a convex loss has a unique solution that is easy to compute, but its efficiency depends on how well the loss fits the errors: least squares for normal errors, least absolute deviations for Laplace errors. ScoreMatchingRegressor estimates the loss from the data (Feng, Kao, Xu & Samworth 2024). Its derivative is minus the antitonic projected score: the decreasing function closest to the score (log p)' of the error density p. Among convex M-estimators, this loss gives the smallest asymptotic variance. For log-concave errors it is the maximum likelihood loss. For heavier tails it is bounded, so it resists outliers in the response.

>>> from robustmodels.shape import ScoreMatchingRegressor
>>> rng = np.random.default_rng(4)
>>> X = rng.normal(size=(400, 2))
>>> y = 1 + X @ [2.0, -1.0] + rng.standard_t(2, 400)  # least squares: (0.69, 2.0, -0.86)
>>> fit = ScoreMatchingRegressor().fit(X, y)
>>> print(fit.summary(["x1", "x2"]))
               Estimate  Std. Error   z value  Pr(>|z|)
(Intercept)      0.9944     0.07473    13.306  2.12e-40
x1                2.103     0.07094    29.641  4.43e-193
x2               -1.021     0.07708   -13.242  5e-40

The fit starts from least absolute deviations, estimates the score from its residuals with a normal kernel density estimate, minimizes the convex loss, and re-estimates the score once. Standard errors come from (information_ X'X)^-1, with information_ the mean squared score of the residuals. With symmetric=True (default) the errors are assumed symmetric and the intercept is estimated with the slopes. With symmetric=False the slopes need no symmetry, and the intercept is the median of the residuals. When the data fit a line exactly to numerical precision, the coefficients are available and the score and standard errors are reported as NaN. The published efficiency theorem uses sample splitting under its own regularity conditions. The implementation follows the practical two-pass fit on the whole sample.

import numpy as np
from robustmodels import plots
from robustmodels.shape import ScoreMatchingRegressor

rng = np.random.default_rng(4)
X = rng.normal(size=(400, 2))
y = 1 + X @ [2.0, -1.0] + rng.standard_t(2, 400)
plots.score_plot(ScoreMatchingRegressor().fit(X, y), X, y)

(png, svg)

Estimated antitonic score, bounded in the tails, against the normal score.

The score resists outliers in the response, not leverage points; for those, use MMRegressor. With normal errors the fit is close to least squares.

Numerical checks and sources

The log-concave estimate is checked against its characterization (Dümbgen & Rufibach 2009): the log density is concave, no kink at an observation increases the likelihood, the density integrates to one, and its mean is the sample mean. Two distinct values give the uniform density. The integrals of the exponential of linear functions match numerical quadrature. On frozen data R’s logcondens 2.1 finds the same knots, and our log-likelihoods are higher: logcondens stops its Newton steps earlier.

For the regression, the estimated score is decreasing (and odd when symmetric), the fit solves the estimating equation X' psi(residuals) = 0, and it is regression and scale equivariant. With normal errors it is close to least squares. On frozen data R’s asm 0.2 gives the same coefficients (to 1e-6) and standard errors (to 1e-4); the density estimate of the residuals is binned on the same grid. asm fails when more than half the residuals are equal; robustmodels then uses all residuals for the density estimate.

Sources are Walther (2002), Pal, Woodroofe & Meyer (2007), Dümbgen & Rufibach (2009, 2011), Dümbgen, Hüsler & Rufibach (2007) and Feng, Kao, Xu & Samworth (2024); see the method references.

Reference

class LogConcaveDensity[source]

Maximum likelihood estimate of a univariate log-concave density (Walther 2002).

Among all densities f = exp(phi) with phi concave, which include the normal, logistic, gamma and beta densities with shape at least one, the estimate maximizes the likelihood. It exists and is unique for two or more distinct observations, needs no bandwidth, and phi is piecewise linear with knots at some observations, -inf outside their range (Pal, Woodroofe & Meyer 2007; Dümbgen & Rufibach 2009). It is computed by the active set algorithm of Dümbgen, Hüsler & Rufibach (2007), as R’s logcondens: Newton steps for the values of phi at a set of knots, which grows where the likelihood can increase and shrinks where phi would stop being concave. The estimate has the mean of the sample and at most its variance (divisor n).

support_

Sorted distinct observations.

Type:

ndarray of shape (n_distinct,)

weights_

Share of the sample at each of them.

Type:

ndarray of shape (n_distinct,)

log_density_

phi at support_.

Type:

ndarray of shape (n_distinct,)

knots_

Observations where the slope of phi changes, with the extremes.

Type:

ndarray

References

Walther, G. (2002). Detecting the presence of mixing with multiscale maximum likelihood. Journal of the American Statistical Association, 97(458), 508-513.

Pal, J. K., Woodroofe, M. and Meyer, M. (2007). Estimating a Polya frequency function_2. In Complex Datasets and Inverse Problems, IMS Lecture Notes 54, 239-249.

Dümbgen, L. and Rufibach, K. (2009). Maximum likelihood estimation of a log-concave density and its distribution function: basic properties and uniform consistency. Bernoulli, 15(1), 40-68.

Dümbgen, L., Hüsler, A. and Rufibach, K. (2007). Active set and EM algorithms for log-concave densities based on complete and censored data. Technical report 61, University of Bern. arXiv:0707.4643.

Examples

>>> import numpy as np
>>> from robustmodels.shape import LogConcaveDensity
>>> x = np.random.default_rng(0).gamma(3, size=200)
>>> fit = LogConcaveDensity().fit(x)
>>> len(fit.knots_), np.exp(fit.score_samples([1, 3, 6])).round(3).tolist()
(7, [0.186, 0.22, 0.039])
>>> fit.cdf([1, 3, 6]).round(3).tolist()
[0.068, 0.612, 0.943]
fit(X, y=None)[source]

Fit to the one-dimensional sample X; y is ignored. Returns self.

score_samples(X)[source]

Log density at each value of X (-inf outside the range of the sample).

cdf(X)[source]

Distribution function at each value of X.

class ScoreMatchingRegressor(*, symmetric=True)[source]

Linear regression by antitonic score matching (Feng, Kao, Xu & Samworth 2024).

Among M-estimators with a convex loss, the smallest asymptotic variance is reached by the loss whose derivative is minus the antitonic projected score psi*: the decreasing function closest to the score (log p)' of the error density p in mean square. psi* = (log p)' when p is log-concave, and psi* is bounded when p has heavier tails than an exponential distribution, so the estimate resists outliers in the response (not leverage points). The estimate needs no tuning: from the residuals of a least absolute deviations fit, psi* is estimated by the slopes of the least concave majorant of J = p o F^-1, with p and F from a normal kernel density estimate (bandwidth bw.nrd0), on a grid of max(3000, 2n) quantiles. The coefficients minimize the convex loss by Newton steps, and the score is re-estimated once from the new residuals, as R’s asm.

Parameters:

symmetric (bool, default True) – Assume errors symmetric about zero: the score is symmetrized and the intercept is estimated with the slopes. Otherwise the slopes are estimated with centred predictors and the intercept is the median of y - X @ coef_, with the variance of a sample median.

coef_
Type:

ndarray of shape (n_features,)

intercept_
Type:

float

scale_

MAD of the residuals, which standardizes them in the diagnostic plots.

Type:

float

information_

Mean of psi(residuals)^2, the estimated Fisher information int psi*^2 p of the projected score.

Type:

float

cov_params_

Asymptotic covariance of [intercept_, *coef_]: (information_ X'X)^-1 for symmetric errors.

Type:

ndarray of shape (n_features + 1, n_features + 1)

std_errors_, z_values_, p_values_

Standard errors, z statistics and two-sided normal p-values.

Type:

ndarray of shape (n_features + 1,)

score_knots_, score_values_

The estimated score before symmetrization: linear between these points and constant beyond them. psi() evaluates it.

Type:

ndarray

Notes

The density of the residuals is binned on 2^15 points, as in asm, and the fits agree with asm to about 1e-6. When more than half the residuals are equal, asm fails and the density is estimated over the range of all residuals. The variance with symmetric=False follows asm with its "median" intercept; by default asm uses the mean of the residuals.

The efficiency result in the reference is for a sample-split estimator under its regularity conditions. This implementation uses the two-pass fit on the whole sample. For an exact fit, the score and inference are unavailable and reported as NaN.

References

Feng, O. Y., Kao, Y.-C., Xu, M. and Samworth, R. J. (2024). Optimal convex M-estimation via score matching. arXiv:2403.16688.

Examples

>>> import numpy as np
>>> from robustmodels.shape import ScoreMatchingRegressor
>>> rng = np.random.default_rng(0)
>>> X = rng.normal(size=(300, 2))
>>> y = 1 + X @ [2.0, -1.0] + rng.standard_cauchy(300)  # least squares: (-3.09, -1.23, -6.55)
>>> fit = ScoreMatchingRegressor().fit(X, y)
>>> round(fit.intercept_, 2), fit.coef_.round(2).tolist()
(1.01, [1.92, -0.9])
>>> fit.std_errors_.round(3).tolist()
[0.105, 0.104, 0.106]
fit(X, y)[source]

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

predict(X)[source]

Predicted values X @ coef_ + intercept_.

psi(residuals)[source]

Estimated antitonic score at residuals, or NaN for an exact fit.

summary(feature_names=None)[source]

Coefficient table, as R’s summary(asm).

Parameters:

feature_names (sequence of str, optional) – Names of the columns of X; x0, x1, ... by default.

Return type:

str