Depth and the bagplot

Depth measures centrality relative to a sample. halfspace_depth is the smallest fraction of observations in a closed halfspace whose boundary passes through the query point. It is exact in one and two dimensions, including ties. Above two dimensions, it searches directions normal to sample hyperplanes and returns an approximation that can overestimate the exact depth. Supply n_directions and random_state to control that search, or exact=True for the exact depth by the recursive algorithm of Dyckerhoff and Mozharovskyi (2016). It needs no general position and costs O(n^(p-1) log n) per point: the depths of all 200 points of a sample in three dimensions take about 6 seconds on a laptop, and those of 60 points in four dimensions about 12.

When the sample lies in a lower-dimensional affine span, the default search works in that span. Queries outside it have depth zero. If the span is a line or a plane, the corresponding one- or two-dimensional calculation is used.

>>> import numpy as np
>>> from robustmodels.depth import halfspace_depth
>>> X3 = np.random.default_rng(1).normal(size=(30, 3))
>>> exact = halfspace_depth(X3, exact=True)
>>> bool(np.all(halfspace_depth(X3, random_state=0) >= exact))  # the search never underestimates
True

regression_depth measures the smallest fraction of observations crossed when tilting a fitted regression plane to a vertical nonfit. It is exact with one predictor. With several predictors, enumerating all directions is exact for data in general position; a limited random search can overestimate depth. Predictors exclude the intercept column. Depths are fractions in [0, 1].

Bivariate center and outliers

halfspace_median returns the area centroid of the deepest bivariate region (or the midpoint of a segment, or its only point). bagplot_stats builds the bag containing approximately half the sample, its inflated fence, the outlier mask, and the loop containing the bag and observations inside the fence. plots.bagplot draws these statistics and returns a Matplotlib axes.

>>> import numpy as np
>>> from robustmodels.depth import bagplot_stats, halfspace_depth
>>> square = [[0, 0], [1, 0], [1, 1], [0, 1], [0.5, 0.5]]
>>> halfspace_depth(square).tolist()
[0.2, 0.2, 0.2, 0.2, 0.6]
>>> X = np.random.default_rng(0).normal(size=(100, 2))
>>> X[:3] = [[6, 6], [7, -6], [-8, 5]]
>>> np.flatnonzero(bagplot_stats(X).outliers).tolist()
[0, 1, 2]

import numpy as np
from robustmodels import plots

X = np.random.default_rng(0).normal(size=(100, 2))
X[:3] = [[6, 6], [7, -6], [-8, 5]]
plots.bagplot(X, feature_names=["First measurement", "Second measurement"])

(png, svg)

Bagplot with a Tukey median, central bag, fence and three outliers.

Comparing two samples

The depth-depth plot (Liu, Parelius & Singh 1999) places every observation of two samples at its depth in each. Samples from one distribution keep the points near the diagonal; a difference in location bends them into a lens, and a difference in spread moves them to one side, as here. density.kde_test tests the difference.

import numpy as np
from robustmodels import plots

rng = np.random.default_rng(4)
control = rng.normal(size=(150, 2))
treated = rng.normal(size=(120, 2)) * [1.6, 1]
plots.dd_plot(control, treated, labels=["Control", "Treated"])

(png, svg)

Depth-depth plot of two samples whose spreads differ, with points off the diagonal.

Numerical checks and limits

The bivariate median and bag use a subset of at most max_samples=200 observations. Set a seed for larger samples. The complete data must span two dimensions; a singular selected subset raises ValueError and requires a larger max_samples. Duplicated observations are supported, including a bag that collapses to a segment or a point. The bag boundary interpolates depth regions over a finite angular grid, so transformed bag vertices need not be exactly affine equivariant. Univariate halfspace depth compares represented values directly, so a distinct external point is not merged into the sample. Bivariate depth evaluates open angular cells after diagonal conditioning; independent rational-sign enumeration checks narrow-angle cases. Opposite offsets from the query point, as when it lies between two observations, share one line angle, and lines closer than 1e-13 radians after the conditioning are taken as one. Version 0.2.0 compared separately rounded angles instead and could open a spurious cell: for the query (0.5, 1.5) between the observations (-1, 0) and (2, 3) of an integer sample it returned 2/9 instead of 3/9. Exact depth in three or more dimensions is checked against linear-programming separation of every subset in small samples and against R’s ddalpha. Projection and region calculations retain numerical tolerances.

The bag interpolates both adjacent depth regions even when the inner one is a nonzero segment. An explicit tied five-point sample checks its diagonal boundary at (13/6, 13/6). Small regression-depth problems in three predictor dimensions are checked by exhaustive deletion and linear-programming separation. Frozen mrfDepth/aplpack outputs retain their provenance for supplementary regression checks; invalid captured depths are excluded as mathematical witnesses. The definition and the independent geometry checks determine correctness, including when external software differs.

Sources are Tukey (1975), Rousseeuw and Ruts (1996, 1998), Rousseeuw and Hubert (1999), Rousseeuw, Ruts and Tukey (1999) and Dyckerhoff and Mozharovskyi (2016); full citations follow.

Reference

halfspace_depth(X, points=None, *, exact=False, n_directions=None, random_state=None)[source]

Halfspace (Tukey) depth of points relative to the sample X.

The depth of z is the smallest fraction of observations in a closed halfspace whose boundary passes through z (Tukey 1975). It is exact for one and two variables (the latter as Rousseeuw & Ruts 1996, in O(n log n) per point). For more variables it is, by default, the smallest univariate depth over directions normal to hyperplanes through p observations, which is affine invariant and never below the exact depth, as the approximate algorithm of R’s mrfDepth. With exact=True it is the exact depth, by the recursive algorithm of Dyckerhoff & Mozharovskyi (2016) in O(n^(p-1) log n) per point, which needs no general position.

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Sample.

  • points (array-like of shape (n_points, n_features), optional) – Points whose depth is computed; the rows of X by default.

  • exact (bool, default False) – Exact depth for three or more variables; n_directions and random_state are then ignored. Practical for p = 3 and a few hundred observations, or p = 4 and about a hundred.

  • n_directions (int, default None) – Directions for three or more variables; 250 * n_features by default. All hyperplanes are used when there are at most that many.

  • random_state (int, numpy.random.Generator, numpy.random.RandomState or None) – Seed for the random directions.

Returns:

Depths in [0, 1]. Exact depths of points outside the convex hull are 0; approximate depths in higher dimensions may be positive.

Return type:

ndarray of shape (n_points,)

References

Tukey, J. W. (1975). Mathematics and the picturing of data. Proceedings of the International Congress of Mathematicians, 2, 523-531.

Rousseeuw, P. J. and Ruts, I. (1996). Algorithm AS 307: Bivariate location depth. Journal of the Royal Statistical Society: Series C, 45(4), 516-526.

Dyckerhoff, R. and Mozharovskyi, P. (2016). Exact computation of the halfspace depth. Computational Statistics & Data Analysis, 98, 19-30.

Examples

>>> import numpy as np
>>> from robustmodels.depth import halfspace_depth
>>> square = np.array([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.5, 0.5]])
>>> halfspace_depth(square).tolist()
[0.2, 0.2, 0.2, 0.2, 0.6]
>>> halfspace_depth(square, [[2.0, 2.0]]).tolist()
[0.0]
regression_depth(X, y, coef, intercept=0.0, *, n_directions=None, random_state=None)[source]

Regression depth of the fit y = intercept + X @ coef (Rousseeuw & Hubert 1999).

The regression depth is the smallest fraction of observations that must be removed to make the fit a nonfit: a fit that can be tilted around some hyperplane of the X space until it is vertical without passing through any observation. A fit with depth 0 fits no data; the deepest fits have a depth of at least 1 / (n_features + 2), and close to 1/2 when the linear model holds with symmetric errors. The depth is exact for one regressor. For more, the tilting hyperplanes pass through n_features observations: all of them when there are at most n_directions, which is exact for data in general position, otherwise a random selection, which never underestimates the depth.

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Regressors, without a constant column.

  • y (array-like of shape (n_samples,)) – Response.

  • coef (array-like of shape (n_features,)) – Slopes of the fit.

  • intercept (float, default 0.0) – Intercept of the fit.

  • n_directions (int, default None) – Number of tilting directions; 250 * n_features by default.

  • random_state (int, numpy.random.Generator, numpy.random.RandomState or None) – Seed for the random directions.

Returns:

Regression depth in [0, 1].

Return type:

float

References

Rousseeuw, P. J. and Hubert, M. (1999). Regression depth. Journal of the American Statistical Association, 94(446), 388-402.

Rousseeuw, P. J. and Struyf, A. (1998). Computing location depth and regression depth in higher dimensions. Statistics and Computing, 8, 193-203.

Examples

>>> import numpy as np
>>> from robustmodels.depth import regression_depth
>>> x = np.arange(10.0)
>>> y = 1 + 2 * x + np.array([1, -1, 1, -1, 1, -1, 1, -1, 1, -1.0])
>>> regression_depth(x[:, None], y, [2.0], 1.0)  # residual signs alternate
0.4
>>> regression_depth(x[:, None], y, [2.0], 5.0)  # the line lies above the data
0.0
halfspace_median(X, *, max_samples=200, random_state=None)[source]

Tukey median of bivariate data: the centre of gravity of the deepest region.

The deepest region is the set of points with the largest halfspace depth, a convex polygon (or a segment or a point). The Tukey median is affine equivariant and its breakdown point is at least 1/3.

Parameters:
  • X (array-like of shape (n_samples, 2)) – Sample.

  • max_samples (int, default 200) – The depth regions are computed from a random subset of this size when the sample is larger, as mrfDepth; the search is exact otherwise.

  • random_state (int, numpy.random.Generator, numpy.random.RandomState or None) – Seed for the subset.

Return type:

ndarray of shape (2,)

References

Rousseeuw, P. J. and Ruts, I. (1998). Constructing the bivariate Tukey median. Statistica Sinica, 8(3), 827-839.

Examples

>>> import numpy as np
>>> from robustmodels.depth import halfspace_median
>>> X = np.array([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]])
>>> halfspace_median(X).round(6).tolist()
[0.5, 0.5]
bagplot_stats(X, *, factor=3.0, max_samples=200, random_state=None)[source]

Elements of the bagplot, the bivariate boxplot of Rousseeuw, Ruts & Tukey (1999).

The bag contains half of the observations: it lies between the two consecutive halfspace depth regions that hold at most and more than half of them, interpolated along rays from the Tukey median. The fence is the bag inflated by factor from the median; observations outside it are outliers, and the loop is the convex hull of the bag and the others.

Parameters:
  • X (array-like of shape (n_samples, 2)) – Sample.

  • factor (float, default 3.0) – Inflation of the bag that gives the fence.

  • max_samples (int, default 200) – The median and the bag are computed from a random subset of this size when the sample is larger, as mrfDepth.

  • random_state (int, numpy.random.Generator, numpy.random.RandomState or None) – Seed for the subset.

Returns:

center (Tukey median), bag, fence and loop (polygon vertices in counterclockwise order, one per row), outliers (boolean mask of the observations outside the fence) and depth (halfspace depth of each observation).

Return type:

sklearn.utils.Bunch

References

Rousseeuw, P. J., Ruts, I. and Tukey, J. W. (1999). The bagplot: a bivariate boxplot. The American Statistician, 53(4), 382-387.

Examples

>>> import numpy as np
>>> from robustmodels.depth import bagplot_stats
>>> X = np.random.default_rng(0).normal(size=(100, 2))
>>> X[:3] = [[6, 6], [7, -6], [-8, 5]]
>>> np.flatnonzero(bagplot_stats(X).outliers).tolist()
[0, 1, 2]