我试图计算列表中每个项目之间的Pearson相关性相关性。我试图获得数据[0]和数据[1],数据[0]和数据[2],数据[1]和数据[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))]
这会在TypeError: 'int' object is not iterable
上返回错误h
。有人可以在这里解释错误吗?感谢。
答案 0 :(得分:3)
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)]
答案 1 :(得分:0)
为什么不使用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. ]])
答案 2 :(得分:0)
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)]