![](/img/trans.png)
[英]How to get the remaining sample after using random.sample() in 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_list
是set
,則此檢查將為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.