如何计算 tf.metrics 多标签分类的准确率?

How to calculate the accuracy for multilabel classification with tf.metrics?

我想用张量流训练多标签分类模型 (tf.estimator.Estimator)。我需要在评估时输出准确度。但它似乎不适用于以下代码:

accuracy = tf.metrics.accuracy(labels=labels, predictions=preds)
metrics = {'accuracy': accuracy}

if mode == tf.estimator.ModeKeys.EVAL:
    return tf.estimator.EstimatorSpec(mode, loss=loss, eval_metric_ops=metrics)

tf.metrics.accuracy 不适用于 multihot 结果。那么什么是多标签指标?

实际上tf.metrics.accuracy也计算多标签分类的准确率。请参阅以下示例:

import tensorflow as tf

labels = tf.constant([[1, 0, 0, 1],
                      [0, 1, 1, 1],
                      [1, 1, 0, 0],
                      [0, 0, 0, 1],
                      [1, 1, 0, 0]])

preds = tf.constant([[1, 0, 1, 1],
                     [0, 1, 1, 1],
                     [1, 1, 0, 0],
                     [0, 0, 0, 1],
                     [1, 1, 0, 0]])

acc, acc_op = tf.metrics.accuracy(labels, preds)

with tf.Session() as sess:
    sess.run(tf.local_variables_initializer())
    sess.run(tf.global_variables_initializer())
    print(sess.run([acc, acc_op]))
    print(sess.run([acc]))

如您所见,我们总共有 20 个标签,第一行中只有一个条目被错误标记,因此我们的准确率为 0.95%。