有没有比这更好的方法来计算两个列表的协方差?

may*_*ull 0 python math covariance

我有两个列表,其中一个由 x 坐标组成,另一个由 y 坐标组成。

x_coordinates = [1, 2, 3, 4, 5]
y_coordinates = [1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)

例如,point 1(1,1)

我想计算两个列表的协方差,我编写了一个代码,但我认为它有些不必要的冗长和混乱。我知道我可以只使用 math.cov 来计算这个,但我想知道是否可以巧妙地编程,也许使用 map 和 lambda 函数。

公式是这样的:

(x1 - average_x)*(y1 - average_y) + ... + (xn - average_x)*(yn - average_y) / (the number of the items in one of the lists)
Run Code Online (Sandbox Code Playgroud)

编码:

import math

x_coordinates = [1, 2, 3, 4, 5]
y_coordinates = [1, 2, 3, 4, 5]
covariance_temp_sum = 0

x_mean = math.fsum(x_coordinates) / len(x_coordinates)
y_mean = math.fsum(y_coordinates) / len(y_coordinates)

for n in range(len(x_coordinates)):
    covariance_temp_sum += (x_coordinates[n] - x_mean) * (y_coordinates[n] - y_mean)

covariance = covariance_temp_sum / len(x_coordinates)
Run Code Online (Sandbox Code Playgroud)

Car*_*ans 5

如果不想使用外部模块,可以这样处理:

x = [1, 2, 3, 4, 5]
y = [1, 2, 3, 4, 5]
mean_x = sum(x) / len(x)
mean_y = sum(y) / len(y)

sum((a - mean_x) * (b - mean_y) for (a,b) in zip(x,y)) / len(x)
Run Code Online (Sandbox Code Playgroud)

输出: 2