带组合生成器的Numpy:如何加速组合?

2024-05-14 03:54:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我的理解是itertools functionsare 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编写的,这是否意味着它不能被加速?请告知。在

提前谢谢。在


Tags: 代码inimportnumpy示例withnpitertools
1条回答
网友
1楼 · 发布于 2024-05-14 03:54:02

确实,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))

例如:

^{pr2}$

区别在于combinatorics使下三角成为随机胡言乱语,其中{}使矩阵对称。如果你真的想避免把每样东西都加两次,你也许可以,但我一时想不出该怎么做。在

哦,还有另一个区别:

>>> 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

相关问题 更多 >