Mahalanobis distance

Also known as: Mahalanobis outlier detection

On this page 7

Mahalanobis distance is a multivariate distance measure that expresses how far a point lies from the center of a distribution, scaled by the covariance structure of the data, so that directions with high variance count less and correlated features are not double-counted. In anomaly detection, it serves as one of the oldest and most interpretable anomaly scores: points with a large Mahalanobis distance from the mean of normal data are flagged as outliers.

The measure was introduced by the statistician P. C. Mahalanobis in 1936. It underpins Mahalanobis outlier detection, the elliptic envelope, robust covariance methods such as the minimum covariance determinant, and several modern deep-feature detectors, including PaDiM for visual inspection.

How the Mahalanobis distance is calculated

The squared Mahalanobis distance of a point x from a distribution with mean vector mu and covariance matrix Sigma is D^2 = (x - mu)^T Sigma^-1 (x - mu). The inverse covariance matrix is the essential ingredient: it rescales each direction by its variance and removes the effect of correlation between features.

Geometrically, the calculation is equivalent to whitening the data and then measuring ordinary Euclidean distance. Whitening rotates the feature space onto the principal axes of the covariance and divides each axis by its standard deviation. Points with equal Mahalanobis distance therefore lie on ellipsoids aligned with the data cloud, not on spheres.

The table below summarizes the quantities involved and the role of each.

QuantityWhat it representsHow it is usually estimated
Mean vectorCenter of normal behaviorSample mean of training data
Covariance matrixSpread and correlation of featuresSample covariance or a robust estimate
Inverse covarianceScaling and decorrelation of directionsMatrix inversion or Cholesky solve
Squared distanceAnomaly score of one pointQuadratic form of the centered point
Dimension pNumber of featuresFixed by the feature set
Ingredients of the Mahalanobis distance

When the covariance matrix is the identity, the Mahalanobis distance reduces to the Euclidean distance. When it is diagonal, the result equals the Euclidean distance after standardizing each feature to unit variance, so the full measure adds value precisely when features are correlated.

Statistical thresholds for flagging outliers

A major advantage of the Mahalanobis distance is a principled threshold. If normal data follow a multivariate normal distribution with known parameters, the squared distance follows a chi-square distribution with p degrees of freedom. A cutoff can then be read from chi-square quantiles instead of being tuned by hand.

Features p97.5% quantile99% quantile99.9% quantile
27.389.2113.82
512.8315.0920.52
1020.4823.2129.59
2034.1737.5745.31
Chi-square cutoffs for the squared Mahalanobis distance

These cutoffs are only approximate in practice. The parameters are estimated rather than known, real data are rarely exactly Gaussian, and heavy tails inflate false alarms. Many teams therefore treat chi-square quantiles as a starting point and calibrate the final threshold on a validation set with known anomalies or to match a target alert rate.

Robust estimation and the masking problem

The classical sample mean and covariance are highly sensitive to outliers. A cluster of anomalies in the training data pulls the mean toward itself and inflates the covariance, which shrinks their own distances. This effect is called masking; the opposite effect, in which normal points appear anomalous because the estimates are distorted, is called swamping.

Robust covariance estimators solve this by fitting the mean and covariance on the most central subset of the data. The minimum covariance determinant, usually computed with the FastMCD algorithm, searches for the subset whose covariance has the smallest determinant. The elliptic envelope in common libraries applies exactly this idea with a contamination rate parameter that sets the expected share of outliers.

EstimatorStrengthWeaknessTypical setting
Sample covarianceSimple and fastBreaks down with contaminationClean training data
Minimum covariance determinantHigh breakdown pointCostly in high dimensionsContaminated tabular data
Ledoit-Wolf shrinkageStable when samples are fewBiased toward a scaled identityMany features, limited samples
Regularized covarianceAlways invertibleNeeds a tuned penaltyDeep feature embeddings
Covariance estimators used with the Mahalanobis distance

Mahalanobis distance compared with other anomaly scores

The Mahalanobis distance is a global, parametric score that assumes one elliptical cluster of normal data. Other detectors in the field relax that assumption in different ways.

  • Euclidean distance to the mean ignores scale and correlation, so it overweights high-variance features.
  • Local outlier factor and k-NN anomaly detection compare local densities and handle several clusters, but they cost more and offer no closed-form threshold.
  • Isolation forests make no distributional assumption and scale well, yet their scores are harder to explain feature by feature.
  • Autoencoder reconstruction error captures nonlinear structure but needs far more data and tuning.

Because the score is a quadratic form, its value can be decomposed into feature contributions, which supports anomaly explanation. Mahalanobis scoring also performs strongly when applied to features from pretrained networks, a common approach in visual anomaly detection and out-of-distribution detection.

Limitations and common mistakes

The most frequent failure is a singular or ill-conditioned covariance matrix. It occurs when features are linearly dependent or when the number of samples is close to the number of features. Inverting such a matrix produces unstable, meaningless scores; shrinkage, regularization or dimensionality reduction is required.

Other mistakes include applying the measure to multimodal or strongly skewed data, where a single ellipsoid misrepresents normal behavior, and mixing categorical codes with continuous features. Finally, the covariance must be estimated on normal reference data and refreshed when the process drifts; otherwise, gradual change appears as a growing stream of false alarms.

Stripped to the essentials

Mahalanobis distance tells how unusual a point is compared with a group of normal points. It does not just measure a straight line. It also considers how spread out the data are and which measurements tend to move together.

Think of height and weight. A tall, heavy person is common. A tall, very light person is rare, even if the numbers alone do not look extreme. Mahalanobis distance notices that unusual combination. A large distance means the point is a likely anomaly.

Where it is applied

A manufacturing plant monitors a pump with six sensors: vibration on two axes, bearing temperature, motor current, flow rate and outlet pressure. Engineers collect four weeks of readings during verified normal operation and fit a robust mean and covariance with the minimum covariance determinant.

Every minute, the monitoring system computes the squared Mahalanobis distance of the latest reading. The team sets the alert threshold at the 99.9% chi-square quantile for six features, about 22.5, and then adjusts it slightly after a two-week trial to keep false alarms below one per day.

Three months later, motor current and flow rate begin to drift apart while each stays within its own normal range. Their broken correlation pushes the distance above the threshold, and an inspection finds a partially clogged impeller. The fault is repaired during a planned stop, avoiding an unplanned shutdown.