使用Keras神经网络进行GridSearch

使用Keras神经网络进行GridSearch

本文介绍了使用Keras神经网络进行GridSearch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为使用keras构建的神经网络执行参数调整.这是我的代码,在引起错误的行上带有注释:

I'm trying to perform parameters tuning for a neural network built with keras. This is my code with a comment on the line that causes the error:

from sklearn.cross_validation import StratifiedKFold, cross_val_score
from sklearn import grid_search
from sklearn.metrics import classification_report
import multiprocessing

from keras.models import Sequential
from keras.layers import Dense
from sklearn.preprocessing import LabelEncoder
from keras.utils import np_utils
from keras.wrappers.scikit_learn import KerasClassifier
import numpy as np


def tuning(X_train,Y_train,X_test,Y_test):

  in_size=X_train.shape[1]
  num_cores=multiprocessing.cpu_count()
  model = Sequential()
  model.add(Dense(in_size, input_dim=in_size, init='uniform', activation='relu'))
  model.add(Dense(8, init='uniform', activation='relu'))
  model.add(Dense(1, init='uniform', activation='sigmoid'))
  model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

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

  k_model = KerasClassifier(build_fn=model, verbose=0)
  clf = grid_search.GridSearchCV(estimator=k_model, param_grid=param_grid, cv=StratifiedKFold(Y_train, n_folds=10, shuffle=True, random_state=1234),
                   scoring="accuracy", verbose=100, n_jobs=num_cores)

  clf.fit(X_train, Y_train) #ERROR HERE

  print("Best parameters set found on development set:")
  print()
  print(clf.best_params_)
  print()
  print("Grid scores on development set:")
  print()
  for params, mean_score, scores in clf.grid_scores_:
    print("%0.3f (+/-%0.03f) for %r"
        % (mean_score, scores.std() * 2, params))
  print()
  print("Detailed classification report:")
  print()
  print("The model is trained on the full development set.")
  print("The scores are computed on the full evaluation set.")
  print()
  y_true, y_pred = Y_test, clf.predict(X_test)
  print(classification_report(y_true, y_pred))
  print()

这是错误报告:

 clf.fit(X_train, Y_train)
  File "/usr/local/lib/python2.7/dist-packages/sklearn/grid_search.py", line 804, in fit
    return self._fit(X, y, ParameterGrid(self.param_grid))
  File "/usr/local/lib/python2.7/dist-packages/sklearn/grid_search.py", line 553, in _fit
    for parameters in parameter_iterable
  File "/usr/local/lib/python2.7/dist-packages/sklearn/externals/joblib/parallel.py", line 800, in __call__
    while self.dispatch_one_batch(iterator):
  File "/usr/local/lib/python2.7/dist-packages/sklearn/externals/joblib/parallel.py", line 658, in dispatch_one_batch
    self._dispatch(tasks)
  File "/usr/local/lib/python2.7/dist-packages/sklearn/externals/joblib/parallel.py", line 566, in _dispatch
    job = ImmediateComputeBatch(batch)
  File "/usr/local/lib/python2.7/dist-packages/sklearn/externals/joblib/parallel.py", line 180, in __init__
    self.results = batch()
  File "/usr/local/lib/python2.7/dist-packages/sklearn/externals/joblib/parallel.py", line 72, in __call__
    return [func(*args, **kwargs) for func, args, kwargs in self.items]
  File "/usr/local/lib/python2.7/dist-packages/sklearn/cross_validation.py", line 1531, in _fit_and_score
    estimator.fit(X_train, y_train, **fit_params)
  File "/usr/local/lib/python2.7/dist-packages/keras/wrappers/scikit_learn.py", line 135, in fit
    **self.filter_sk_params(self.build_fn.__call__))
TypeError: __call__() takes at least 2 arguments (1 given)

我错过了什么吗?网格搜索非常适合随机森林,svm和逻辑回归.我只有神经网络有问题.

Am I missing something? The grid search goes well with random forests, svm and logistic regression. I only have problems with Neural Networks.

推荐答案

此处错误指示build_fn需要具有2个参数,如param_grid中的#个参数所示.

Here the error indicates that the build_fn needs to have 2 arguments as indicated from the # of parameters from param_grid.

因此,您需要显式定义一个新函数并将其用作build_fn=make_model

So you need to explicitly define an new function and use that as build_fn=make_model

def make_model(batch_size, nb_epoch):
    model = Sequential()
    model.add(Dense(in_size, input_dim=in_size, init='uniform', activation='relu'))
    model.add(Dense(8, init='uniform', activation='relu'))
    model.add(Dense(1, init='uniform', activation='sigmoid'))
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

还要检查keras/examples/mnist_sklearn_wrapper.py,其中GridSearchCV用于超参数搜索.

Also check keras/examples/mnist_sklearn_wrapper.py where GridSearchCV is used for hyper-parameter search.

这篇关于使用Keras神经网络进行GridSearch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 12:35