Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keras: how to predict classes in order?

Tags:

keras

I'm trying to predict image classes in keras (binary classification). The model accuracy is fine, but it seems that ImageDataGenerator shuffles the input images, so I was not able to match the predicted class with the original images.

datagen = ImageDataGenerator(rescale=1./255)

generator = datagen.flow_from_directory(
        pred_data_dir,
        target_size=(img_width, img_height),
        batch_size=32,
        class_mode=None,
        shuffle=False,
        save_to_dir='images/aug'.format(feature))

print  model.predict_generator(generator, nb_input)

For example, if I have a1.jpg, a2.jpg,..., a9.jpg under pred_data_dir, I expect to get an array like

[class for a1.jpg, class for a2.jpg, ... class for a9.jpg] 

from model.predict_generator(), but actually I got something like

[class for a3.jpg, class for a8.jpg, ... class for a2.jpg]

How can I resolve the issue?

like image 592
Yusuke Avatar asked Jun 23 '16 03:06

Yusuke


1 Answers

Look at the source code of flow_from_directory. In my case, I had to rename all images. They were named 1.jpg .. 1000.jpg, but to be in order, they had to be named 0001.jpg .. 1000.jpg. The sorting is important here.

flow_from_directory uses sorted(os.listdir(directory)), thus the sorting is not always intuitive.

like image 154
Magnus Avatar answered Oct 11 '22 22:10

Magnus