Scikit-learn 管道中的 Keras 模型提前停止

Keras model in Scikit-learn pipeline with early stopping

我正在训练一个位于 Scikit 管道中并经过一些预处理的 Keras 模型。 Keras 模型定义为

from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, Input, Dropout
from tensorflow.keras import optimizers
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.wrappers.scikit_learn import KerasRegressor
from sklearn.pipeline import make_pipeline


def create_model(X_train):
    inp = Input(shape=(X_train.shape[1],))
    x = Dense(150, activation="relu")(inp)
    x = Dropout(0.4)(x)
    mean = Dense(1, activation="linear")(x)
    train_model_1 = Model(inp, mean)
    adam = optimizers.Adam(lr=0.01)
    train_model_1.compile(loss=my_loss_function, optimizer=adam)
    return train_model_1


clf = KerasRegressor(build_fn=create_model, epochs=250, batch_size=64)

然后在 Pipeline

中使用
pipeline = make_pipeline(
                other_steps,
                clf(X_train)
            )


pipeline.fit(X_train, y_train)

我想使用 EarlyStopping,其中测试数据 (X_test, y_test) 用于验证。这通常很简单

callbacks=[EarlyStopping(monitor='val_loss', patience=5)]

train_model_1.fit(X_train, y_train,
                  validation_data=(X_test, y_test),
                  callbacks=callbacks,
                  )

但我不知道这将在管道中进行到哪里。构建这个的正确方法是什么?

Pipeline.fit 有一个关键字参数参数:

**fit_params : dict of string -> object

Parameters passed to the fit method of each step, where each parameter name is prefixed such that parameter p for step s has key s__p.

所以像 pipeline.fit(x_train, y_train, kerasregressor__callbacks=callbacks) 这样的东西应该可以工作。 (检查您的管道步骤的名称,例如使用 pipeline.stepsmake_pipeline 使用 class 的小写名称生成名称,但我不确定是否可以正常工作keras.)

另见