Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get class labels from Keras functional model

Tags:

python

keras

I have a functional model in Keras (Resnet50 from repo examples). I trained it with ImageDataGenerator and flow_from_directory data and saved model to .h5 file. When I call model.predict I get an array of class probabilities. But I want to associate them with class labels (in my case - folder names). How can I get them? I found that I could use model.predict_classes and model.predict_proba, but I don't have these functions in Functional model, only in Sequential.

like image 806
Ledzz Avatar asked Aug 16 '16 09:08

Ledzz


2 Answers

y_prob = model.predict(x)  y_classes = y_prob.argmax(axis=-1) 

As suggested here.

like image 139
Emilia Apostolova Avatar answered Oct 21 '22 02:10

Emilia Apostolova


When one uses flow_from_directory the problem is how to interpret the probability outputs. As in, how to map the probability outputs and the class labels as how flow_from_directory creates one-hot vectors is not known in prior.

We can get a dictionary that maps the class labels to the index of the prediction vector that we get as the output when we use

generator= train_datagen.flow_from_directory("train", batch_size=batch_size) label_map = (generator.class_indices) 

The label_map variable is a dictionary like this

{'class_14': 5, 'class_10': 1, 'class_11': 2, 'class_12': 3, 'class_13': 4, 'class_2': 6, 'class_3': 7, 'class_1': 0, 'class_6': 10, 'class_7': 11, 'class_4': 8, 'class_5': 9, 'class_8': 12, 'class_9': 13} 

Then from this the relation can be derived between the probability scores and class names.

Basically, you can create this dictionary by this code.

from glob import glob class_names = glob("*") # Reads all the folders in which images are present class_names = sorted(class_names) # Sorting them name_id_map = dict(zip(class_names, range(len(class_names)))) 

The variable name_id_map in the above code also contains the same dictionary as the one obtained from class_indices function of flow_from_directory.

Hope this helps!

like image 38
Lokesh Kumar Avatar answered Oct 21 '22 01:10

Lokesh Kumar