scipy.spatial.distance.

mahalanobis#

scipy.spatial.distance.mahalanobis(u, v, VI)[source]#

Compute the Mahalanobis distance between two arrays.

The Mahalanobis distance between 1-D arrays u and v, is defined as

\[\sqrt{ (u-v) V^{-1} (u-v)^T }\]

where V is the covariance matrix. Note that the argument VI is the inverse of V.

Parameters:
u(…, N) array_like

Input array.

v(…, N) array_like

Input array.

VI(…, N, N) array_like

The inverse of the covariance matrix.

Returns:
mahalanobisfloat or array

The Mahalanobis distance between vectors u and v.

Notes

Array API Standard Support

mahalanobis has support for Python Array API Standard compatible backends in addition to NumPy. The following combinations of backend and device (or other capability) are supported.

Library

CPU

GPU

NumPy

✅

n/a

CuPy

n/a

✅

PyTorch

✅

✅

JAX

✅

✅

Dask

✅

n/a

See Array API coverage for more information.

Examples

>>> from scipy.spatial import distance
>>> iv = [[1, 0.5, 0.5], [0.5, 1, 0.5], [0.5, 0.5, 1]]
>>> distance.mahalanobis([1, 0, 0], [0, 1, 0], iv)
1.0
>>> distance.mahalanobis([0, 2, 0], [0, 1, 0], iv)
1.0
>>> distance.mahalanobis([2, 0, 0], [0, 1, 0], iv)
1.7320508075688772