Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 624
xxl Avatar asked Feb 19 '17 12:02

xxl


People also ask

How is accuracy calculated in keras?

Accuracy calculates the percentage of predicted values (yPred) that match with actual values (yTrue). For a record, if the predicted value is equal to the actual value, it is considered accurate. We then calculate Accuracy by dividing the number of accurately predicted records by the total number of records.

How do you get a top 5 accuracy?

Top-5 accuracy means any of our model's top 5 highest probability answers match with the expected answer. It considers a classification correct if any of the five predictions matches the target label. In our case, the top-5 accuracy = 3/5 = 0.6.

What is top1 and top5 accuracy?

Top-1 accuracy is the conventional accuracy, which means that the model answer (the one with the highest probability) must be exactly the expected answer. Top-5 accuracy means that any of your model that gives 5 highest probability answers that must match the expected answer.

What is accuracy and Val accuracy in keras?

Now, coming to the log, 'acc' refers to accuracy of what was trained against. 'val_acc' refers to validation set. Note that val_acc refers to a set of samples that was not shown to the network during training and hence refers to how much your model works in general for cases outside the training set.


3 Answers

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])
like image 124
Frank Wilson Avatar answered Sep 28 '22 00:09

Frank Wilson


Frank Wilson's answer is probably the more official answer, but just you can also calculate it like this.

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))
like image 26
JtotheR Avatar answered Sep 27 '22 22:09

JtotheR


You can use tf.keras.metrics.TopKCategoricalAccuracy(k). By default k=5.

Documentation is here: https://keras.io/api/metrics/accuracy_metrics/#topkcategoricalaccuracy-class.

Here is code example to use it in model.compile.

import tensorflow as tf

model.compile(optimizer, loss, 
          metrics= [tf.keras.metrics.TopKCategoricalAccuracy(k=5)]
         )
like image 35
Ijaz Ahmad Avatar answered Sep 27 '22 22:09

Ijaz Ahmad