我想在Python中使用多处理来加速while循环。循环条件并行化/多处理
更具体地说:
我有一个矩阵(样本*功能)。我想选择x样本的子集,其特征的随机子集的值不等于某个值(本例中为-1)。
我的串行代码:
np.random.seed(43)
datafile = '...'
df = pd.read_csv(datafile, sep=" ", nrows = 89)
no_feat = 500
no_samp = 5
no_trees = 5
i=0
iter=0
samples = np.zeros((no_trees, no_samp))
features = np.zeros((no_trees, no_feat))
while i < no_trees:
rand_feat = np.random.choice(df.shape[1], no_feat, replace=False)
iter_order = np.random.choice(df.shape[0], df.shape[0], replace=False)
samp_idx = []
a=0
#--------------
#how to run in parallel?
for j in iter_order:
pot_samp = df.iloc[j, rand_feat]
if len(np.where(pot_samp==-1)[0]) == 0:
samp_idx.append(j)
if len(samp_idx) == no_samp:
print a
break
a+=1
#--------------
if len(samp_idx) == no_samp:
samples[i,:] = samp_idx
features[i, :] = rand_feat
i+=1
iter+=1
if iter>1000: #break if subsets cannot be found
break
搜索拟合样品是潜在地昂贵的部分(第j for循环),这在理论上可以并行运行。在某些情况下,不需要遍历所有样本以找到足够大的子集,这就是为什么一旦子集足够大,我就会跳出循环。
我很努力地找到一个实现,可以检查已经生成了多少有效结果。它甚至有可能吗?
我以前用过joblib
。如果我理解正确,这会使用多处理方法作为仅适用于单独任务的后端?我在想,queues
可能会有所帮助,但迄今为止我未能实施它们。
使用'joblib'或'multiprocessing.pool'是有道理的。我会为每个核心运行一个进程,并创建一个共享计数器,由'Lock'保护或者实现为一个原子整数,将其递增直至达到特定计数(考虑到重复),然后所有进程都将完成,返回他们的结果。 (你可以使用'apply_async()')。 – advance512
@ advance512谢谢你给我这些方法来看看。 – Dahlai