# Why is my keras cnn model giving me the same result for every prediction?

I have a simple cat or dog cnn model. My model has an 80% validation accuracy and an 84% training accuracy

import keras
import tensorflow as tf
from keras.models import Sequential
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dense
import numpy as np

classifier = tf.keras.Sequential()

classifier.add(Dense(units = 128, activation = "relu" ))
classifier.add(Dense(units = 1, activation = "sigmoid" ))
classifier.compile(optimizer = "adam", loss = "binary_crossentropy", metrics = ["accuracy"])
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(training_set,
steps_per_epoch=int(8000/32),
epochs=25,
validation_data=test_set,
validation_steps=int(2000/32))
print(training_set.class_indices)
from keras.preprocessing import image
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)


You are applying a preprocessing step to both your train and test images: rescale=1./255. This normalises the values of the image pixels to be in the range of (0,1) instead of (0,255).

However, when you are doing your predictions you are not applying this rescaling to your test image. This translates into testing an image with pixel values 255 higher than your model is expecting, thus always predicting the same (always a 1 I gues...) You should rescale your test samples as well. Just try:

print(classifier.predict(test_image/255))

• Hi, thanks for replying, i tried your solution but i now have the issue of the model not returning binary output May 13 '20 at 0:22
• predicted_class = np.argmax(prediction,axis=1), this will turn the probabilities into binary predictions May 13 '20 at 6:54
• I tried it, the output it returns now is always 0 May 13 '20 at 8:36

In addition to the answer by @TitoOrt I like to point out that it can be useful to make predictions in Keras - when trained using a data generator - also using a generator function. I had some trouble when I worked out a solution in the first place, so I documented the general logic on Stackoverflow. The code also includes proper preprocessing of test images.

• Oh i will check it out, thank you May 13 '20 at 0:52