Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
by (19k points)

I'm only beginning with keras and machine learning in general.

I trained a model to classify images from 2 classes and saved it using Here is the code I used:

from keras.preprocessing.image import ImageDataGenerator

from keras.models import Sequential

from keras.layers import Conv2D, MaxPooling2D

from keras.layers import Activation, Dropout, Flatten, Dense

from keras import backend as K


# dimensions of our images.

img_width, img_height = 320, 240

train_data_dir = 'data/train'

validation_data_dir = 'data/validation'

nb_train_samples = 200  #total

nb_validation_samples = 10  # total

epochs = 6

batch_size = 10

if K.image_data_format() == 'channels_first':

    input_shape = (3, img_width, img_height)


    input_shape = (img_width, img_height, 3)

model = Sequential()

model.add(Conv2D(32, (3, 3), input_shape=input_shape))


model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))


model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))


model.add(MaxPooling2D(pool_size=(2, 2)))










# this is the augmentation configuration we will use for training

train_datagen = ImageDataGenerator(

    rescale=1. / 255,




# this is the augmentation configuration we will use for testing:

# only rescaling

test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(


    target_size=(img_width, img_height),



validation_generator = test_datagen.flow_from_directory(


    target_size=(img_width, img_height),





    steps_per_epoch=nb_train_samples // batch_size,




It successfully trained with 0.98 accuracy which is pretty good. To load and test this model on new images, I used the below code:

from keras.models import load_model

import cv2

import numpy as np

model = load_model('model.h5')




img = cv2.imread('test.jpg')

img = cv2.resize(img,(320,240))

img = np.reshape(img,[1,320,240,3])

classes = model.predict_classes(img)

print classes

It outputs:


Why wouldn't it give out the actual name of the class and why [[0]]?

Thanks in advance.

1 Answer

0 votes
by (33.1k points)

For your case, if you use Keras predict_classes, that will output a numpy array of class predictions to the index of the neuron of highest activation from your last(softmax) layer. 

Here, [[0]] means that your model predicted that your test data is class 0. If you pass multiple image, and the result would look like [[0], [1], [1], [0]] )

You should convert your actual label (e.g. 'cancer', 'not cancer') into binary encoding (0 for 'cancer', 1 for 'not cancer') for binary classification task. Then you can define your sequence output of [[0]] as having the class label 'cancer'

Hope this answer helps.

Browse Categories