python 协方差 轮子
def covariance(x, y):
# Finding the mean of the series x and y
mean_x = sum(x)/float(len(x))
mean_y = sum(y)/float(len(y))
# Subtracting mean from the individual elements
sub_x = [i - mean_x for i in x]
sub_y = [i - mean_y for i in y]
numerator = sum([sub_x[i]*sub_y[i] for i in range(len(sub_x))])
denominator = len(x)-1
cov = numerator/denominator
return cov
当然,有现成的轮子
x = [-2.1, -1, 4.3]
y = [3, 1.1, 0.12]
np.cov(x,y)
output:
array([[11.71 , -4.286 ],
[-4.286 , 2.144133]])
得到的是协方差矩阵
留言
張貼留言