用于多标签分类的keras自定义指标

用于多标签分类的keras自定义指标

本文介绍了用于多标签分类的keras自定义指标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Sigmoid binary_crossentropy 进行多标签分类。

I'm using sigmoid and binary_crossentropy for multi-label classification.

例如, y_true 的标签类似于 [1,0,1, 0,0] ,标签 y_pred 就像 [0.8,0.3,0.9,0,0]

For example, the label of y_true is like [1,0,1,0,0], and the label of y_pred is like [0.8,0.3,0.9,0,0].

如何设置Keras自定义指标函数,以使 y_pred 中的每个元素大于0.5的映射为1, y_pred 中的每个小于0.5的元素映射为0,然后比较 y_pred y_true 的c $ c>?

How can I set a Keras custom metric function so that each element in y_pred larger than 0.5 is mapped to 1, each element in y_pred lower than 0.5 is mapped to 0, then compare the number of labels in y_pred that matches the y_true?

推荐答案

在进行多标签分类时,您似乎希望将整个真实标签和预测标签相互比较。例如,对于一个具有真实标签 [1、0、0] 和预测标签 [0、0、0]的单个样本您将预测精度视为零(尽管第二和第三类的标签已正确预测)。如果是这样,您可以比较标签,然后从后端使用 all()方法来确保所有类的标签相互匹配:

Since you are doing multi-label classification, it seems you want to compare the whole true and predicted labels with each other. For example, for one single sample with a true label of [1, 0, 0] and a predicted label of [0, 0, 0] you consider the prediction accuracy as zero (despite the fact that the labels for the second and third classes have been predicted correctly). If that's the case, you can compare the labels and then use all() method from backend to make sure the labels for all the classes match with each other:

from keras import backend as K

def full_multi_label_metric(y_true, y_pred):
    comp = K.equal(y_true, K.round(y_pred))
    return K.cast(K.all(comp, axis=-1), K.floatx())

这篇关于用于多标签分类的keras自定义指标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 18:32