Keras: how to get top-k accuracy
Alternatively,
from keras.metrics import top_k_categorical_accuracy
def topKacc(Y_true, Y_pred):
return top_k_categorical_accuracy(Y_true,
Y_pred,
k = int_here)
metrics = [topKacc, ...]
model.compile(...,
metrics=metrics)
Ok here is the code that works for me, in case someone else stumbles upon similar issues - the missing link for me was using ".evaluate":
import functools
top3_acc = functools.partial(keras.metrics.top_k_categorical_accuracy, k=3)
top3_acc.__name__ = 'top3_acc'
model.compile(Adam(lr=.001),#
optimizers.RMSprop(lr=2e-5),
loss='categorical_crossentropy',
metrics=['accuracy','top_k_categorical_accuracy',top3_acc])
model.evaluate(X_test, y_test)
where 'top_k_categorical_accuracy' gives me the score for k=5 (standard) and top3_acc can be adjusted by changing k=3 in the function call.