tensorflowkerasdeep-learningtensorflow2.0tf.keras

model prediction using CNN


I am building an CNN model using Tensorflow 2.0 but not using transfer learning. How to predict with new images? I want to load it from my directory and need predictions (classification problem).

My code is given below:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,Conv2D,MaxPool2D,Dropout,Flatten
from tensorflow.keras.callbacks import EarlyStopping

model = Sequential()

model.add(Conv2D(filters = 16,kernel_size = (3,3), input_shape = image_shape, activation = 'relu'))
model.add(MaxPool2D(pool_size = (2,2)))

model.add(Conv2D(filters = 32,kernel_size = (3,3), activation = 'relu'))
model.add(MaxPool2D(pool_size = (2,2)))

model.add(Conv2D(filters = 64,kernel_size = (3,3), activation = 'relu'))
model.add(MaxPool2D(pool_size = (2,2)))

model.add(Flatten())

model.add(Dense(128,activation = 'relu'))
#model.add(Dropout(0.5))

model.add(Dense(1,activation = 'sigmoid'))

model.compile(loss = 'binary_crossentropy',optimizer = 'adam',
             metrics = ['accuracy'])

early_stop = EarlyStopping(monitor = 'val_loss',patience = 2)

batch_size = 16

train_image_gen = image_gen.flow_from_directory(train_path,
                                               target_size = image_shape[:2],
                                               color_mode = 'rgb',
                                               batch_size = batch_size,
                                               class_mode = 'binary')

test_image_gen = image_gen.flow_from_directory(test_path,
                                               target_size = image_shape[:2],
                                               color_mode = 'rgb',
                                               batch_size = batch_size,
                                               class_mode = 'binary',
                                              shuffle = False)

class myCallback(tf.keras.callbacks.Callback):
    def on_epoch_end(self, epoch, logs={}):
        if(logs.get('accuracy')>0.97):
            print("\nReached 97% accuracy so cancelling training!")
            self.model.stop_training = True

callbacks = myCallback()
results = model.fit_generator(train_image_gen,epochs = 85,
                             validation_data = test_image_gen,
                             callbacks = [callbacks])

# Let's now save our model to a file
model.save('cell_image_classifier.h5')

# Load the model
model = tf.keras.models.load_model('cell_image_classifier.h5')

model.evaluate_generator(test_image_gen)

#Prediction on image
pred = model.predict_generator(test_image_gen)

predictions = pred > .5

print(classification_report(test_image_gen.classes,predictions))
confusion_matrix(test_image_gen.classes,predictions)

Now externally I want to load the image and get prediction.


Solution

  • This will do!

    import numpy as np
    from keras.preprocessing import image
    
    # predicting images
    fn = 'cat-2083492_640.jpg'  # name of the image
    path='/content/' + fn     # path to the image
    img=image.load_img(path, target_size=(150, 150)) # edit the target_size
    
    x=image.img_to_array(img)
    x=np.expand_dims(x, axis=0)
    images = np.vstack([x])
    
    classes = model.predict(images, batch_size=16) # edit the batch_size
    
    print(classes)