如果在纪元 y 的准确度低于 x,则停止在 Keras 中的训练

数据挖掘 喀拉斯
2022-03-14 05:05:21

除了 KERAS 中基本的提前停止功能外,如果在 epoch 40 时验证准确率仍低于 0.80,我想停止训练。

我怎样才能做到这一点?

1个回答

我认为不存在具有此类功能的现有回调,但您可以编写自定义回调来完成此操作。请参阅以下示例,该示例从此 stackoverflow 答案复制并针对您的特定示例进行了修改:

from keras.callbacks import Callback

class TerminateOnBaseline(Callback):
    """
    Callback that terminates training when either acc or val_acc reaches a specified
    baseline after a specified number of epochs
    """
    def __init__(self, monitor='val_accuracy', baseline=0.8, n_epochs=40):
        super(TerminateOnBaseline, self).__init__()
        self.monitor = monitor
        self.baseline = baseline
        self.n_epochs = n_epochs

    def on_epoch_end(self, epoch, logs=None):
        logs = logs or {}
        acc = logs.get(self.monitor)
        if acc is not None:
            if acc < self.baseline and epoch >= self.n_epochs:
                print('Epoch %d: Accuracy has not reached the baseline, terminating training' % (epoch))
                self.model.stop_training = True

callbacks然后,您可以在使用方法中的参数训练模型时包含此回调fit