6
$\begingroup$

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?

$\endgroup$
0
2
$\begingroup$

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

$\endgroup$
1
  • 2
    $\begingroup$ y_prob = model.predict(x) y_classes = y_prob.argmax(axis=-1) $\endgroup$ – Aditya May 26 '18 at 14:38
1
$\begingroup$

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]

$\endgroup$
0
$\begingroup$

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) 
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.