pythontf.keras

How to get the first two best predicted labels along with their respective probabilities


I want to use model.predict to get the two best labels along with their respective probabilities. I was able to get the top labels with their probabilities, but I am having issues getting the second-best ones. Any help is welcomed. below are the codes to produce the top labels.

# Classes with the highest predicted probability
y_pred = label_encoder.inverse_transform(prediction_prob_matrix.argmax(axis=1))
# Predicted probabilities
y_prob = prediction_prob_matrix.max(axis=1)

Solution

  • You can use numpy.sort:

    sorted_prob = np.sort(prediction_prob_matrix, axis=1)
    y_prob_first = sorted_prob[:, -1]
    y_prob_second = sorted_prob[:, -2]
    

    To get the label, numpy.where might help.