需要帮助将公式转换为Tensorflow样式自定义度量



我需要帮助创建一个自定义度量回调,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 friendly";,因为它看起来不像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

想明白了!

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

最新更新