python - 基于 2d numpy 数组中的索引列表访问行的更有效方法?
问题描述
所以我有 2d numpay 数组 arr。这是一个比较大的:arr.shape = (2400, 60000)
我目前正在做的事情如下:
- 随机(带替换)选择
arr.shape[0]
索引 - 访问(按行)选择的索引
arr
- 计算列平均值并选择最大值
- 我重复了k次
它看起来像:
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
也还可以。
你觉得有什么需要改进的地方吗?一种更有效的访问索引的方法,或者更好的更快的方法来解决这个问题?
到目前为止我尝试了什么:
- numpy.take(较慢)
- numpy.ravel:
某事类似于:
random_idxs = np.random.choice(sample_idxs, size=sample_size, replace=True)
test = random_idxs.ravel()[arr.ravel()].reshape(arr.shape)
- 与当前方法类似,但没有循环。我一次性创建了 3d arr 并访问了其他维度的行
解决方案
由于高级索引会生成一个副本,因此程序会在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))
推荐阅读
- javascript - 在 ionic 中与 sourcemap 链接
- sonarqube - Sonarqube v.4.3.0 VSTS 任务“发布分析结果”抛出错误“无法获取指标”(404)
- antlr - 想从 SQL 语句中提取表名和列名
- python - chaquopy代码在什么目录下搜索Android app代码的Python代码中导入的Python包
- laravel - Laravel 5.6 调度队列模型
- c# - CheckBoxFor 选中时未正确注册
- python-2.7 - 如何在 Python 中构建主谓宾提取模型?
- c# - XML 签名:验证所有必需的元素都已签名
- amazon-web-services - 来自部署在亚马逊 S3 上的 Vue 应用程序的 Axios 请求返回站点的索引
- wso2 - WSO2 APIM:登录时管理应用程序在 BPS 的序言中生成意外的 EOF