在验证损失满足特定条件时提前停止

我在Keras中训练一个神经网络模型。我希望监控验证损失,并在达到特定条件时停止训练。

我知道我可以使用EarlyStopping在训练没有改善的情况下,经过给定的patience轮次后停止训练。

但我想做一些不同的事情。我希望在val_loss超过某个值,比如x,并且经过n轮次后停止训练。

为了说明清楚,假设x0.5n50。我希望只有在epoch数大于50并且val_loss超过0.5时才停止模型的训练。

我该如何在Keras中实现这一点?


回答:

你可以通过继承Keras的EarlyStopping回调并用你自己的逻辑重写它来定义你自己的回调:

from keras.callbacks import EarlyStopping # use as base classclass MyCallBack(EarlyStopping):    def __init__(self, threshold, min_epochs, **kwargs):        super(MyCallBack, self).__init__(**kwargs)        self.threshold = threshold # threshold for validation loss        self.min_epochs = min_epochs # min number of epochs to run    def on_epoch_end(self, epoch, logs=None):        current = logs.get(self.monitor)        if current is None:            warnings.warn(                'Early stopping conditioned on metric `%s` '                'which is not available. Available metrics are: %s' %                (self.monitor, ','.join(list(logs.keys()))), RuntimeWarning            )            return        # implement your own logic here        if (epoch >= self.min_epochs) & (current >= self.threshold):            self.stopped_epoch = epoch            self.model.stop_training = True

一个小例子来说明它应该能工作:

from keras.layers import Input, Densefrom keras.models import Modelimport numpy as np# Generate some random datafeatures = np.random.rand(100, 5)labels = np.random.rand(100, 1)validation_feat = np.random.rand(100, 5)validation_labels = np.random.rand(100, 1)# Define a simple modelinput_layer = Input((5, ))dense_layer = Dense(10)(input_layer)output_layer = Dense(1)(dense_layer)model = Model(inputs=input_layer, outputs=output_layer)model.compile(loss='mse', optimizer='sgd')# Fit with custom callbackcallbacks = [MyCallBack(threshold=0.001, min_epochs=10, verbose=1)] model.fit(features, labels, validation_data=(validation_feat, validation_labels), callbacks=callbacks, epochs=100)   

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注