[TensorFlow 2.0] Keras使用Grid Search进行参数选择

首先安装scikeras:

pip install scikeras

使用KerasClassifier类对模型进行封装

# coding = utf-8

from scikeras.wrappers import KerasClassifier
from sklearn.model_selection import GridSearchCV

from tensorflow import keras

# Prepare data X_train: ndarray,(60000, 28, 28) y_train: ndarray, (60000,)
(X_train, y_train), (X_valid, y_valid) = keras.datasets.fashion_mnist.load_data()
X_train = X_train / 255.0
X_valid = X_valid / 255.0


# Build model
def create_model(hidden_num=4):
    inputs = keras.Input(shape=(28, 28))
    x = keras.layers.Flatten()(inputs)
    x = keras.layers.Dense(hidden_num, activation='relu')(x)
    outputs = keras.layers.Dense(10, activation='softmax')(x)

    model = keras.Model(inputs, outputs)

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


# Grid search
param_grid = {
    'epochs': [10, 20],
    'batch_size': [8, 16, 32],
    'hidden_num': [4, 8]
}
model = KerasClassifier(model=create_model, hidden_num=4)
grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=1, cv=5, verbose=3)
grid_result = grid.fit(X_train, y_train)

# Print grid search result
print(f'Best: {grid_result.best_score_} using {grid_result.best_params_}')
means = grid_result.cv_results_['mean_test_score']
stds = grid_result.cv_results_['std_test_score']
params = grid_result.cv_results_['params']

for mean, std, param in zip(means, stds, params):
    print(f"{mean} {std} with: {param}")

1、对于model.fit()函数原有的参数,比如epchos、batch_size,可以直接放进字典里
2、自定义的参数,比如上面的hidden_num,在创建KerasClassifier时需要当做参数传入。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

手撕机

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值