BBQuercus
BBQuercus

Reputation: 879

Predicting a single image with Keras' ImageDataGenerator

I'm very new to deep learning so please forgive me for this probably simple question.

I trained a network to classify between positive and negative. To simplify the image generation and fitting process I used a ImageDataGenerator and the fit_generator function, as shown below:

import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator

# Simplified model
model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(12, 12, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

# Image import, for 'validation_generator' equally
train_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
    './training/',
    target_size=(12, 12),
    batch_size=128,
    class_mode='binary')

# Compiling
model.compile(loss='binary_crossentropy',
             optimizer='adam',
             metrics=['acc'])

# Fitting, for Tensorboard 'history = model.fit_gen...'
model.fit_generator(train_generator,
                    steps_per_epoch=8,
                    epochs=50,
                    verbose=1,
                    validation_data = validation_generator,
                    validation_steps=8,
                    callbacks=[tb]) # Standard Tensorboard

I want to use my model to predict a single image (imported as numpy array) as shown below:

image = 'single imported image with shape (12, 12, 3)'
model.predict(image)

However, the only thing I get is an error message stating the Matrix size-incompatible. I have tried model.predict_generator() on my validation_generator which works, but that isn't a single image.

Thanks in advance.

Upvotes: 4

Views: 1887

Answers (1)

gorjan
gorjan

Reputation: 5555

If you want to do a prediction on a single image, do the following:

image = np.random.rand(12, 12, 3) # single imported image with shape (12, 12, 3)
image = np.expand_dims(image, axis=0) # image shape is (1, 12, 12, 3)
model.predict(image)

In other words, your model still expects input shape of (None, 12, 12, 3). So, before doing the prediction, expand the dimensions of the image to be a batch of a single image.

Upvotes: 5

Related Questions