1
$\begingroup$

I have created Image Generators that I used for training on labeled data. Now I want to make predictions on unlabeled data using the generators. I created a test generator as follows:

test_generator = gen_test.flow_from_directory(
                        test_path,
                        target_size=IMAGE_SIZE,
                        class_mode=None,
                        shuffle=False,
                        batch_size=batch_size)

The outputs I get seem to be one hot encoded like this

array([[0., 0., 1., 0., 0.],
       [0., 0., 0., 0., 1.],
       [0., 0., 0., 0., 1.],
       ...,
       [0., 1., 0., 0., 0.],
       [0., 1., 0., 0., 0.],
       [0., 0., 0., 0., 1.]], dtype=float32)

I would like to know the correct method of getting the actual class labels for each of the images. For instance, the classes in my training image generator is something like this

array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4,
       4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
       4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
       4, 4, 4, 4, 4, 4], dtype=int32)

I am using this for the first time, so I there is probably a simpler way to get this information. Any pointers are much appreciated.

$\endgroup$
1
$\begingroup$

Using argmax with model.predict is the way to go.

# testdata is the dataframe of Generator
paths = testdata.filenames # Your files path

y_pred = model.predict(testdata).argmax(axis=1) # Predict prob and get Class Indices
classes = testdata.class_indices  # Map of Indices to Class name

from keras.preprocessing import image
a_img_rand = np.random.randint(0,len(paths))   # A rand to pick a rand image
img = image.load_img(paths[a_img_rand])       
img = image.img_to_array(img)
from google.colab.patches import cv2_imshow
cv2_imshow(img)
print(f'Class Predicted ---- {list(classes)[y_pred[a_img_rand]]}')

enter image description here

$\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.