Hyperparameter tuning to decide optimal neural network

Viewed 278

I would like to find which is the optimal neural network based on some criteria. The criteria are the following ones:

  • Test 4 architectures with one, two, three, four hidden layers + output layer

  • Learning rates to be tested: 0.1,0.01,0.001

  • Epochs to be tested: 10,50,100

  • Input dimensions = 20

The output should be a table showing each combination (36 rows). For example, with one hidden layer, lr = 0.1, epochs = 10, the accuracy was X.

Please, see my code below:

#Function to create the model
def create_model(layers,learn_rate):
    model = Sequential()
    for i, nodes in enumerate(layers):
        if i==0:
            model.add(Dense(nodes),input_dim = 20,activation = 'relu')
        else:
            model.add(Dense(nodes),activation = 'relu')   

    model.add(Dense(units = 4,activation = 'softmax')) 

    model.compile(optimizer=adam(lr=learn_rate), loss='categorical_crossentropy',metrics=['accuracy'])
    return model

#Initialization of variables
#Here there are the four possible types of layers with the neurons in each.
layers = [[20], [40, 20], [45, 30, 15],[32,16,8,4]]
learn_rate = [0.1,0.01,0.001]
epochs = [10,50,100]

#GridSearchCV for hyperparameter tuning
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import GridSearchCV
model = KerasClassifier(build_fn = create_model, verbose = 0)
param_grid = dict(layers = layers,learn_rate = learn_rate,epochs = epochs)
grid = GridSearchCV(estimator = model, param_grid = param_grid,cv = 3)
grid_result = grid.fit(train_x,train_y)

But when I´m running the code I get the following error:

RuntimeError: Cannot clone object <keras.wrappers.scikit_learn.KerasClassifier object at    0x000001AA272C7748>, as the constructor either does not set or modifies parameter layers
1 Answers

Cannot clone object is not main problem. It is consequence of another error in model generator function.
You had some syntax errors in create_model(). Please look at errors that were before "Cloning problem" in your output.
Here is fixed function:

from keras import optimizers

def create_model(layers, learn_rate):
    model = Sequential()
    for i, nodes in enumerate(layers):
        if i==0:
            model.add(Dense(nodes,input_dim = 20,activation = 'relu'))
        else:
            model.add(Dense(nodes,activation = 'relu'))
    model.add(Dense(units = 4,activation = 'softmax')) 

    model.compile(optimizer=optimizers.adam(lr=learn_rate), loss='categorical_crossentropy',metrics=['accuracy']) 
    return model
Related