Kerem
Kerem

Reputation: 1553

How to use the created CNN model with new data in Keras

I just followed a tutorial that classifies 10k images of cats and dogs with CNN with Keras(Tensorflow backend).

Everything seems OK, I obtained good accuracy on both test and training sets:

....    
    Epoch 24/25
    250/250 [==============================] - 26s 104ms/step - loss: 0.2938 - acc: 0.8745 - val_loss: 0.4235 - val_acc: 0.8270
    Epoch 25/25
    250/250 [==============================] - 25s 99ms/step - loss: 0.2901 - acc: 0.8719 - val_loss: 0.4324 - val_acc: 0.8270

But how do I use this model to predict the class of a new image?

My code that creates and fits the classifier:

# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
import PIL
#these 2 lines are for timer
import cv2
from timeit import default_timer as timer
start = timer()
# Initialising the CNN
classifier = Sequential()
# Step 1 - Convolution
classifier.add(Conv2D(32, (3, 3), activation="relu", input_shape=(64, 64, 3)))
# Step 2 - Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Adding a second convolutional layer
classifier.add(Conv2D(32, (3, 3), activation="relu"))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Step 3 - Flattening
classifier.add(Flatten())
# Step 4 - Full connection
classifier.add(Dense(units=128, activation="relu"))
classifier.add(Dense(units=1, activation="sigmoid"))
# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Part 2 - Fitting the CNN to the images
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255,
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory('dataset/training_set',
                                                 target_size = (64, 64),
                                                 batch_size = 32,
                                                 class_mode = 'binary')
test_set = test_datagen.flow_from_directory('dataset/test_set',
                                            target_size = (64, 64),
                                            batch_size = 32,
                                            class_mode = 'binary')
classifier.fit_generator(training_set,
                         steps_per_epoch = 250,
                         epochs = 25,
                         validation_data = test_set,
                         validation_steps = 63)
# elapsed time
end = timer()
print(end - start)
# end of work message
import os
os.system('say "your program has finished"')

Dataset: here

Upvotes: 2

Views: 1126

Answers (2)

blackHoleDetector
blackHoleDetector

Reputation: 3033

You can also create another ImageDataGenerator() for the data that you'll be predicting on. Note, this data you plan to predict on is technically called the test set, whereas the data that you've called test set is actually the validation set.

In any case, after creating an ImageDataGenerator() for the test set, you can call classifier.predict_generator() in a similar fashion as to where you call classifier.fit_generator(). I show an example of how to do this here.

Upvotes: 1

pietz
pietz

Reputation: 2533

This should work. I like to use skimage, but that's up to you.

import skimage.io as io
import skimage.transform as tr

img = io.imread('img.jpg')         # Reads the image
img = tr.resize(img, (64, 64, 3))  # Resizes the image
img = img[np.newaxis, ...]         # Adds a new dim to simulate a batch
pred = classifier.predict(img)     # Predicts a value between 0 and 1

if pred > 0.5:
    print('Class 1')
else:
    print('Class 2')

Upvotes: 3

Related Questions