EarlyStopping 忽略我定义的自定义指标。Keras模型

use*_*356 4 machine-learning python-3.x keras

我正在尝试使用 Keras 模型对信用卡欺诈进行分类。由于数据集不平衡,我需要使用f1_score来提高召回率。

显然,它不接受 f1 函数定义。如何监控每个时期的新指标?如果使用 val_loss 但不使用定义的值,提前停止效果很好。我收到这条消息:

Train on 139554 samples, validate on 59810 samples
Epoch 1/10

7s - loss: 0.3585 - acc: 0.9887 - val_loss: 0.0560 - val_acc: 0.9989
/home/libardo/anaconda3/lib/python3.6/site-packages/keras/callbacks.py:526: RuntimeWarning: Early stopping conditioned on metric f1s which is not available. Available metrics are: val_loss,val_acc,loss,acc
(self.monitor, ','.join(list(logs.keys()))), RuntimeWarning
Run Code Online (Sandbox Code Playgroud)

EarlyStopping 忽略我定义的自定义指标 #10018

备注:我无法将我的代码粘贴到此处。我对此表示歉意。

Mat*_*att 5

我意识到这是很久以前发布的,但我在寻找相同答案时发现了这个问题,并最终自己弄清楚了。简而言之,您需要记住既要定义 EarlyStopping Callback 的指标,又要在编译模型时将其作为指标

好的,所以您已经使用类似的内容定义了自定义损失函数或指标(取自https://github.com/keras-team/keras/issues/10018,其本身取自https://stackoverflow.com/ a/45305384/5210098):

#/sf/answers/3171376911/
def f1_metric(y_true, y_pred):

    def recall(y_true, y_pred):
        true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
        possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
        recall = (true_positives + K.epsilon()) / (possible_positives + K.epsilon())
        return recall

    def precision(y_true, y_pred):
        true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
        predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
        precision = (true_positives + K.epsilon()) / (predicted_positives + K.epsilon())
        return precision

    precision = precision(y_true, y_pred)
    recall = recall(y_true, y_pred)
    return 2*((precision*recall)/(precision+recall+K.epsilon()))
Run Code Online (Sandbox Code Playgroud)

现在,要将其与 EarlyStopping 回调一起使用,您可以将其作为字符串提供,例如EarlyStopping(monitor='f1_metric')or ,以监视验证使用EarlyStopping(monitor='val_f1_metric')

但这还不够!如果你停在那里,你会得到你所得到的错误。当您使用 编译模型时,您还需要提供实际函数作为参数model.compile(metrics=[f1_metric])。请注意缺少引号——您正在引用函数本身。

如果您通过包含使用指标关键字的函数来编译模型,并且还包含 EarlyStopping 回调,那么它应该可以正常工作。