【问题标题】:Keras custom decision threshold for precision and recallKeras 自定义决策阈值,用于准确率和召回率
【发布时间】:2017-07-25 04:14:24
【问题描述】:

我正在使用Keras(带有Tensorflow 后端)进行二元分类,我的准确率约为 76%,召回率约为 70%。现在我想尝试使用决策阈值。据我所知Keras 使用决策阈值 0.5。 Keras 有没有办法使用自定义阈值来实现决策精度和召回率?

感谢您的宝贵时间!

【问题讨论】:

  • 为了完成:Keras 现在本机包含一个阈值参数,用于基于 True/False Positives/Negatives 的指标。

标签: python machine-learning tensorflow classification keras


【解决方案1】:

像这样创建自定义指标:

感谢@Marcin 编辑:创建以threshold_value 作为参数返回所需指标的函数

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

现在你可以使用它们了

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

我希望这会有所帮助:)

【讨论】:

  • @NassimBen 不错的解决方案。我想做一些非常相似的事情,但根据y_pred 中的kth 最大值动态计算threshold_value:我在这里问过这个问题:stackoverflow.com/questions/45720458/…
  • 如果我给它不同的阈值并以什么精度或召回值保存模型,模型将被保存?
  • 这里是[另一种方法](stackoverflow.com/questions/52041931/…),我不知道为什么这两个代码在相同的阈值下会产生不同的结果,并且它们都与我用预测计算的值不同结果(而 keras_metrics.precision() 返回 0.5 阈值的正确答案)。
  • @Mohsin 我相信该模型根本不会保存精度或召回值。它们仅用于评估。训练后,您可以保存权重,这些权重旨在降低损失值。
猜你喜欢
  • 1970-01-01
  • 2022-12-17
  • 1970-01-01
  • 2018-06-02
  • 1970-01-01
  • 2014-10-07
  • 2020-03-26
  • 2020-09-02
  • 2021-02-22
相关资源
最近更新 更多