网格使用keras搜索隐藏层的数量

Dan*_*el 3 python neural-network hyperparameters keras

我正在尝试使用Keras和sklearn来优化我的NN的超参数.我正在使用KerasClassifier(这是一个分类问题).我正在尝试优化隐藏层的数量.我不知道如何用keras做到这一点(实际上我想知道如何设置函数create_model以最大化隐藏层的数量)有谁可以帮助我?

我的代码(只是重要部分):

## Import `Sequential` from `keras.models`
from keras.models import Sequential

# Import `Dense` from `keras.layers`
from keras.layers import Dense

def create_model(optimizer='adam', activation = 'sigmoid'):
  # Initialize the constructor
  model = Sequential()
  # Add an input layer
  model.add(Dense(5, activation=activation, input_shape=(5,)))
  # 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
my_classifier = KerasClassifier(build_fn=create_model, verbose=0)# Create 
hyperparameter space
epochs = [5, 10]
batches = [5, 10, 100]
optimizers = ['rmsprop', 'adam']
activation1 = ['relu','sigmoid']
# Create grid search
grid = RandomizedSearchCV(estimator=my_classifier, 
param_distributions=hyperparameters) #inserir param_distributions

# Fit grid search
grid_result = grid.fit(X_train, y_train)
# Create hyperparameter options
hyperparameters = dict(optimizer=optimizers, epochs=epochs, 
batch_size=batches, activation=activation1)
# View hyperparameters of best neural network
grid_result.best_params_
Run Code Online (Sandbox Code Playgroud)

小智 11

如果要将隐藏图层的数量设置为超参数,则必须将其作为参数添加到您的KerasClassifier build_fn喜好中:

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
Run Code Online (Sandbox Code Playgroud)

然后你就可以将其添加到字典中,它被传递到优化隐层的数目RandomizedSearchCVparam_distributions.

还有一件事,你可能应该将activation输出层的使用与其他层分开.不同类别的激活函数适用于隐藏层和二进制分类中使用的输出层.