TensorFlow指标:top-N准确度

问题描述 投票:2回答:1

我正在使用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个准确度?

python tensorflow metrics top-n
1个回答
2
投票

如果你想自己实现它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
© www.soinside.com 2019 - 2024. All rights reserved.