Mahalanobis distance measures how far an observation lies from a data distribution while accounting for its center, feature variances, and covariances. Unlike Euclidean distance, it reflects the distribution’s shape: movement along a high-variance direction counts less than equally sized movement along a low-variance direction. The method is therefore useful for assessing outlierness in correlated tabular data. section 5.5 section 5.5.1
Figure 5.6 The middle pane is an example of using Euclidean distance from the center of a dataset to measure the outlierness of datapoints. Here, point A is a stronger outlier than point B but is the same distance from the center using Euclidean distance. The right pane is an example using distances based on fitting an ellipse to the data and provides more meaningful distance measures, allowing us to consider A farther from the center than B.
Compare Euclidean and ellipse-adjusted distances: points equally distant under Euclidean geometry can receive different Mahalanobis distances when the data shape makes one more unusual. section 5.5
The calculation incorporates the inverse covariance matrix, effectively transforming features into an uncorrelated, equal-variance space before applying Euclidean distance. This interpretation connects the method to principal component analysis. Standard use assumes one cluster with roughly Gaussian, or at least unimodal, dimensions. Those assumptions can fail, so flagged observations require investigation rather than automatic acceptance as meaningful anomalies. section 5.5.1
A practical implementation proceeds by:
- Fitting a covariance estimator to the dataset and using its estimated center and covariance matrix. section 5.5.1
- Preferring robust estimators such as minimum covariance determinant or minimum volume ellipsoid when outliers could distort covariance estimates through masking or swamping. section 5.5.1
- Applying mahalanobis() to obtain distances for observations after fitting the estimator. section 5.5.1
- Using cluster-relative distances when the data contains multiple clusters with different shapes or sizes. section 7.8.1
Robust covariance and distance calculation
from sklearn.covariance import MinCovDet cov = MinCovDet(random_state=0).fit(X) distances = cov.mahalanobis(X) Here, MinCovDet estimates the covariance structure and center, while mahalanobis() returns each observation’s covariance-adjusted distance. section 5.5.1
