【问题标题】:Need Help Converting Formula to Tensorflow Style Custom Metric需要帮助将公式转换为 TensorFlow 风格的自定义指标
【发布时间】:2020-09-12 08:38:14
【问题描述】:

我需要帮助创建 Keras 可以在训练期间跟踪的自定义指标回调。我在跑步:

Windows 10
Python 3.6

scikit-learn==0.23.2
pandas==0.25.3
numpy==1.18.5
tensorflow==2.3.0
keras==2.4.3

我要使用的公式如下所示:

step_1 = (True_Positives - False_Positives) / Sum_of_y_true
result = (step_1 -- 1)/(1 -- 1) # For scaling range of (-1, 1) to (0, 1)

我知道 Keras 提供了 TruePositives()FalsePositives() 类,所以我想在一个可以用作回调的自定义函数中利用它,我想伪代码看起来像这样:

def custom_metric():
    Get True_Positives 
    Get False_Positives
    Get Sum_of_y_true

    Perform the above formula

    Return that result into a "tensor" friendly form that can be used for callback

或者这可能是单线回报,我不知道。我不清楚如何使自定义指标“Keras 友好”,因为它似乎不喜欢 numpy 数组或只是常规浮点数?

谢谢!

更新

到目前为止,我尝试过的看起来是这样的。不确定它是否正确,但想知道我是否走在正确的轨道上:

def custom_metric(y_true, y_pred):

    TP = np.logical_and(backend.eval(y_true) == 1, backend.eval(y_pred) == 1)
    FP = np.logical_and(backend.eval(y_true) == 0, backend.eval(y_pred) == 1)

    TP = backend.sum(backend.variable(TP))
    FP = backend.sum(backend.variable(FP))
    SUM_TRUES = backend.sum(backend.eval(y_true) == 1)

    # Need help with this part?
    result = (TP-FP)/SUM_TRUES
    result = (result -- 1)/(1--1)

    return result

【问题讨论】:

    标签: python-3.x tensorflow keras


    【解决方案1】:

    想通了!

    def custom_m(y_true, y_pred):
    
        true_positives = backend.sum(backend.round(backend.clip(y_true * y_pred, 0, 1)))
        predicted_positives = backend.sum(backend.round(backend.clip(y_pred, 0, 1)))
        false_positives = predicted_positives - true_positives
        possible_positives = backend.sum(backend.round(backend.clip(y_true, 0, 1)))
    
        step_1 = (true_positives - false_positives) / possible_positives
        result = (step_1 -- 1)/(1 -- 1)
        
        return result
    

    【讨论】:

      猜你喜欢
      • 2010-11-30
      • 2016-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 1970-01-01
      • 1970-01-01
      • 2018-11-24
      相关资源
      最近更新 更多