【问题标题】:Custom loss function Keras backend自定义损失函数 Keras 后端
【发布时间】:2018-08-06 20:12:33
【问题描述】:

我在实现一个自定义损失函数时遇到了困难,该函数应该测量分类数据的召回率。

有关更详细的问题描述,请参阅: Classification: skewed data within a class

我已经用 numpy 数组实现了它,但是如何将它转换为 Keras 后端?有人有想法吗?

# Try Recall for the loss
def customLoss(yTrue,yPred):
   true_positives = np.sum(np.logical_and(yPred, yTrue))
   total = np.sum(np.sum(yTrue))
   return true_positives/total

提前致谢!

【问题讨论】:

标签: python machine-learning keras classification


【解决方案1】:

我们必须使用处理张量的 tensorflow 数学库,而不是使用 numpy。您可以在以下链接中找到数学示例:tf.reduce_sum()

您必须小心张量元素的数据类型。 tf.logical_and 函数只接受布尔输入,因此 yTrue 和 yPred 必须转换为布尔值。既然要float输出,建议把logical_and运算的输出转换成float的dtype。

您的自定义损失函数应如下所示(或多或少):

import tensorflow as tf
def customLoss(yTrue,yPred):
    # Convert yPred and yTrue to boolean
    yPred_bool = tf.equal(yPred > 0.5, True)
    yTrue_bool = tf.equal(yTrue > 0.5, True)    
    # Count number of true positive labels
    true_positives = tf.reduce_sum(tf.cast(tf.logical_and(yPred_bool, yTrue_bool),dtype=tf.float32), axis=0)
    # Count number of positive labels
    total = tf.reduce_sum(tf.cast((yTrue > 0.5),dtype=tf.float32),axis=0)
    return true_positives/total

希望有用。干杯!

【讨论】:

    猜你喜欢
    • 2018-12-26
    • 1970-01-01
    • 2020-12-19
    • 2017-12-18
    • 2020-03-27
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 2018-12-03
    相关资源
    最近更新 更多