gpt4 book ai didi

python - 查找列表内列表之间的相关性的效率问题

转载 作者:行者123 更新时间:2023-11-30 22:51:39 25 4
gpt4 key购买 nike

如果我有两个小列表,并且我想找到 list1 中的每个列表与 list2 中的每个列表之间的相关性,我可以这样做

from scipy.stats import pearsonr

list1 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
list2 = [[10,20,30],[40,50,60],[77,78,79],[80,78,56]]

corrVal = []
for i in list1:
for j in list2:
corrVal.append(pearsonr(i,j)[0])

print(corrVal)

OUTPUT: [1.0, 1.0, 1.0, -0.90112711377916588, 1.0, 1.0, 1.0, -0.90112711377916588, 1.0, 1.0, 1.0, -0.90112711377916588, 1.0, 1.0, 1.0, -0.90112711377916588]

效果很好......差不多了。 (编辑:刚刚注意到我上面的相关输出似乎给出了正确的答案,但它们重复了 4 次。不太确定为什么这样做)

但是,对于列表中包含 1000 个值的较大数据集,我的代码会无限期卡住,不会输出任何错误,因此每次都会强制退出 IDE。有什么想法我在这里滑倒了吗?不确定 pearsonr 函数可以处理的数量是否存在固有限制,或者我的编码是否导致了问题。

最佳答案

scipy 模块 scipy.spatial.distance 包含一个称为 Pearson's distance 的距离函数,它只是 1 减去相关系数。通过在 scipy.spatial.distance.cdist 中使用参数 metric='correlation',您可以有效计算两个输入中每对向量的 Pearson 相关系数。

这是一个例子。我将修改您的数据,使系数更加多样化:

In [96]: list1 = [[1, 2, 3.5], [4, 5, 6], [7, 8, 12], [10, 7, 10]]

In [97]: list2 = [[10, 20, 30], [41, 51, 60], [77, 80, 79], [80, 78, 56]]

所以我们知道会发生什么,这是使用 scipy.stats.pearsonr 计算的相关系数:

In [98]: [pearsonr(x, y)[0] for x in list1 for y in list2]
Out[98]:
[0.99339926779878296,
0.98945694873927104,
0.56362148019067804,
-0.94491118252306794,
1.0,
0.99953863896044937,
0.65465367070797709,
-0.90112711377916588,
0.94491118252306805,
0.93453339271427294,
0.37115374447904509,
-0.99339926779878274,
0.0,
-0.030372836961539348,
-0.7559289460184544,
-0.43355498476205995]

查看数组中的内容更方便:

In [99]: np.array([pearsonr(x, y)[0] for x in list1 for y in list2]).reshape(len(list1), len(list2))
Out[99]:
array([[ 0.99339927, 0.98945695, 0.56362148, -0.94491118],
[ 1. , 0.99953864, 0.65465367, -0.90112711],
[ 0.94491118, 0.93453339, 0.37115374, -0.99339927],
[ 0. , -0.03037284, -0.75592895, -0.43355498]])

这是使用 cdist 计算出的相同结果:

In [100]: from scipy.spatial.distance import cdist

In [101]: 1 - cdist(list1, list2, metric='correlation')
Out[101]:
array([[ 0.99339927, 0.98945695, 0.56362148, -0.94491118],
[ 1. , 0.99953864, 0.65465367, -0.90112711],
[ 0.94491118, 0.93453339, 0.37115374, -0.99339927],
[ 0. , -0.03037284, -0.75592895, -0.43355498]])

使用cdist比在嵌套循环中调用pearsonr快得多。在这里,我将使用两个数组,data1data2,每个数组的大小为 (100, 10000):

In [102]: data1 = np.random.randn(100, 10000)

In [103]: data2 = np.random.randn(100, 10000)

我将使用 ipython 中方便的 %timeit 命令来测量执行时间:

In [104]: %timeit c1 = [pearsonr(x, y)[0] for x in data1 for y in data2]
1 loop, best of 3: 836 ms per loop

In [105]: %timeit c2 = 1 - cdist(data1, data2, metric='correlation')
100 loops, best of 3: 4.35 ms per loop

嵌套循环需要 836 毫秒,cdist 需要 4.35 毫秒。

关于python - 查找列表内列表之间的相关性的效率问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38943055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com