Reputation: 1899
How can I retrieve the top 5 predictions from model.predict()
in Keras? It only gives only 1 prediction. Is there any way to do so? I don't want it as an evaluation metric. I just need the top 5 predictions.
Upvotes: 7
Views: 5297
Reputation: 41
You can try with the below code.
n = 5
y_preds = self.model.predict(x)
y_preds = np.argsort(y_preds, axis=1)[:,-n:]
Upvotes: 1
Reputation: 503
if labels are the indices of the correct class:
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))
Upvotes: 0
Reputation: 638
if you are trying to get top prediction from a image classification problem, you will receive a one hot code prediction.
class_prob = [0.98,0.50,0.60,0.90,0.87,0.79,0.87]
top_values_index = sorted(range(len(class_prob)), key=lambda i: class_prob[i])[-the_top_values_you_want_to_extract:]
you now have the index for all the five top values.you can now just loop through the index and get the class name.
to extract just the top_values_without_index
top_values= [class_prob[i] for i in np.argsort(class_prob)[-5:]]
Upvotes: 4