opencvmachine-learningdeep-learningconv-neural-networkhandwriting-recognition

model.predict_generator() and model.predict() gives different output label in multicategories classification?


ploting confusion matrix using model.predict_generator() gives good result while predicting individual image using model.predict() gives different output labels.

from sklearn.externals import joblib
loaded_model = joblib.load("CNNmodel.pkl")

from keras.preprocessing.image import ImageDataGenerator
test_datagen = ImageDataGenerator(rescale=1./255)
test_set = test_datagen.flow_from_directory(
        'dataset/Test',
        target_size=(28, 28),
        batch_size=32,shuffle=False,
        color_mode='grayscale',
        class_mode='categorical')
import matplotlib.pyplot as plt
test_set.reset() 
Y_pred = loaded_model.predict_generator(test_set,4930 // 32+1)
y_pred = np.argmax(Y_pred,axis=-1)
s=confusion_matrix(test_set.classes,y_pred)

this gives good confusion matrix result but

test_image=image.load_img('dataset/Test/character_1_ka/017_02.jpg',target_size=(28,28),color_mode='grayscale')
test_image=image.img_to_array(test_image)
test_image=np.expand_dims(test_image,axis=0)
result=loaded_model.predict(test_image)

while predicting for individual image it doesn't predict the result provided by predict_generator. it predicts same output for all images. The individual image prediction gives same output label [43] for different images.


Solution

  • The test_datagen uses rescale=1./255 i.e. it normalizes the data. Basically it multiplies 1/255 to all the images in the test set.

    you haven't applied it to the images when you pass it through predict.

    Try

    test_image  = test_image/255. 
    

    then pass it to predict, it should work fine.