【问题标题】:Pearson Product-Moment Correlation Coefficient Weighting in PythonPython中的皮尔逊积矩相关系数加权
【发布时间】:2014-04-11 22:02:25
【问题描述】:

我目前正在使用以下函数来计算 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
...

【问题讨论】:

    标签: python pearson


    【解决方案1】:

    您需要的是statsmodels 包:

    pip install statsmodels
    

    然后在python中:

    from statsmodels.stats.weightstats import DescrStatsW
    ...
    

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

    【讨论】:

      【解决方案2】:

      如果你可以使用 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)
      

      【讨论】:

      • 我在 python 的列表中找不到任何关于除法分配的文档。 “/=”到底在做什么?我的猜测是列表中每个元素的除以权重之和?
      • w 是一个 numpy 数组而不是 python 列表。您的猜测是正确的 /= 是列表中每个元素的除法。
      • 您将分数乘以权重 - 这会改变实际测量值,而不是它对相关性的影响强度。
      • 不要使用那个解决方案!这是完全错误的......它使值相乘而不是改变多重性!
      猜你喜欢
      • 2021-08-29
      • 2019-08-31
      • 1970-01-01
      • 2011-09-10
      • 2014-11-13
      • 1970-01-01
      • 2011-09-13
      • 2012-11-19
      • 2013-10-12
      相关资源
      最近更新 更多