聚合numpy的功能 [英] Aggregate numpy functions
问题描述
我有一个numpy的操作,我称之为集中,我需要优化:
I have a numpy operation that I call intensively and I need to optimise:
np.sum(a**2, axis=1)**.5 # where a is a 2 dimensional ndarray
此操作是由三个功能,并且需要通过'一'三次迭代。这将是更有效地聚集在一个函数的所有操作,并沿轴线1.不幸的是,numpy的的的 apply_along_axis 功能不是一种选择,因为性能大约是X1000差。
This operation is composed of three functions and requires iterating through 'a' three times. It would be more efficient to aggregate all operations under one function and apply that function just once along axis 1. Unfortunately, numpy's apply_along_axis function is not an option as performance is around x1000 worse.
有聚集几个numpy的操作的方式,因此只需要一次循环阵列上
Is there a way of aggregating several numpy operations so it only has to loop once over the array?
推荐答案
在浮点阵列时,您可以使用的 np.einsum
-
When working with floating-point array, you can use np.einsum
-
np.sqrt(np.einsum('ij,ij->i',a,a))
运行测试 -
Runtime test -
In [34]: a = np.random.rand(1000,1000)
In [35]: np.allclose(np.sum(a**2, axis=1)**.5,np.sqrt(np.einsum('ij,ij->i',a,a)))
Out[35]: True
In [36]: %timeit np.sum(a**2, axis=1)**.5
100 loops, best of 3: 7.57 ms per loop
In [37]: %timeit np.sqrt(np.einsum('ij,ij->i',a,a))
1000 loops, best of 3: 1.52 ms per loop
这篇关于聚合numpy的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!