TensorFlow 指标:top-N 准确率

TensorFlow metric: top-N accuracy

我正在使用 add_metric 尝试创建一个自定义指标来计算分类器的前 3 准确度。据我所知:

def custom_metrics(labels, predictions):
   # labels => Tensor("fifo_queue_DequeueUpTo:422", shape=(?,), dtype=int64)
   # predictions => {
   #    'logits': <tf.Tensor 'dnn/logits/BiasAdd:0' shape=(?, 26) dtype=float32>,
   #     'probabilities': <tf.Tensor 'dnn/head/predictions/probabilities:0' shape=(?, 26) dtype=float32>,
   #     'class_ids': <tf.Tensor 'dnn/head/predictions/ExpandDims:0' shape=(?, 1) dtype=int64>,
   #     'classes': <tf.Tensor 'dnn/head/predictions/str_classes:0' shape=(?, 1) dtype=string>
   #  }

查看现有 tf.metrics 的实现,一切都是使用 tf ops 实现的。我怎样才能实现前 3 准确度?

如果您想自己实现它 tf.nn.in_top_k 非常有用 - 它 returns 一个布尔数组,指示目标是否在前 k 个预测中。您只需取结果的平均值:

def custom_metrics(labels, predictions):
    return tf.metrics.mean(tf.nn.in_top_k(predictions=predictions, targets=labels, k=3))

你也可以导入它:

from tf.keras.metrics import top_k_categorical_accuracy