Created
September 8, 2019 05:23
-
-
Save beru/3b66691d8903cb082d5d0d850a8aed11 to your computer and use it in GitHub Desktop.
分散共分散行列と相関係数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import numpy.linalg as LA | |
import matplotlib.pyplot as plt | |
from pprint import pprint | |
# original : https://qiita.com/Seiji_Tanaka/items/5c8041dbd7da1510fbe9 | |
# https://mathtrain.jp/covariance | |
# https://examist.jp/mathematics/data/kyoubunsan-soukankeisuu/ | |
#データ数 上げると精度が上がる | |
N = 40 | |
#乱数の生成 | |
width = 0.5 | |
length = 10 | |
x = np.random.uniform(-width/2, +width/2, N) | |
y = np.random.uniform(-length/2, +length/2, N) | |
#二つの乱数列の結合 それぞれ異なるパラメータを設定したいため後から結合する | |
pts = np.vstack([x, y]) | |
#回転前の分布の表示 この時点ではx軸方向かy軸方向へ平べったい楕円形 | |
#plt.scatter(pts[0][:], pts[1][:]) | |
#xの分布の回転 これによって一般系の2次元正規分布に変形 | |
theta = -0.49 * np.pi | |
rot = np.array([[np.cos(theta), np.sin(theta)], [-np.sin(theta), np.cos(theta)]], np.float32) | |
pts = np.dot(rot, pts) | |
x = pts[0] | |
y = pts[1] | |
plt.scatter(x, y, s=4) | |
plt.grid() | |
plt.xlabel('X') | |
plt.ylabel('Y') | |
plt.xlim(-10, 10) | |
plt.ylim(-10, 10) | |
plt.show() | |
#共分散行列の計算 | |
x_ave = np.sum(x) / N | |
#x_diff = x - x_ave | |
#x_variance = np.sum(x_diff ** 2) / N | |
x_variance = np.sum(x ** 2) / N - (x_ave ** 2) | |
y_ave = np.sum(y) / N | |
#y_diff = y - y_ave | |
#y_variance = np.sum(y_diff ** 2) / N | |
y_variance = np.sum(y ** 2) / N - (y_ave ** 2) | |
xy_covariance = np.sum(x * y) / N - x_ave * y_ave | |
corr_coeff = xy_covariance / np.sqrt(x_variance * y_variance) | |
print(corr_coeff) | |
#共分散行列の固有値と固有ベクトルの表示 | |
print('{0:.2f}, {1:.2f}'.format(x_variance, xy_covariance)) | |
print('{0:.2f}, {1:.2f}'.format(xy_covariance, y_variance)) | |
#eigenvector = LA.eig(V_X) | |
#pprint(eigenvector) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
斜め45度に近づくとXの分散とYの分散の比は小さくなるので判定に使えなくなる。ある程度傾きがあれば相関係数の値は大きくなるので、その値で判定可能。
傾きが完全に水平や垂直に近づくと相関係数の値が下がってしまうが、その時はXの分散とYの分散の比がとても大きくなっている。