pythonで定義通りに相関係数を求める
解決したいこと
pythonを使用して定義通りに相関係数を求めようとしています。それっぽいコードは書いてみたのですが、相関係数が1を超えてしまいました。エラー等は出ていません。どこを治せば良いのか教えてください。
該当するソースコード
import math
import pandas
data = pandas.read_csv("TravelReview2019.csv").values.tolist()
N = len(data)
print("Size of Data =", N)
def cor(i, j):
df = pandas.DataFrame(data)
X_list = df.iloc[i].to_list()
Y_list = df.iloc[j].to_list()
X_ave = sum(X_list) / N
Y_ave = sum(Y_list) / N
X_var = (sum((x - X_ave) ** 2 for x in X_list)) / N
Y_var = (sum((y - Y_ave) ** 2 for y in Y_list)) / N
cov = (sum((x - X_ave) * (y - Y_ave) for x in X_list for y in Y_list )) / N
return cov / ((X_var * 0.5) * (Y_var * 0.5))
for m in range(1,8):
for n in range(m+1, 8):
print("Correlation", m, "-", n, "= ", cor(m, n))
結果
Size of Data = 23
Correlation 1 - 2 = 13.93735362997658
Correlation 1 - 3 = 12.93047256925584
Correlation 1 - 4 = 11.04209494291407
Correlation 1 - 5 = 13.712045654550785
Correlation 1 - 6 = 11.247751104003488
Correlation 1 - 7 = 9.059847131333846
Correlation 2 - 3 = 10.664990182634169
Correlation 2 - 4 = 9.10746560353056
Correlation 2 - 5 = 11.309627819583383
Correlation 2 - 6 = 9.277089793773367
Correlation 2 - 7 = 7.472517357298921
Correlation 3 - 4 = 8.449511814682346
Correlation 3 - 5 = 10.492582463795992
Correlation 3 - 6 = 8.606881785858183
Correlation 3 - 7 = 6.932677700307746
Correlation 4 - 5 = 8.960236460117128
Correlation 4 - 6 = 7.3499251734891065
Correlation 4 - 7 = 5.920223330231069
Correlation 5 - 6 = 9.127118545660474
Correlation 5 - 7 = 7.351718402073592
Correlation 6 - 7 = 6.030485957855788
0