TransWikia.com

How to predict class label from class probability given by predict_generator for testdata?

Data Science Asked by B. Kanani on January 10, 2021

While using Keras’ flow_from_directory method to train my model on a multi-class image classification problem, the predict_generator function gives the class probabilities.

So, my query is how to get the corresponding class-labels for those class probabilities?

3 Answers

You just take the class with the maximum probability. This can be done using numpy argmax function.

Correct answer by David Masip on January 10, 2021

I realize this question was raised some time back but came across this and thought will share what I have done

It is better to use predict_classes function from the keras model rather than predict_generator - I have run into issues while using this with the time it takes to complete. However, the input data to this function will have to be an array which means we will have to use :


yFit=model.predict_classes(data)

#post which use the train generator to map the labels 
#back to actual names of the classes 

label_map = (train_generator.class_indices)
label_map = dict((v,k) for k,v in label_map.items()) #flip k,v
predictions = [label_map[k] for k in yFit]

Answered by vivek on January 10, 2021

Just to simplify things to receive the class label try:

predict_img = '../Directory'

predict_img = image.load_img(predict_paper_1,target_size="your models target size")

Converting to a numpy array

predict_img = image.img_to_array(predict_paper_1)

predict_img = np.expand_dims(predict_img,axis=0) # position from where converted image array is read

yFit=model.predict_classes(predict_img)


#post which use the trained generator to map the labels 
#back to actual names of the classes 

label_map = (train_gen.class_indices)

label_map = dict((v,k) for k,v in label_map.items()) #flip k,v

predictions = [label_map[k] for k in yFit[:,0]] # YFIT[:,0] INSURES THAT THE ARRAY IS READ IN THE RIGHT SHAPE

print(predictions) 

Answered by user102954 on January 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP