如何使用tensorflow.models.Sequential()提前停止?

时间:2019-01-30 20:27:51

标签: tensorflow keras deep-learning

使用这样生成的顺序模型:

def generate_model():
    model = Sequential()
    model.add(Conv1D(64, kernel_size=10, strides=1,
                     activation='relu', padding='same',
                     input_shape=(MAXLENGTH, NAMESPACELENGTH)))
    model.add(MaxPooling1D(pool_size=4, strides=2))
    model.add(Conv1D(32, 3, activation='relu', padding='same'))
    model.add(MaxPooling1D(pool_size=4))
    model.add(Flatten())
    model.add(Dense(10, activation='relu'))
    model.add(Dense(1, activation='linear'))
    model.compile(loss='mean_squared_error', 
                  optimizer='adam', metrics=['mean_squared_error'])
    return model

我想进行Kfold交叉验证建模。因此,我循环训练了K个模型:

models = []
for ndx_train, ndx_val in kfold.split(X, y):
    model = generate_model()
    N_train = len(ndx_train)
    X_batch = X[ndx_train]
    y_batch = y[ndx_train]
    model.fit(X_batch, y_batch, epochs=100, verbose=1, steps_per_epoch=10,
             validation_data=(X[ndx_val], y[ndx_val]), validation_steps=100)

    models.append(model)

现在,通过查看输出,可以看到何时希望每个模型停止运行。即当验证错误再次增加时。是否可以使用纯tf并使用此更高级别的api设置轻松地做到这一点?有一些建议使用tflearn here

1 个答案:

答案 0 :(得分:2)

通过使用EarlyStopping回调:

from tensorflow.keras.callbacks import EarlyStopping
callbacks = [
    EarlyStopping(monitor='val_mean_squared_error', patience=2, verbose=1),
]
model.fit(..., callbacks=callbacks)