【統計学】相関係数(Python)
前回解説いたしました相関係数を今度はPythonで実装してみたいと思います。
共分散
データ
散布図でも使用しました上記書籍のP60にあるJリーグの試合結果のデータを使用します。
#勝数 wins = [22, 20, 20, 18, 17, 18, 13, 13, 13, 13, 13, 13, 13, 12, 12, 5, 6, 4] #得点 score = [67, 84, 80, 60, 68, 62, 51, 47, 49, 50, 57, 43, 56, 46, 42, 32, 44, 38] #失点 lost = [28, 55, 48, 41, 51, 53, 49, 45, 43, 56, 58, 55, 65, 65, 64, 56, 70, 74]
計算
numpy.cov関数を使用します。
import numpy as np np.cov(wins, score) #[array([[ 25.54575163, 61.32679739], # [ 61.32679739, 195.35947712]])
右上と左下の61.32679739が共分散です。 左上と右下はそれぞれの分散です。
標本相関係数
データ
上記のデータです。
計算
次に同じ勝数と得点で相関係数をとります。相関係数は様々な方法で算出できます。
pandasを使う
df=pd.DataFrame(a)# ただし、転置をしております。 df_cor = df.corr() print(df_cor) # 0 1 #0 1.000000 0.868108 #1 0.868108 1.000000
相関行列
df2 = pd.DataFrame({ "wins": wins, "score":score, "lost":lost }) df2_cor = df2.corr() print(df2_cor) # wins score lost #wins 1.000000 0.868108 -0.707724 #score 0.868108 1.000000 -0.441341 #lost -0.707724 -0.441341 1.000000
scipy.stats
import scipy.stats scipy.stats.pearsonr(wins, score) #(0.8681078844717941, 3.0192387576016544e-06)
左側が相関係数です。
ほかにも方法がありそうです。ご存知の方はぜひお教えください。
標本自己相関分析
データ
ここからは新しいデータを使います。教科書のP65例題2.3を使います。
rate = [103,105,105,107,107,109,112,111,111,115,118,119]
計算
準備中(ごおめんなさい)
順位相関
データ
教科書P66表2-5のデータを使用します。10人の統計学と数学の得点順位です。
statistics = [1,2,3,4,5,6,7,8,9,10] math = [1,4,2,3,7,5,6,10,8,9]
計算
corr()t関数のメソッドを"spearman"に設定することで計算できます。
statistics = [1,2,3,4,5,6,7,8,9,10] math = [1,4,2,3,7,5,6,10,8,9] df3 = pd.DataFrame({ "statistics": statistics, "math":math }) cor.test ( statistics , math, method="spearman") #Out[47]: # statistics math #statistics 1.000000 0.890909 #math 0.890909 1.000000