在Keras中進行超參數調優通常使用GridSearchCV或RandomizedSearchCV來完成。以下是一個使用GridSearchCV進行超參數調優的示例:
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import GridSearchCV
def create_model(optimizer='adam', activation='relu'):
model = Sequential()
model.add(Dense(units=64, activation=activation, input_shape=(X_train.shape[1],)))
model.add(Dense(units=1, activation='sigmoid'))
model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy'])
return model
model = KerasClassifier(build_fn=create_model, epochs=5, batch_size=32)
param_grid = {'optimizer': ['adam', 'sgd'],
'activation': ['relu', 'tanh']}
grid = GridSearchCV(estimator=model, param_grid=param_grid, cv=3)
grid_result = grid.fit(X_train, y_train)
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
best_model = grid_result.best_estimator_
best_params = grid_result.best_params_
通過這種方法,您可以使用GridSearchCV來搜索最佳的超參數組合,以優化模型的性能。您還可以嘗試使用RandomizedSearchCV來進行隨機搜索超參數調優。