python求相关系数

记录一下作业

import math

a = [23,23,27,27,39,41,47,49,50,52,54,54,56,57,58,58,60,61]
b =[9.5,26.5,7.8,17.8,31.4,25.9,27.427.2,31.2,34.6,42.5,28.8,33.4,30.2,34.1,32.9,41.2,35.7]
"""a1 = input("请输入年龄:")
a = [int(i) for i in a1.split()]
b1 = input("请输入%fat")
b = [float(j) for j in b1.split()]
"""

计算平均值

def mean(x):
    return sum(x) / len(x)

计算每一项数据与均值的差

def de_mean(x):
    x_bar = mean(x)
    return [x_i - x_bar for x_i in x]

辅助计算函数 dot product 、sum_of_squares

def dot(v, w):
    return sum(v_i * w_i for v_i, w_i in zip(v, w))


def sum_of_squares(v):
    return dot(v, v)

方差

def variance(x):
    n = len(x)
    deviations = de_mean(x)
    return sum_of_squares(deviations) / (n - 1)

标准差

def standard_deviation(x):
    return math.sqrt(variance(x))

协方差

def covariance(x, y):
    n = len(x)
    return dot(de_mean(x), de_mean(y)) / (n-1)

相关系数

def correlation(x, y):
    stdev_x = standard_deviation(x)
    stdev_y = standard_deviation(y)
    if stdev_x > 0 and stdev_y > 0:
        return covariance(x, y) / stdev_x / stdev_y
    else:
        return 0
print(a)
print(b)
print("r=", correlation(a, b))

你可能感兴趣的:(github,python)