0

我目前正在使用以下函数来计算 python 中的 Pearson Product-Moment Correlation Coefficient。

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
...
4

2 回答 2

0

您需要的是在statsmodels包装中:

pip install statsmodels

然后在python中:

from statsmodels.stats.weightstats import DescrStatsW
...

这里有一个关于如何使用它的示例(注意:该答案中提到的 statsmodels 错误已修复)。

于 2016-09-02T13:53:29.093 回答
-1

如果你可以使用 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)
于 2014-03-08T18:12:41.117 回答