マハラノビス距離について

これなーに?

マハラノビス距離のメモだよ。

マハラノビス距離って?

2次元以上のベクトル空間において、ある点とある点の距離を平均や分散を考慮して計算するよ。
異常検知などで、ある点とある点の距離から異常か正常かを判断したい場合に、ユークリッド距離は一緒だけど、マハラノビス距離でみると離れていることに気づけるみたいなパターンがあるよ。

↓ こういうの。青の点1と赤の点2は、平均の黒の点からのユークリッド距離は一緒。
だけど、点の集合から考えると青は内側で、赤は外側なので赤の方が異常値だって分かるね。

xとy座標の2次元のマハラノビス距離は、以下の式。

 \displaystyle
MD = \sqrt{
  (x_i - \bar{x} y_i - \bar{y})
  \begin{pmatrix}
     σ_x^2 & σ_{xy} \\
     σ_{xy} & σ_y^2
  \end{pmatrix}^{-1}
  \begin{pmatrix}
     x_i - \bar{x} \\
     y_i - \bar{y}
  \end{pmatrix}
}

真ん中の以下の式は分散・共分散行列の逆行列

 \displaystyle
  \begin{pmatrix}
     σ_x^2 & σ_{xy} \\
     σ_{xy} & σ_y^2
  \end{pmatrix}^{-1}

逆行列は、行列積をすると単位行列になる行列で AA^{-1} = Iになる A^{-1}のこと。

 \displaystyle
  A = \begin{pmatrix}
     a & b \\
     c & d
  \end{pmatrix}

の場合、

 \displaystyle
A^{-1} = \frac{1}{ad - bc}
  \begin{pmatrix}
     d & -b \\
     -c & a
  \end{pmatrix}

になるよ。

 σ_x^{2}はxの分散、 σ_{xy}はxとyの共分散、 σ_y^{2}はyの分散。
xとyのそれぞれの分散やxとyの共分散を考慮して距離を計算するから、散り具合がわかる。
なので、ユークリッド距離が同じでも、変数の散り具合で異常判定などができるって感じね。

具体的な計算例だと、
中心座標が(4.8, 5.1)、観測座標が(6.7, 7.8)、xの分散( σ_x^{2})が2.6、yの分散( σ_y^{2})が2.5、xとyの共分散( σ_{xy})が2.0の場合のマハラノビス距離は、

 \displaystyle
MD = \sqrt{
  (6.7 - 4.8 7.8 - 5.1)
  \begin{pmatrix}
     2.6 & 2.0 \\
     2.0 & 2.5
  \end{pmatrix}^{-1}
  \begin{pmatrix}
     6.7 - 4.8 \\
     7.8 - 5.1
  \end{pmatrix}
}
 \displaystyle
  \begin{pmatrix}
     2.6 & 2.0 \\
     2.0 & 2.5
  \end{pmatrix}^{-1}
= 
  \frac{1}{2.6 * 2.5 - 2.0 * 2.0}
  \begin{pmatrix}
     2.5 & -2.0 \\
     -2.0 & 2.6
  \end{pmatrix}
 \displaystyle
       = 
  \frac{1}{6.5 - 4.0}
  \begin{pmatrix}
     2.5 & -2.0 \\
     -2.0 & 2.6
  \end{pmatrix}
 \displaystyle
       = 
  \frac{1}{2.5}
  \begin{pmatrix}
     2.5 & -2.0 \\
     -2.0 & 2.6
  \end{pmatrix}
 \displaystyle
       = 
  \begin{pmatrix}
     1.0 & -0.8 \\
     -0.8 & 1.04
  \end{pmatrix}
 \displaystyle
MD = \sqrt{
  (1.9 2.7)
  \begin{pmatrix}
     1.0 & -0.8 \\
     -0.8 & 1.04
  \end{pmatrix}
  \begin{pmatrix}
     1.9 \\
     2.7
  \end{pmatrix}
}
 \displaystyle
  = 
\sqrt{
  (1.9 * 1.0 + 2.7 * 0.8 1.9 * -0.8 + 2.7 * 1.04)
  \begin{pmatrix}
     1.9 \\
     2.7
  \end{pmatrix}
}
 \displaystyle
  = 
\sqrt{
  (-0.26 1.288)
  \begin{pmatrix}
     1.9 \\
     2.7
  \end{pmatrix}
}

 \displaystyle
  =
\sqrt{
  (-0.26 * 1.9 + 1.288 * 2.7)
}

 \displaystyle
  =
\sqrt{
  (2.9836)
} = 1.72731

となる。