Grid Search the number of hidden layers with keras

被刻印的时光 ゝ 提交于 2019-12-03 18:56:51

If you want to make the number of hidden layers a hyperparameter you have to add it as parameter to your KerasClassifier build_fn like:

def create_model(optimizer='adam', activation = 'sigmoid', hidden_layers=1):
  # Initialize the constructor
  model = Sequential()
  # Add an input layer
  model.add(Dense(5, activation=activation, input_shape=(5,)))

  for i in range(hidden_layers):
      # Add one hidden layer
      model.add(Dense(8, activation=activation))

  # Add an output layer 
  model.add(Dense(1, activation=activation))
  #compile model
  model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=
  ['accuracy'])
  return model

Then you will be able to optimize the number of hidden layers by adding it to the dictionary, which is passed to RandomizedSearchCV's param_distributions.

One more thing, you probably should separate the activation you use for the output layer from the other layers. Different classes of activation functions are suitable for hidden layers and for output layers used in binary classification.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!