Tensorflow 如何定义Keras中的自定义精度以忽略带有特定金标签的样品?

Tensorflow 如何定义Keras中的自定义精度以忽略带有特定金标签的样品?,tensorflow,keras,metrics,Tensorflow,Keras,Metrics,我想在Keras中编写一个自定义度量(我使用的是tensorflow后端),相当于分类精度,但必须忽略带有特定金标签的样本的输出(在我的示例中为0,来自y_true)。例如,如果我的输出为: Pred 1-黄金0 Pred 1-黄金1 精度为1,因为必须忽略带有金标签0的样本。也就是说,我编写的函数(没有给出预期的结果)是: 感谢您的帮助,谢谢 您可以尝试以下方法: def ignore_accuracy_of_class(class_to_ignore=0): def ignore_a

我想在Keras中编写一个自定义度量(我使用的是tensorflow后端),相当于
分类精度
,但必须忽略带有特定金标签的样本的输出(在我的示例中为0,来自y_true)。例如,如果我的输出为:

Pred 1-黄金0

Pred 1-黄金1

精度为1,因为必须忽略带有金标签0的样本。也就是说,我编写的函数(没有给出预期的结果)是:


感谢您的帮助,谢谢

您可以尝试以下方法:

def ignore_accuracy_of_class(class_to_ignore=0):
    def ignore_acc(y_true, y_pred):
        y_true_class = K.argmax(y_true, axis=-1)
        y_pred_class = K.argmax(y_pred, axis=-1)

        ignore_mask = K.cast(K.not_equal(y_pred_class, class_to_ignore), 'int32')
        matches = K.cast(K.equal(y_true_class, y_pred_class), 'int32') * ignore_mask
        accuracy = K.sum(matches) / K.maximum(K.sum(ignore_mask), 1)
        return accuracy

    return ignore_acc

根据@RKO的响应,这里是TensorFlow 2.0版本

将tensorflow.keras导入为K
def ignore_acc(y_true_类、y_pred_类、class_to_ignore=0):
ignore_mask=K.backend.cast(K.backend.not_equal(y_pred_类,class_to_ignore),'int32')
matches=K.backend.cast(K.backend.equal(y_true_类,y_pred_类),'int32')*忽略掩码
精度=K.backend.sum(匹配项)/K.backend.max(K.backend.sum(忽略掩码),1)
返回精度。numpy()
def ignore_accuracy_of_class(class_to_ignore=0):
    def ignore_acc(y_true, y_pred):
        y_true_class = K.argmax(y_true, axis=-1)
        y_pred_class = K.argmax(y_pred, axis=-1)

        ignore_mask = K.cast(K.not_equal(y_pred_class, class_to_ignore), 'int32')
        matches = K.cast(K.equal(y_true_class, y_pred_class), 'int32') * ignore_mask
        accuracy = K.sum(matches) / K.maximum(K.sum(ignore_mask), 1)
        return accuracy

    return ignore_acc