【问题标题】:How to calculate top5 accuracy in keras?如何计算keras中的top5准确率?
【发布时间】:2017-02-19 12:05:25
【问题描述】:

我想计算 imagenet2012 数据集中的 top5,但我不知道如何在 keras 中计算。 fit 函数只能计算 top 1 准确率。

【问题讨论】:

标签: deep-learning keras


【解决方案1】:

如果你只是在 topK 之后,你总是可以直接调用 tensorflow(你没有说你使用的是哪个后端)。

from keras import backend as K
import tensorflow as tf

top_values, top_indices = K.get_session().run(tf.nn.top_k(_pred_test, k=5))

如果您需要准确度指标,可以将其添加到您的模型 'top_k_categorical_accuracy'

model.compile('adam', 'categorical_crossentropy', ['accuracy', 'top_k_categorical_accuracy'])

history = model.fit(X_train, y_train, nb_epoch=3, validation_split=0.2)

Train on 31367 samples, validate on 7842 samples
Epoch 1/3
31367/31367 [==============================] - 6s - loss: 0.0818 - acc: 0.9765 - top_k_categorical_accuracy: 0.9996 - 
...

此指标的默认 k 为 5,但如果您想将其更改为 3,您可以这样设置模型:

top3_acc = functools.partial(keras.metrics.top_k_categorical_accuracy, k=3)

top3_acc.__name__ = 'top3_acc'

model.compile('adam', 'categorical_crossentropy', ['accuracy', top3_acc])

【讨论】:

  • 也许定义自定义指标更具可读性:def top3_acc(labels, logits): return top_k_categorical_accuracy(y_true=labels, y_pred=logits, k=3)
【解决方案2】:

弗兰克威尔逊的答案可能是更官方的答案,但你也可以这样计算。

top1 = 0.0
top5 = 0.0    
class_probs = model.predict(x)
for i, l in enumerate(labels):
    class_prob = class_probs[i]
    top_values = (-class_prob).argsort()[:5]
    if top_values[0] == l:
        top1 += 1.0
    if np.isin(np.array([l]), top_values):
        top5 += 1.0

print("top1 acc", top1/len(labels))
print("top1 acc", top5/len(labels))

【讨论】:

    【解决方案3】:

    您可以使用 tf.keras.metrics.TopKCategoricalAccuracy(k)。默认 k=5。

    文档在这里:https://keras.io/api/metrics/accuracy_metrics/#topkcategoricalaccuracy-class

    这是在 model.compile 中使用它的代码示例。

    import tensorflow as tf
    
    model.compile(optimizer, loss, 
              metrics= [tf.keras.metrics.TopKCategoricalAccuracy(k=5)]
             )
    

    【讨论】:

      猜你喜欢
      • 2018-05-10
      • 2019-08-06
      • 2018-09-27
      • 2018-11-14
      • 2018-07-20
      • 2018-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多