据我了解,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/