1 def mean(x): 2 return sum(x) / len(x) 3 # 计算每一项数据与均值的差 4 def de_mean(x): 5 x_bar = mean(x) 6 return [x_i - x_bar for x_i in x] 7 # 辅助计算函数 dot product 、sum_of_squares 8 def dot(v, w): 9 return sum(v_i * w_i for v_i, w_i in zip(v, w)) 10 def sum_of_squares(v): 11 return dot(v, v) 12 # 方差 13 def variance(x): 14 n = len(x) 15 deviations = de_mean(x) 16 return sum_of_squares(deviations) / (n - 1) 17 # 标准差 18 import math 19 def standard_deviation(x): 20 return math.sqrt(variance(x)) 21 # 协方差 22 def covariance(x, y): 23 n = len(x) 24 return dot(de_mean(x), de_mean(y)) / (n -1) 25 # 相关系数 26 def correlation(x, y): 27 stdev_x = standard_deviation(x) 28 stdev_y = standard_deviation(y) 29 if stdev_x > 0 and stdev_y > 0: 30 return covariance(x, y) / stdev_x / stdev_y 31 else: 32 return 0 33 correlation(acc_list, pvalue_list)
参考:
https://www.jianshu.com/p/c83dd487df09