python - 带有组合生成器的 Numpy : How does one speed up Combinations?

标签 python performance numpy python-itertools

据我了解,itertools functions are written in C 。如果我想加快这个示例代码的速度:

import numpy as np
from itertools import combinations_with_replacement

def combinatorics(LargeArray):
     newArray = np.empty((LargeArray.shape[0],LargeArray.shape[0]))
     for x, y in combinations_with_replacement(xrange(LargeArray.shape[0]), r=2):
         z = LargeArray[x] + LargeArray[y]
         newArray[x, y] = z
     return newArray

由于combinations_with_replacement是用C编写的,这是否意味着它无法加速?请指教。

提前致谢。

最佳答案

确实,combinations_with_replacement 是用 C 编写的,这意味着您不太可能加快该部分代码的实现速度。但您的大部分代码并没有花在查找组合上:而是在 for 循环上进行添加。当你使用 numpy 时,如果可能的话,你真的、真的、真的想避免这种循环。这个版本将做几乎相同的事情,通过 the magic of broadcasting :

def sums(large_array):
    return large_array.reshape((-1, 1)) + large_array.reshape((1, -1))

例如:

>>> ary = np.arange(5).astype(float)
>>> np.triu(combinatorics(ary))
array([[ 0.,  1.,  2.,  3.,  4.],
       [ 0.,  2.,  3.,  4.,  5.],
       [ 0.,  0.,  4.,  5.,  6.],
       [ 0.,  0.,  0.,  6.,  7.],
       [ 0.,  0.,  0.,  0.,  8.]])
>>> np.triu(sums(ary))
array([[ 0.,  1.,  2.,  3.,  4.],
       [ 0.,  2.,  3.,  4.,  5.],
       [ 0.,  0.,  4.,  5.,  6.],
       [ 0.,  0.,  0.,  6.,  7.],
       [ 0.,  0.,  0.,  0.,  8.]])

不同之处在于,组合数学将下三角保留为随机乱码,其中求和使矩阵对称。如果您真的想避免将所有内容添加两次,您可能可以,但我无法立即想到如何做到这一点。

哦,还有另一个区别:

>>> big_ary = np.random.random(1000)
>>> %timeit combinatorics(big_ary)
1 loops, best of 3: 482 ms per loop
>>> %timeit sums(big_ary)
1000 loops, best of 3: 1.7 ms per loop

关于python - 带有组合生成器的 Numpy : How does one speed up Combinations?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14472362/

相关文章:

python - 深度排序使用大量 CPU

python - 使用类作为特殊值?

Android studio 在布局设计过程中卡住

sql - 为什么这个 Oracle 查询这么慢?

python - 取最近N天的平均值

python - numpy 数组,类型错误 : cannot unpack non-iterable numpy. int64 对象

python - 从嵌套列表 Python 中删除项目

java - jar 文件的大小会影响 JVM 的性能吗?

python - 将 lambda 放入 NumPy `np.fromfunction()` 会导致 TypeError

python - 使用 PyQt 资源系统的问题