Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
937 views
in Technique[技术] by (71.8m points)

deep learning - How to calculate top5 accuracy in keras?

I want to calculate top5 in imagenet2012 dataset, but i don't know how to do it in keras. fit function just can calculate top 1 accuracy.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are just after the topK you could always call tensorflow directly (you don't say which backend you are using).

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))

If you want an accuracy metric you can add it to your model '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 - 
...

The default k for this metric is 5 but if you wanted to change that to say 3 you would set up your model like this:

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])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...