Python中Pearson积矩相关系数权重

0 投票
2 回答
1930 浏览
提问于 2025-04-17 21:26

我现在在用一个函数来计算皮尔逊积矩相关系数,这个是在python里做的。

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

2 个回答

-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)
0

你需要的东西在 statsmodels 这个包里:

pip install statsmodels

然后在 Python 里:

from statsmodels.stats.weightstats import DescrStatsW
...

这里有一个关于如何使用它的例子 在这里(注意:那个回答中提到的 statsmodels 的bug已经修复了)。

撰写回答