超参数调整以决定最佳神经网络

时间:2020-03-18 19:21:39

标签: python machine-learning keras scikit-learn neural-network

我想根据某些标准找到最佳的神经网络。条件如下:

  • 使用1、2、3、4个隐藏层+输出层测试4种架构

  • 要测试的学习率:0.1、0.01、0.001

  • 要测试的历次:10,50,100

  • 输入尺寸= 20

输出应该是一个表,显示每个组合(36行)。例如,对于一个隐藏层lr = 0.1,历元= 10,精度为X。

请,请参见下面的代码:

#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)

但是当我运行代码时,出现以下错误:

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

1 个答案:

答案 0 :(得分:1)

无法克隆对象不是主要问题。这是模型生成器函数中另一个错误的结果。
您在 create_model()中遇到了一些语法错误。请查看输出中“克隆问题”之前的错误。
这是固定功能:

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