如何在 Keras 中对批量维度应用 top_k_categorical_accuracy
How to apply top_k_categorical_accuracy over batch dimension in Keras
我正在基于 top_k_categorical_accuracy
在 keras 中制作自定义指标。在我的自定义度量函数中,我收到 y_true 和 pred(两个张量),具有 3 个维度,形状为 (batch_size, d2, d3),但显然top_k_categorical_accuracy
需要一个二维张量。
tf.keras.metrics.top_k_categorical_accuracy(y_true, y_pred, k=2)
我的问题是如何在不同批次之间应用这个 top_k 函数?
在下面的示例中,我希望指标的输出为 1/2(k=2)。
这将通过取 top_k_categorical_accuracy(y_true[0], y_pred[0])
的 K.mean
(第一批给出 2/3)和 top_k_categorical_accuracy(y_true[1], y_pred[1])
(第二批给出 1/3)。所以平均值是 1/2
y_true = [
[[0, 0, 1], [0, 1, 0], [1, 0, 0]],
[[0, 0, 1], [0, 1, 0], [1, 0, 0]]
]
y_pred = [
[[0.1, 0.7, 0.2], [0.05, 0.95, 0], [0.2,0.3,0.5]],
[[0.7, 0.2, 0.1], [0.95, 0, 0.05], [0.3,0.2,0.5]]
]
由于只有最后一个维度是实际 class 预测,您可以使用 K.reshape:
将前两个维度重塑为一个维度
y_true = K.reshape(y_true, shape=(-1,3))
y_pred = K.reshape(y_pred, shape=(-1,3))
然后张量将满足 API 的形状要求并产生批次*d1 的平均得分,这也是您要求的批次平均得分,因为每个批次具有相同数量的 d1。
我正在基于 top_k_categorical_accuracy
在 keras 中制作自定义指标。在我的自定义度量函数中,我收到 y_true 和 pred(两个张量),具有 3 个维度,形状为 (batch_size, d2, d3),但显然top_k_categorical_accuracy
需要一个二维张量。
tf.keras.metrics.top_k_categorical_accuracy(y_true, y_pred, k=2)
我的问题是如何在不同批次之间应用这个 top_k 函数?
在下面的示例中,我希望指标的输出为 1/2(k=2)。
这将通过取 top_k_categorical_accuracy(y_true[0], y_pred[0])
的 K.mean
(第一批给出 2/3)和 top_k_categorical_accuracy(y_true[1], y_pred[1])
(第二批给出 1/3)。所以平均值是 1/2
y_true = [
[[0, 0, 1], [0, 1, 0], [1, 0, 0]],
[[0, 0, 1], [0, 1, 0], [1, 0, 0]]
]
y_pred = [
[[0.1, 0.7, 0.2], [0.05, 0.95, 0], [0.2,0.3,0.5]],
[[0.7, 0.2, 0.1], [0.95, 0, 0.05], [0.3,0.2,0.5]]
]
由于只有最后一个维度是实际 class 预测,您可以使用 K.reshape:
将前两个维度重塑为一个维度y_true = K.reshape(y_true, shape=(-1,3))
y_pred = K.reshape(y_pred, shape=(-1,3))
然后张量将满足 API 的形状要求并产生批次*d1 的平均得分,这也是您要求的批次平均得分,因为每个批次具有相同数量的 d1。