keras 提供了sklearn 的接口,我们可以很方便的将我们搭建的模型进行封装,这样的话就可以调用sklearn中非常方便的类例如交叉验证、网格搜索等功能。下面我贴一下利用网格搜索寻找最佳神经元数目的代码,大家一看就能明白该怎么用。
from sklearn.model_selection import GridSearchCV
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.wrappers.scikit_learn import KerasClassifier
def create_model(neurons1,neurons2):
# create model
model = Sequential()
model.add(Dense(neurons1, input_dim=8, kernel_initializer='uniform', activation='linear', kernel_constraint=maxnorm(4)))
model.add(Dropout(0.2))
model.add(Dense(neurons2, kernel_initializer='uniform', activation='sigmoid'))
# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
model = KerasClassifier(build_fn=create_model, epochs=100, batch_size=10, verbose=0) #这里就封装好了,大家直接把model当做sklearn的一个类的对象来用就行
neurons1 = [1, 5, 10, 15, 20, 25, 30]
neurons2 = [1, 5, 10, 15, 20, 25, 30]
param_grid = dict(neurons1=neurons1,neurons2=neurons2)
grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=-1)
参考:https://keras-cn.readthedocs.io/en/latest/scikit-learn_API/