gpt4 book ai didi

python - 如何找到Python中MemoryError的来源?

转载 作者:行者123 更新时间:2023-12-01 08:02:15 25 4
gpt4 key购买 nike

我正在使用 Hyperopt 为神经网络运行超参数优化。这样做时,经过一些迭代后,我收到 MemoryError 异常

到目前为止,我尝试在使用后清除所有变量(为它们分配 None 或空列表,有更好的方法吗?)并打印所有 locals()、dirs() 和 globals() 及其值大小,但这些计数永远不会增加,而且大小非常小。

结构如下:

def create_model(params):
## load data from temp files
## pre-process data accordingly
## Train NN with crossvalidation clearing Keras' session every time
## save stats and clean all variables (assigning None or empty lists to them)

def Optimize():
for model in models: #I have multiple models
## load data
## save data to temp files
trials = Trials()
best_run = fmin(create_model,
space,
algo=tpe.suggest,
max_evals=100,
trials=trials)

经过 X 次迭代后(有时它完成前 100 次并转移到第二个模型),它会抛出内存错误。我的猜测是,某些变量保留在内存中,我没有清除它们,但我无法检测到它们。

编辑:

Traceback (most recent call last):
File "Main.py", line 32, in <module>
optimal = Optimize(training_sets)
File "/home/User1/Optimizer/optimization2.py", line 394, in Optimize
trials=trials)
File "/usr/local/lib/python3.5/dist-packages/hyperopt/fmin.py", line 307, in fmin
return_argmin=return_argmin,
File "/usr/local/lib/python3.5/dist-packages/hyperopt/base.py", line 635, in fmin
return_argmin=return_argmin)
File "/usr/local/lib/python3.5/dist-packages/hyperopt/fmin.py", line 320, in fmin
rval.exhaust()
File "/usr/local/lib/python3.5/dist-packages/hyperopt/fmin.py", line 199, in exhaust
self.run(self.max_evals - n_done, block_until_done=self.async)
File "/usr/local/lib/python3.5/dist-packages/hyperopt/fmin.py", line 173, in run
self.serial_evaluate()
File "/usr/local/lib/python3.5/dist-packages/hyperopt/fmin.py", line 92, in serial_evaluate
result = self.domain.evaluate(spec, ctrl)
File "/usr/local/lib/python3.5/dist-packages/hyperopt/base.py", line 840, in evaluate
rval = self.fn(pyll_rval)
File "/home/User1/Optimizer/optimization2.py", line 184, in create_model
x_train, x_test = x[train_indices], x[val_indices]
MemoryError

最佳答案

我花了几天时间才弄清楚这个问题,所以我会回答我自己的问题,以节省遇到此问题的人的时间。

通常,当使用 Hyperopt for Keras 时,建议 create_model 函数的返回如下所示:

return {'loss': -acc, 'status': STATUS_OK, 'model': model}

但是在进行多次评估的大型模型中,您不想返回每个模型并将其保存在内存中,您需要的只是给出最低损失的一组超参数

通过简单地从返回的字典中删除模型,就解决了每次评估时内存增加的问题。

return {'loss': -acc, 'status': STATUS_OK}

关于python - 如何找到Python中MemoryError的来源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55678552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com