0

是否可以在 Keras 中指定数量的 epoch 后应用 Early Stopping。例如,我想将我的 NN 训练 45 个 epoch,然后开始使用 EarlyStopping。

到目前为止,我是这样做的:

early_stop = EarlyStopping(monitor='val_loss', mode='min', verbose=1, baseline = 0.1, patience = 3)

opt = Adam(lr = .00001, beta_1=0.9, beta_2=0.999, epsilon=1e-8)
model.compile(optimizer=opt, loss='categorical_crossentropy', metrics = ['accuracy'])
mod = model.fit_generator(train_batches, steps_per_epoch = 66, validation_data = valid_batches, validation_steps = 22, epochs = 45, verbose = 1)
mod = model.fit_generator(train_batches, steps_per_epoch = 66, validation_data = valid_batches, validation_steps = 22, epochs = 50, callbacks = [early_stop], verbose = 1)

但是这样做只会产生几个步骤图用于训练

在此处输入图像描述

有没有办法可以一起写这些?非常感谢任何帮助!

4

1 回答 1

-1

我认为我们可以使用 Keras 库中的自定义回调来执行此操作。如下定义您的自定义回调:

# Custom Callback
class myCallback(keras.callbacks.Callback):
  def on_epoch_end(self, epoch, logs={}):
    if epoch == 45:
      self.model.stop_training = True
callback = myCallback()

opt = Adam(lr = .00001, beta_1=0.9, beta_2=0.999, epsilon=1e-8)
model.compile(optimizer=opt, loss='categorical_crossentropy', metrics = ['accuracy'])
# Include myCallback in callbacks so that the model stops training after 45th epoch
mod = model.fit_generator(train_batches, steps_per_epoch = 66, validation_data = valid_batches, validation_steps = 22, epochs = 50, callbacks = [early_stop, myCallback], verbose = 1)
于 2020-07-12T10:37:31.927 回答