我正在使用Hyperopt对神经网络进行超参数优化。这样做时,经过一些迭代,我得到了MemoryError异常
到目前为止,我尝试清除所有已使用过的变量(为它们分配无值或空列表,是否有更好的方法呢?)并打印所有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用于Keras时,return
函数的建议create_model
如下所示:
return {'loss': -acc, 'status': STATUS_OK, 'model': model}
但是在具有许多评估的大型模型中,您不想返回每个模型并将其保存在内存中,您所需要做的只是提供给出最低
loss
的超参数集通过简单地从返回的字典中删除模型,解决了每次评估时内存增加的问题。
return {'loss': -acc, 'status': STATUS_OK}
关于python - 如何在Python中找到MemoryError的来源?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55678552/