如何计算keras的top5准确度?

xxl*_*xxl 10 deep-learning keras

我想在imagenet2012数据集中计算top5,但我不知道如何在keras中进行.拟合函数只能算出前1个精度.

Fra*_*son 24

如果你刚刚在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))
Run Code Online (Sandbox Code Playgroud)

如果您需要精确度指标,可以将其添加到模型"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 - 
...
Run Code Online (Sandbox Code Playgroud)

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])
Run Code Online (Sandbox Code Playgroud)


Jto*_*heR 5

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

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))
Run Code Online (Sandbox Code Playgroud)