我是否可以使用GridSearch或RandomizedSearch进行图像分类来调整keras模型中的超参数?我想根据猫猫数据集对猫猫进行分类。
class smallervggnet:
@staticmethod
def build(width, height, depth, classes, finalAct="softmax"):
# initialize the model along with the input shape to be
# "channels last" and the channels dimension itself
model = Sequential()
inputShape = (height, width, depth)
chanDim = -1
# if we are using "channels first", update the input shape
# and channels dimension
if K.image_data_format() == "channels_first":
inputShape = (depth, height, width)
chanDim = 1
# CONV => RELU => POOL
model.add(Conv2D(32, (3, 3), padding="same",
input_shape=inputShape))
model.add(Activation("relu"))
model.add(BatchNormalization(axis=chanDim))
model.add(MaxPooling2D(pool_size=(3, 3)))
model.add(Dropout(0.25))
# (CONV => RELU) * 2 => POOL
model.add(Conv2D(64, (3, 3), padding="same"))
model.add(Activation("relu"))
model.add(BatchNormalization(axis=chanDim))
model.add(Conv2D(64, (3, 3), padding="same"))
model.add(Activation("relu"))
model.add(BatchNormalization(axis=chanDim))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
# (CONV => RELU) * 2 => POOL
model.add(Conv2D(128, (3, 3), padding="same"))
model.add(Activation("relu"))
model.add(BatchNormalization(axis=chanDim))
model.add(Conv2D(128, (3, 3), padding="same"))
model.add(Activation("relu"))
model.add(BatchNormalization(axis=chanDim))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
# first (and only) set of FC => RELU layers
model.add(Flatten())
model.add(Dense(1024))
model.add(Activation("relu"))
model.add(BatchNormalization())
model.add(Dropout(0.5))
# softmax classifier
model.add(Dense(classes))
model.add(Activation(finalAct))
# return the constructed network architecture
return model
我要调整的是卷积层或调整池化层中的神经元。
param_grid = {'neurons':[4, 8, 16, 32, 64],
'pooling': ['MaxPooling2D', 'AveragePooling2D', 'GlobalMaxPooling2D', 'GlobalAveragePooling2D']
}
其中param_grid应该放入网格搜索或随机搜索中。我该怎么办?
答案 0 :(得分:0)
是的,可以这样做。 做到这一点的方法是使用sci-kit Learn中的KerasClassifier。
clf = KerasBatchClassifier(build_fn=create_model, epochs=epochs, shuffle=True)
grid = GridSearchCV(estimator=clf, param_grid=parameters,return_train_score=False)
grid_result = grid.fit(X,y)
print(grid_result.best_score_)
print(grid_result.best_params_)
create_model是您的构建函数,它接受参数。
您应该考虑一些事情:
要解决这些问题,您可以尝试做一个自定义的KerasClassifier实现,我也做了。在我的方法中,我只进行了3次交叉验证。我使用了20%的训练数据来利用提前停止,并将其用于处理发电机。