我目前正在使用以下函数来计算python中的Pearson Product-Moment相关系数。
def PearsonCoefficient(x, y):
assert len(x) == len(y)
n = len(x)
assert n > 0
avg_x = float(sum(x)) / n
avg_y = float(sum(y)) / n
diffprod = 0
xdiff2 = 0
ydiff2 = 0
for idx in range(n):
xdiff = x[idx] - avg_x
ydiff = y[idx] - avg_y
diffprod += xdiff * ydiff
xdiff2 += xdiff * xdiff
ydiff2 += ydiff * ydiff
p = math.sqrt(xdiff2 * ydiff2)
if p == 0:
return None
return diffprod / p我的数据是基于时间序列的(基于x),y值表示用户得分。我将按周对时间序列数据进行分组,并取该时间段的平均分数。然而,我想要将过去三个月的数据权重高于之前的数据。我不确定如何根据这个假设生成我的权重向量。
我的数据看起来像
jan 1st - 0.4
jan 8th - 0.7
jan 15th - 0.55
jan 22nd - 0.75
jan 29th - 0.88
feb 5th - 0.91
feb 12th - 0.87
feb 19th - 0.89
feb 26th - 0.93
feb 5th - 0.56
...发布于 2016-09-02 21:53:29
您需要的是statsmodels包中的内容:
pip install statsmodels然后在python中:
from statsmodels.stats.weightstats import DescrStatsW
...有一个关于如何使用它的示例here (注意:答案中提到的statsmodels错误已经修复)。
发布于 2014-03-09 02:12:41
如果你能使用numpy,你可以做类似这样的事情
import numpy as np
def PearsonCoefficient(x, y):
assert len(x) == len(y)
assert len(x) > 0
x = np.array(x)
y = np.array(y)
# Generate uniform weights
w = np.ones(52)
# Increase the weight of the last three months
w[-12:] = 1.5
w /= np.sum(w)
# Actual weighting
x *= w
y *= w
# Calculate pearson correlation and return the result
return np.corrcoef(x, y)https://stackoverflow.com/questions/22272419
复制相似问题