Python 为什么“GridSearchCV”上的第二个“fit”调用会无休止地工作?

Python 为什么“GridSearchCV”上的第二个“fit”调用会无休止地工作?,python,machine-learning,scikit-learn,keras,jupyter-notebook,Python,Machine Learning,Scikit Learn,Keras,Jupyter Notebook,我正在使用sklearn中的GridSearchCV调整Keras模型中的超参数,如中所示 我调用fit方法来寻找最佳超参数 grid_result = grid.fit(X, Y) 但是,假设我想更改batch_大小,并再次调用fit(无需在Jupyter中重新启动内核) 当我调用fit grid_result = grid.fit(X, Y) 它无休止地工作,不会终止。为了适应这个改变了的参数,我必须重新启动内核,然后重新加载数据、模块等 问题。如果不重新启动内核,如何在GridSear

我正在使用
sklearn
中的
GridSearchCV
调整
Keras
模型中的超参数,如中所示

我调用
fit
方法来寻找最佳超参数

grid_result = grid.fit(X, Y)
但是,假设我想更改
batch_大小
,并再次调用
fit
(无需在Jupyter中重新启动内核)

当我调用
fit

grid_result = grid.fit(X, Y)
它无休止地工作,不会终止。为了适应这个改变了的参数,我必须重新启动内核,然后重新加载数据、模块等

问题。如果不重新启动内核,如何在
GridSearchCV
上第二次调用
fit


详细信息。我使用。详细片段:

import numpy as np
from sklearn.model_selection import GridSearchCV
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier

def create_model():
    model = Sequential()
    model.add(Dense(12, input_dim=8, activation='relu'))
    model.add(Dense(1, activation='sigmoid'))
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

dataset = np.loadtxt("data/pima-indians-diabetes.data.csv", delimiter=",")
X = dataset[:,0:8]
y = dataset[:,8]

model = KerasClassifier(build_fn=create_model, verbose=0)

batch_size = [10, 20, 40, 60, 80, 100]
epochs = [10, 50]
param_grid = dict(batch_size = batch_size, epochs = epochs)

grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=-1)
然后我调用
fit
,它工作正常

grid_result = grid.fit(X, y)
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
Out:
Best:0.690104使用{'batch_size':10,'epochs':50}

然后,我运行以下命令进行一些更改:

batch_size = [5, 10, 15, 20]
param_grid = dict(batch_size = batch_size, epochs = epochs)
grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=-1)
最后,我第二次调用
fit
,它从未停止过

grid_result = grid.fit(X, y)

我可以在我的MacBook Pro上重现错误。 我也使用了
pima.data.csv
dataset

这里的问题是tensorflow会话。如果在
GridSearchCV.fit()之前的父进程中创建了会话,它肯定会挂起

一种可能的解决方案是将所有会话创建代码限制在
KerasClassifier
类和模型创建函数中

此外,您可能希望在模型创建函数或
KerasClassifier
的子类中限制TF的内存使用


快速解决方案:

n_jobs = 1
但这需要很长时间才能完成


参考文献:

n_jobs = 1


您使用什么数据集?我现在正试图确认这个问题。你会在笔记本上运行代码吗?@seralouk我会用细节粘贴整个snnipet。你能重现这个问题吗?@是的,我已经发布了一个答案快速解决方案,但是如果你使用Winsdows,我仍然会尝试在函数
创建模型
中加载
keras
模块。是的,另一个尝试是使用
如果你使用Winsdows。让我知道,请考虑接受我的答案。我正在使用谷歌计算VM与Debian。我将浏览您提供的链接,并尝试为我找到最佳解决方案
n_jobs=1
是一个糟糕的解决方案,因为我的虚拟机提供了多个CPU。我试图将代码包装到函数(和函数)中,并将
keras
模块导入其中,但我发现我这样做是盲目的,没有任何效果。根据您的说明,我猜一个可能的解决方案是将所有会话创建代码限制在KerasClassifier类和模型创建函数中。从你第一个链接的帖子来看,这是可能的。你能给我一些提示怎么做吗?
n_jobs = 1