首页 > 解决方案 > TensorFlow 指标:top-N 准确率

问题描述

我正在使用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 名的准确性?

标签: pythontensorflowmetricstop-n

解决方案


如果您想自己实现它tf.nn.in_top_k非常有用 - 它返回一个布尔数组,指示目标是否在前 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

推荐阅读