如何将 keras categorical_accuracy 与多维输出一起使用?

How can I use keras categorical_accuracy with a multi-dimentional output?

我正在尝试使用 categorical_accuracy 指标评估我的 keras 神经网络。但是,这仅适用于 1d 列表,因此如果我将其作为目标:

[[[0, 1, 0], [0, 0, 0]], ...]

这是我的输出:

[[[0.1, 0.8, 0.2], [0.3, 0.4, 0.2]], ...]

它会 return 该项目的准确度为 0.5,因为它会将两个列表中的每一个列表放在一起进行比较。但是,我想比较整个输出(3d 输出)的最大参数,因此希望上面的示例 return 精度为 1.

我试过这个:

class Accuracy(keras.metrics.CategoricalAccuracy):
    def __init__(self):
        super().__init__()

    def call(self, inputs, **kwargs):
        super().call((tf.reshape(inputs[0], (output_size,)), tf.reshape(inputs[1], (output_size,))), **kwargs)

但它似乎仍然 return 相同的值。有没有其他方法可以在不求助于创建我自己的指标的情况下调整固有的 keras 函数,这可能 运行 慢得多?

更新: 我创建了一个函数来解决这个问题:

def cat_acc(y_true, y_pred):
    return tf.keras.metrics.categorical_accuracy(tf.keras.backend.flatten(y_true),
                                                 tf.keras.backend.flatten(y_pred))

然而,这有一个问题,它会一次计算整个批次,所以它会 return 1 或 0,其中 1 表示整个批次中的最大值正确,而 0当它不是。我找不到一种明智的方法来循环批处理,而不会在我的模型创建时在 keras 编译它时抛出值错误。

我最终想出了以下解决方案:

def cat_acc(y_true, y_pred):
    return tf.reduce_mean(tf.keras.metrics.categorical_accuracy(tf.reshape(y_true, (-1, output_size)),
                                                                tf.reshape(y_pred, (-1, output_size))))

此处,output_size 指的是模型输出的大小,例如对于输出形状为 (3, 2, 2) 的模型,output_size 变量将为 12 .