繁体   English   中英

使用random.sample()时发生Python内存错误

[英]Python Memory Error when using random.sample()

好的,所以我有一个确实需要帮助的问题。

我的程序从pdb文件中读取值,并将这些值存储在(array = [])中,然后从存储值的这种排列中获取4的每种组合,并将其存储在名为maxcoorlist的列表中。 因为组合列表的数量如此之多,为了加快处理速度,我只想从该组合列表中抽取1000-10000个样本。 但是,这样做的话,我在随机采样的那一行上遇到了一个内存错误。

MemoryError                               Traceback (most recent call last)
<ipython-input-14-18438997b8c9> in <module>()
     77     maxcoorlist= itertools.combinations(array,4)
     78     random.seed(10)
---> 79     volumesample= random_sample(list(maxcoorlist), 1000)
     80     vol_list= [side(i) for i in volumesample]
     81     maxcoor=max(vol_list)

MemoryError: 

在此代码中也要使用random.seed(),这一点很重要,因为我将使用种子获取其他样本。

如其他答案所述,list()调用使您内存不足。

取而代之的是,首先遍历maxcoorlist以确定其长度。 然后在[0,长度)范围内创建随机数,并将其添加到索引集中,直到索引集的长度为1000。

然后,如果当前索引在您的索引集中,则再次遍历maxcoorlist并将当前值添加到样本集中。

编辑

一种优化是直接计算maxcoorlist的长度,而不是对其进行迭代:

import math
n = len(array)
r = 4
length = math.factorial(n) / math.factorial(r) / math.factorial(n-r)
maxcoorlist= itertools.combinations(array,4)
...
volumesample= random_sample(list(maxcoorlist), 1000)

当执行volumesample时,您volumesample中构建所有组合的列表...然后采样到1000 ...

代替需要构建整个列表的示例,可以对它应用islice,例如:

from itertools import islice
volumesample = list(islice(maxcoorlist, 1000))

取前1000个; 您可以将其调整为每n分之一或类似的值,以获得更像样本的效果...

使用maxcoorlist可能会占用大量内存(和时间),并且将其maxcoorlist转换为列表会使占用的内存空间增加一倍。 您可能应该自己生成1000个随机组合:随机抽取4个元素,然后检查该组合是否在列表中(对它们进行排序,然后this_combination in combination_list使用this_combination in combination_list 。如果combination_listset ,则此检查将为O(1) )

这样,您仅占用所需的内存。

如何将代码重构为使用元组而不是像这样的列表:

maxcoorlist= itertools.combinations(array,4)
random.seed(10)
volumesample= random.sample(tuple(maxcoorlist), 1000)
vol_list= [side(i) for i in volumesample]
maxcoor=max(vol_list)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM