11

我正在尝试使用和加速花式索引来“加入”两个数组并在结果轴之一上求和。

像这样的东西:

$ ipython
In [1]: import numpy as np
In [2]: ne, ds = 12, 6
In [3]: i = np.random.randn(ne, ds).astype('float32')
In [4]: t = np.random.randint(0, ds, size=(1e5, ne)).astype('uint8')

In [5]: %timeit i[np.arange(ne), t].sum(-1)
10 loops, best of 3: 44 ms per loop

有没有一种简单的方法来加速语句In [5]?我应该使用 OpenMP 和类似scipy.weaveorCython的东西prange吗?

4

1 回答 1

8

numpy.take由于某种原因,它比花式索引要快得多。唯一的技巧是它将数组视为平面。

In [1]: a = np.random.randn(12,6).astype(np.float32)

In [2]: c = np.random.randint(0,6,size=(1e5,12)).astype(np.uint8)

In [3]: r = np.arange(12)

In [4]: %timeit a[r,c].sum(-1)
10 loops, best of 3: 46.7 ms per loop

In [5]: rr, cc = np.broadcast_arrays(r,c)

In [6]: flat_index = rr*a.shape[1] + cc

In [7]: %timeit a.take(flat_index).sum(-1)
100 loops, best of 3: 5.5 ms per loop

In [8]: (a.take(flat_index).sum(-1) == a[r,c].sum(-1)).all()
Out[8]: True

我认为,除此之外,您将看到速度大幅提升的唯一另一种方法是使用PyCUDA 之类的东西为 GPU 编写自定义内核。

于 2012-08-05T00:27:59.793 回答