Keras自定义决策阈值以实现精确度和召回率 [英] Keras custom decision threshold for precision and recall

查看:1149
本文介绍了Keras自定义决策阈值以实现精确度和召回率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Keras(具有Tensorflow后端)进行二进制分类,并且我获得了约76%的精度和70%的召回率.现在,我想尝试使用决策阈值.据我所知,Keras使用决策阈值0.5. Keras中是否可以使用自定义阈值来提高决策精度和召回率?

I'm doing a binary classification using Keras (with Tensorflow backend) and I've got about 76% precision and 70% recall. Now I want to try to play with decision threshold. As far as I know Keras uses decision threshold 0.5. Is there a way in Keras to use custom threshold for decision precision and recall?

谢谢您的时间!

推荐答案

创建这样的自定义指标:

create custom metrics like this :

感谢@Marcin 进行了创建以threshold_value作为参数返回所需指标的函数

Edited thanks to @Marcin : Create functions that returns the desired metrics with threshold_value as argument

def precision_threshold(threshold=0.5):
    def precision(y_true, y_pred):
        """Precision metric.
        Computes the precision over the whole batch using threshold_value.
        """
        threshold_value = threshold
        # Adaptation of the "round()" used before to get the predictions. Clipping to make sure that the predicted raw values are between 0 and 1.
        y_pred = K.cast(K.greater(K.clip(y_pred, 0, 1), threshold_value), K.floatx())
        # Compute the number of true positives. Rounding in prevention to make sure we have an integer.
        true_positives = K.round(K.sum(K.clip(y_true * y_pred, 0, 1)))
        # count the predicted positives
        predicted_positives = K.sum(y_pred)
        # Get the precision ratio
        precision_ratio = true_positives / (predicted_positives + K.epsilon())
        return precision_ratio
    return precision

def recall_threshold(threshold = 0.5):
    def recall(y_true, y_pred):
        """Recall metric.
        Computes the recall over the whole batch using threshold_value.
        """
        threshold_value = threshold
        # Adaptation of the "round()" used before to get the predictions. Clipping to make sure that the predicted raw values are between 0 and 1.
        y_pred = K.cast(K.greater(K.clip(y_pred, 0, 1), threshold_value), K.floatx())
        # Compute the number of true positives. Rounding in prevention to make sure we have an integer.
        true_positives = K.round(K.sum(K.clip(y_true * y_pred, 0, 1)))
        # Compute the number of positive targets.
        possible_positives = K.sum(K.clip(y_true, 0, 1))
        recall_ratio = true_positives / (possible_positives + K.epsilon())
        return recall_ratio
    return recall

现在您可以在其中使用它们

now you can use them in

model.compile(..., metrics = [precision_threshold(0.1), precision_threshold(0.2),precision_threshold(0.8), recall_threshold(0.2,...)])

我希望这会有所帮助:)

I hope this helps :)

这篇关于Keras自定义决策阈值以实现精确度和召回率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆