【发布时间】:2015-11-18 07:19:49
【问题描述】:
我的代码包含这个while 循环:
while A.shape[0] > 0:
idx = A.score.values.argmax()
one_center = A.coordinate.iloc[idx]
# peak_centers and peak_scores are python lists
peak_centers.append(one_center)
peak_scores.append(A.score.iloc[idx])
# exclude the coordinates around the selected peak
A = A.loc[(A.coordinate <= one_center - exclusion) | (A.coordinate >= one_center + exclusion)]
A 是一个熊猫DataFrame,看起来像这样:
score coordinate
0 0.158 1
1 0.167 2
2 0.175 3
3 0.183 4
4 0.190 5
我试图在A 中找到最高分(一个峰值),然后排除先前找到的峰值周围的一些坐标(在这种情况下为几百个),然后找到下一个峰值,依此类推。
A 这是一个非常大的熊猫DataFrame。在运行这个while 循环之前,ipython 会话使用了 20% 的机器内存。我认为运行这个while 循环只会导致内存消耗下降,因为我从DataFrame 中排除了一些数据。但是,我观察到内存使用量不断增加,并且在某些时候机器内存已耗尽。
这里有什么我错过的吗?我需要在某处显式释放内存吗?
这是一个可以使用随机数据复制行为的简短脚本:
import numpy as np
import pandas as pd
A = pd.DataFrame({'score':np.random.random(132346018), 'coordinate':np.arange(1, 132346019)})
peak_centers = []
peak_scores = []
exclusion = 147
while A.shape[0] > 0:
idx = A.score.values.argmax()
one_center = A.coordinate.iloc[idx]
# peak_centers and peak_scores are python lists
peak_centers.append(one_center)
peak_scores.append(A.score.iloc[idx])
# exclude the coordinates around the selected peak
A = A.loc[(A.coordinate <= one_center - exclusion) | (A.coordinate >= one_center + exclusion)]
# terminated the loop after memory consumption gets to 90% of machine memory
# but peak_centers and peak_scores are still short lists
print len(peak_centers)
# output is 16
【问题讨论】:
-
你打印列表的长度吗?也许你错过了一些东西,尽管你假设它变得越来越大!?
-
我的第一个猜测是 A.shape[0] 永远不会达到 0。while 循环是意外创建无限循环的好方法,并且您在每个循环上都添加了 peak_centers 和 peak_scores。如果你搞砸了,它们会不断变大,直到空间用完。强烈建议如果您必须使用 while 循环,请仔细检查并确保 while 测试在每个循环上都接近 False。
-
到目前为止,我认为这不是原因。请参阅更新的代码以复制此内容。