【问题标题】:Calculating correlations between every item in a list计算列表中每个项目之间的相关性
【发布时间】:2012-11-07 03:17:18
【问题描述】:

我正在尝试计算列表中每个项目之间的 Pearson 相关性。我正在尝试获取 data[0] 和 data[1]、data[0] 和 data[2]、data[1] 和 data[2] 之间的相关性。

import scipy
from scipy import stats

data = [[1, 2, 4], [9, 5, 1], [8, 3, 3]]

def pearson(x, y):
    series1 = data[x]
    series2 = data[y]
    if x != y:
        return scipy.stats.pearsonr(series1, series2)

h = [pearson(x,y) for x,y in range(0, len(data))]

这会在h 上返回错误TypeError: 'int' object is not iterable。有人可以在这里解释错误吗?谢谢。

【问题讨论】:

  • 具体错误来自于尝试将x, y分配给range(0, len(data))的一个元素——range的每个元素都只是一个整数,所以不能拆分分配到两个变量。

标签: python correlation


【解决方案1】:

range 将在您尝试使用它时返回一个 int 值列表,就像它返回一个元组一样。改用itertools.combinations

import scipy
from scipy import stats
from itertools import combinations

data = [[1, 2, 4], [9, 5, 1], [8, 3, 3]]

def pearson(x, y):
    series1 = data[x]
    series2 = data[y]
    if x != y:
        return scipy.stats.pearsonr(series1, series2)

h = [pearson(x,y) for x,y in combinations(len(data), 2)]

或者正如@Marius 建议的那样:

h = [stats.pearsonr(data[x], data[y]) for x,y in combinations(len(data), 2)]

【讨论】:

  • 尝试运行 h 给我这个错误:Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in pearson TypeError: list indices must be integers, not list
  • 你应该可以跳过你自定义的pearson函数,直接做h = [scipy.stats.pearsonr(*comb) for comb in combinations(data, 2)]
  • 一个更快速的问题 - 是否有可能找出数据中的哪些项目产生了哪些相关系数?
  • 什么意思?给我一个示例输出
  • 嗯,所以运行 Marius 的代码会得到[(-0.98198050606196574, 0.12103771832367667), (-0.75592894601845462, 0.45437105165701003), (0.86602540378443871, 0.33333333333333331)]。是否有可能找出data 的哪两项产生了给定的结果?
【解决方案2】:

为什么不使用numpy.corrcoef

import numpy as np
data = [[1, 2, 4], [9, 5, 1], [8, 3, 3]]  

结果:

>>> np.corrcoef(data)
array([[ 1.        , -0.98198051, -0.75592895],
       [-0.98198051,  1.        ,  0.8660254 ],
       [-0.75592895,  0.8660254 ,  1.        ]])

【讨论】:

    【解决方案3】:

    range() 函数每次迭代只会给你一个 int,你不能将一个 int 分配给一对值。

    如果您想了解该范围内所有可能的整数对,您可以尝试

    import itertools
    
    h = [pearson(x,y) for x,y in itertools.product(range(len(data)), repeat=2)]
    

    这会将给定范围内的所有可能性组合在一个 2 个元素的元组中

    请记住,使用您定义的函数,当 x==y 时,您将拥有 None 值。要解决这个问题,您可以使用:

    import itertools
    
    h = [pearson(x,y) for x,y in itertools.permutations(range(len(data)), 2)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 2018-12-16
      • 1970-01-01
      相关资源
      最近更新 更多