How to get percentage prediction for each class from TensorFlow?

Solution for How to get percentage prediction for each class from TensorFlow?
is Given Below:

I’m creating a neural network for image classification and i have the following classes:
[class1, class2, class3]

I have a model based on VGG with the last layer of the model being modified as follows:

predictions = layers.Dense(int(len(['class1', 'class2', 'class3'])), activation='softmax')(x)

Then I compile the model as follows:

model.compile(loss="categorical_crossentropy", optimizer=Adam(), metrics=['accuracy'])

Then I predict the class according to the input image:

img = load_img(input_path, target_size=(224, 224))
img = np.asarray(img) / 255.
img = cv2.resize(img, (224, 224))
img = img.reshape(1, 224, 224, 3)

prediction = model.predict(img)

However, it does come back to me as a kind of prediction:

[[5.7733614e-29 2.5203591e-28 3.1751932e-38]]

I would like to understand what this data means and how it can be interpreted as a percentage, so that I can say that class1 is 59%, class2 is 20% and class3 is 21%.

I mean, I’d like the output to be like this:

[[0.59 0.20 0.21]]

Am I doing something wrong, or am I just working with the data incorrectly?

Thank you very much.

Edit: For Imagenet only.

You should use decode_predictions on top of predict to get more human-readable results.

To illustrate, the output may look like after calling predict:

3.60479535e-05 2.34715412e-06 9.06522095e-04 1.34255132e-03

After decode_predictions:

[[('n01944390', 'snail', 0.24689779), ('n01943899', 'conch', 0.2438357), ('n03944341', 'pinwhe ...

Please try the below snippet.

from tensorflow.keras.applications.vgg16 import decode_predictions

prediction = model.predict(img)

# You can use the one below.
# print( 'Predicted:', decode_predictions( prediction, top=5 )[0] )
# or...
results = decode_predictions(prediction)
for result in results[0]:
    print( result[2] ) # prints the accuracy levels of each class