首页 > 解决方案 > 基于 2d numpy 数组中的索引列表访问行的更有效方法?

问题描述

所以我有 2d numpay 数组 arr。这是一个比较大的:arr.shape = (2400, 60000)

我目前正在做的事情如下:

它看起来像:

no_rows = arr.shape[0]
indicies = np.array(range(no_rows))
my_vals = []
for k in range(no_samples):
    random_idxs = np.random.choice(indicies, size=no_rows, replace=True)
    my_vals.append(
        arr[random_idxs].mean(axis=0).max()
    )

我的问题是速度很慢。以我的arr尺寸,1 个循环大约需要 3 秒。因为我想要一个大于 1k 的样本 - 我目前的解决方案非常糟糕(1k*~3s -> ~1h)。我已经对其进行了分析,瓶颈是基于索引访问行。"mean"而且"max"工作fast. np.random.choice也还可以。

你觉得有什么需要改进的地方吗?一种更有效的访问索引的方法,或者更好的更快的方法来解决这个问题?

到目前为止我尝试了什么:

某事类似于:

random_idxs = np.random.choice(sample_idxs, size=sample_size, replace=True) 
test = random_idxs.ravel()[arr.ravel()].reshape(arr.shape)

标签: pythonarraysnumpynumpy-indexing

解决方案


由于高级索引会生成一个副本,因此程序会在arr[random_idxs].

因此,提高效率的最简单方法之一就是批量处理。

BATCH = 512
max(arr[random_idxs,i:i+BATCH].mean(axis=0).max() for i in range(0,arr.shape[1],BATCH))

推荐阅读