【发布时间】:2022-01-23 04:45:51
【问题描述】:
假设我想根据条件并行采样。
例如,给出矩阵A。我想对p 对索引(i,j) 进行采样,这样A[i][j] != 5
import numpy as np
import random
A = np.random.randint(10, size=(5000, 5000)) # assume this is fixed
p = 400 # sample 400 index
res = set()
cnt = 0
while cnt < p:
r, c = random.randint(0, A.shape[0]-1), random.randint(0, A.shape[0]-1)
if A[r, c] != 5 and (r,c) not in res:
res.add((r,c))
cnt += 1
以上是我的尝试。但是,矩阵A 和样本数量p 可能非常大。我们可以并行吗?喜欢使用joblib、multiprocessing?或者有什么快速获取row和col的方法?
【问题讨论】:
-
谢谢,由于我的采样有一些条件,我不怎么修改上面的示例代码。
-
如果您需要速度,矢量化和缓存效率也很重要。您是否需要在两个指数中都进行抽样?你能系统地浏览一下这些指数吗?在随机点中对矩阵进行采样非常耗时。通过增加
i在循环中执行np.argwhere(A[i] != 5)可能是最快的解决方案之一。这样就可以得到第一个p非5值。 -
比较整数比从内存中加载值要快,后者可能要慢数百或数千倍。
标签: python random parallel-processing multiprocessing joblib