超参数调整以决定最佳神经网络
Posted
技术标签:
【中文标题】超参数调整以决定最佳神经网络【英文标题】:Hyperparameter tuning to decide optimal neural network 【发布时间】:2020-06-29 22:34:24 【问题描述】:我想根据某些标准找出最佳神经网络。标准如下:
用一、二、三、四隐藏层 + 输出层测试 4 种架构
要测试的学习率:0.1,0.01,0.001
要测试的时期:10,50,100
输入尺寸 = 20
输出应该是显示每个组合的表格(36 行)。例如,一个隐藏层,lr = 0.1,epochs = 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
【问题讨论】:
正如错误消息所暗示的,您不能将层数用作KerasClassifier
中的超参数。您必须构建单独的模型并分别为每个模型运行网格搜索。
【参考方案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
【讨论】:
以上是关于超参数调整以决定最佳神经网络的主要内容,如果未能解决你的问题,请参考以下文章
TensorFlow从0到1之TensorFlow超参数及其调整(24)