8
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

マハラノビス距離の求め方

Last updated at Posted at 2019-11-19

マハラノビス距離

d=(x-\mu)^T\Sigma^{-1}(x-\mu)

$x$はデータ群との距離を求めたいベクトル。
$\mu$はデータ群の平均値。
$\Sigma^{-1}$はデータ群の共分散行列の逆行列。
コレスキー分解を使うと、以下のように式変形できる。

\begin{eqnarray}
d &=& (x-\mu)^T\Sigma^{-1}(x-\mu) \\
  &=& (x-\mu)^T(LL^T)^{-1}(x-\mu) \\
  &=& (L^{-1}(x-\mu))^T(L^{-1}(x-\mu)) \\
  &=& z^Tz
\end{eqnarray}

$L$はコレスキー分解によって得られる下三角行列。
$$z=(L^{-1}(x-\mu))$$ として、これを求めればあとは内積を計算するだけ。

実装

以上をpythonで実装します。

import numpy as np
from scipy.linalg import solve_triangular

def mahalanobis(x, mu, sigma):
    L = np.linalg.cholesky(sigma)
    d = x - mu
    z = solve_triangular(
        L, d.T, lower=True, check_finite=False,
        overwrite_b=True)
    squared_maha = np.sum(z * z, axis=0)
    return squared_maha

$L$はnumpyのlinalg.choleskyで求められます。
$z$はscipyのlinalg.solve_triangularで求められます。

参考

8
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?