需要帮助将公式转换为Tensorflow样式自定义指标 [英] Need Help Converting Formula to Tensorflow Style Custom Metric

查看:76
本文介绍了需要帮助将公式转换为Tensorflow样式自定义指标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need help creating a custom metric callback that Keras can track during training. I'm running:

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()类,因此我想在自定义函数中加以利用,该函数可用作回调,我想像是伪代码,它看起来像: /p>

I know Keras offers the TruePositives() and FalsePositives() classes, so I'd like to take advantage of that in a custom function that can be used as a callback, pseudo-code I imagine would look something like:

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数组,也不喜欢常规的浮点数?

Or maybe this could be a one-liner return, I don't know. I'm unclear about how to make a custom metric "Keras friendly", as it doesn't appear to like numpy arrays or just regular float numbers?

谢谢!

更新

到目前为止,我尝试过的事情看起来像这样.不确定是否正确,但想知道我是否走对了:

What I've attempted so far looks like this. Not sure if it's correct but would like to know if I'm on the right track:

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

推荐答案

想通了!

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

这篇关于需要帮助将公式转换为Tensorflow样式自定义指标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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