共分散(covariance)
・2つの変数間の相関関係を表す指標
・次回紹介する相関係数を求めるのに重要な指標
まずは1変数の分散がどのようになるか考えてみましょう。
1変数の分散
s^2_x = \frac{1}{n}\sum^n_{i=1}(x_i-\bar{x})^2 = \frac{1}{n}\sum^n_{i=1}(x_i-\bar{x})(x_i-\bar{x})
s^2_y = \frac{1}{n}\sum^n_{i=1}(y_i-\bar{y})^2 = \frac{1}{n}\sum^n_{i=1}(y_i-\bar{y})(y_i-\bar{y})
上記から、2変数間のグラフがどのようになるか考えます。
すると、グラフは下記のようになり、xが大きくなるとyも大きくなるxとyの相関関係があることがわかります。
xとyの相関係数$s_{xy}$
s_{xy} = \frac{1}{n}\sum^n_{i=1}(x_i-\bar{x})(y_i-\bar{y})
なぜ、共分散が上記のような式になるかというと、下記の図のように、全てのデータにおいて、$(x_1$-$\bar{x})$ * $(y_1$-$\bar{y})$ + $(x_2$-$\bar{x})$ * $(y_2$-$\bar{y})$ + $(x_3$-$\bar{x})$ * $(y_3$-$\bar{y})$ ....
を計算し、平均をとるためである。
共分散行列(covariance matrix)
・複数の変数間の分散と共分散を行列にしたもの
・分散共分散行列ともいう
変数$x, y$の場合
S =
\begin{bmatrix}
s^2_x & s_{xy} \\
s_{yx} & s^2_y
\end{bmatrix}
変数$X_1,X_2,...,X_n$の場合
S=
\begin{pmatrix}
s_{11} & s_{12} & \dots & s_{1n} \\
s_{21} & s_{22} & \dots & s_{2n} \\
\vdots & \vdots & \ddots & \vdots \\
s_{n1} & s_{n2} & \dots & s_{nn}
\end{pmatrix}
Pythonで実践
共分散行列を求める
・np.cov(xarray, yarray, bias=True)
・np.cov(array, bias=True)
import numpy as np
import seaborn as sns
# データ準備
df = sns.load_dataset('tips')
df['tip_rate'] = df['tip'] / df['total_bill']
np.cov(df['total_bill'], df['tip'], bias=True)
結果
array([[78.92813149, 8.28938892],
[ 8.28938892, 1.90660851]])
複数の変数間の場合
'total_bill', 'tip', 'size'についてnp.stackで連結する
array = np.stack([df['total_bill'], df['tip'], df['size']], axis=0)
np.cov(array, bias=True)
結果
array([[78.92813149, 8.28938892, 5.04522121],
[ 8.28938892, 1.90660851, 0.64126747],
[ 5.04522121, 0.64126747, 0.9008835 ]])