How do I output confidence level in Resnet 50 classification?
I trained Resnet-50 classification network to classify my objects and I use the following code to evaluate the network.
from tensorflow.keras.models import load_model import cv2 import numpy as np import os class_names = ["x", "y", "b","g", "xx", "yy", "bb","gg", "xyz","xzy","yy"] model = load_model('transfer_resnet.h5') model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) imgg = cv2.imread('/path to image/a1.jpg') img = cv2.resize(imgg,(224,224)) img = np.reshape(img,[1,224,224,3]) classes = np.argmax(model.predict(img), axis = -1) print(classes) for i in classes: names = class_names[i] print(names) cv2.imshow("id",imgg) key = cv2.waitKey(0)
The output of the system after processing is only the class of the object without showing any confidence percentage, my question is how do I also show confidence percentage during the test?
model.predict
gives you the confidences for each class. Using np.argmax
on top of this gives you only the class with the highest confidence.
Therefore, just do:
confidences = np.squeeze(model.predict(img))
I’ve added np.squeeze
to remove any singleton dimensions as we’re just looking at a single image, so the batch size is 1. The first dimension therefore will only have a size 1, so I’m putting in np.squeeze
to remove the singleton dimension. Further, you can get the best class for this image as well as the confidence by doing:
class = np.argmax(confidences) name = class_names[class] top_conf = confidences[class]
If you want to go further and show say the top 5 classes in the prediction, you can do a np.argsort
, sort the predictions then find the indices of the corresponding classes and show those confidences. Take note that I’m going to sort by the negative so we get the confidences in descending order so the first index of the sort corresponds to the class with the highest confidence. I’ll also scale the probability by 100 to give you a percentage confidence as you requested:
k = 5 confidences = np.squeeze(model.predict(img)) inds = np.argsort(-confidences) top_k = inds[:k] top_confidences = confidences[inds] for i, (conf, ind) in enumerate(zip(top_confidences, top_k)): print(f'Class #{i + 1} - {class_names[ind]} - Confidence: {100 * conf}%')
You can adapt the code to display how many you’d like. I’ve made this easy for you to play with so if you just want the most confident class only, set k = 1
.