All formulas

Linear algebra

Mahalanobis distance

linalg.mahalanobisAlso called mahalanobis, mahalanobis distance, mahal

DM(x)=(x−μ)⊤Σ−1(x−μ)D_M(x) = \sqrt{(x - \mu)^\top \Sigma^{-1} (x - \mu)}

Distance from x to a distribution with mean μ and covariance Σ, in units that account for the covariance.

Notation

xx

the point

x ∈ ℝd

μ\mu

mean vector

μ ∈ ℝd

Σ\Sigma

covariance matrix, symmetric positive definite

Σ ∈ ℝd×d, symmetric positive definite

dd

dimension

Size, at least 1

DM(x)D_M(x)

Result: the distance

scalar

Worked examples

Each result is solved exactly and confirmed by two independent computations.

  1. Given

    x=[1,2],μ=[0,0],Σ=[[1,0],[0,1]]x = [1, 2], \mu = [0, 0], \Sigma = \left[\left[1, 0\right], \left[0, 1\right]\right]

    Result

    DM(x)=5\displaystyle D_M(x) = \sqrt{5}

    ≈ 2.2360679775

  2. Given

    x=[1,0],μ=[0,0],Σ=[[2,1],[1,2]]x = [1, 0], \mu = [0, 0], \Sigma = \left[\left[2, 1\right], \left[1, 2\right]\right]

    Result

    DM(x)=63\displaystyle D_M(x) = \frac{\sqrt{6}}{3}

    ≈ 0.816496580928

  3. Given

    x=[2,1],μ=[0,0],Σ=[[4,0],[0,1]]x = [2, 1], \mu = [0, 0], \Sigma = \left[\left[4, 0\right], \left[0, 1\right]\right]

    Result

    DM(x)=2\displaystyle D_M(x) = \sqrt{2}

    ≈ 1.41421356237

  4. Given

    x=[3,1],μ=[1,1],Σ=[[4,0],[0,9]]x = [3, 1], \mu = [1, 1], \Sigma = \left[\left[4, 0\right], \left[0, 9\right]\right]

    Result

    DM(x)=1\displaystyle D_M(x) = 1

Common mistakes

  • Uses Σ where Σ−1 belongs

    The quadratic form multiplies by the covariance instead of its inverse. SciPy's mahalanobis takes the inverse covariance as its third argument.

    Fix: Solve Σv = (x − μ) and use √((x − μ)Tv), or pass the inverse to scipy.spatial.distance.mahalanobis.

  • Returns the squared distance

    The final square root is missing.

    Fix: Take the square root of the quadratic form.

Source

  • Bishop 2006

    Bishop, Christopher M. Pattern Recognition and Machine Learning. Springer, 2006.