[英]How to calculate True Positive in custom loss function in Keras
I do classification task with Keras, I make simple custom loss function in Keras and it works我用 Keras 做分类任务,我在 Keras 中制作了简单的自定义损失函数并且它有效
import keras.backend as K
def customLoss(yTrue,yPred):
return K.abs(yTrue-yPred)
to make more complex loss function that i want, i need to calculate True Positive, True Negative , False Positive , False Negative为了制作我想要的更复杂的损失函数,我需要计算 True Positive, True Negative , False Positive , False Negative
How to calculate them ?如何计算它们?
i cant calculate them because i dont know the type of yTrue and yPred .我无法计算它们,因为我不知道 yTrue 和 yPred 的类型。 Are they 2D array or list or anything else.
它们是二维数组或列表还是其他任何东西。 if i know, maybe i can calculate TP,TN,FP,FN using for , like this:
如果我知道,也许我可以使用for计算 TP、TN、FP、FN,如下所示:
TP=0
for x,y in zip(yTrue,yPred):
if x == 1 and y > 0.5:
TP=TP+1
According to the Keras Documentation the data types of yTrue/yPred are TensorFlow/Theano tensor depending on the backend you are using.根据 Keras文档,yTrue/yPred 的数据类型是 TensorFlow/Theano 张量,具体取决于您使用的后端。
Therefore, you cannot use a for loop for the loss function, otherwise you will get an error.因此,损失函数不能使用for循环,否则会报错。
But you can use logical and for this matter:但是您可以使用逻辑和来解决这个问题:
TN = np.logical_and(K.eval(y_true) == 0, K.eval(y_pred) == 0)
FP = np.logical_and(K.eval(y_true) == 0, K.eval(y_pred) == 1)
After that you can add them up:之后,您可以将它们相加:
TN = K.sum(K.variable(TN))
FP = K.sum(K.variable(FP))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.