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 model.save()
. 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) else: input_shape = (img_width, img_height, 3) model = Sequential() model.add(Conv2D(32, (3, 3), input_shape=input_shape)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(32, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(64)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(1)) model.add(Activation('sigmoid')) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # this is the augmentation configuration we will use for training train_datagen = ImageDataGenerator( rescale=1. / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) # 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( train_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='binary') validation_generator = test_datagen.flow_from_directory( validation_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='binary') model.fit_generator( train_generator, steps_per_epoch=nb_train_samples // batch_size, epochs=epochs, validation_data=validation_generator, validation_steps=5) model.save('model.h5')
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') model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) 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:
[[0]]
Why wouldn't it give out the actual name of the class and why [[0]]
?
Thanks in advance.
h5 file into memory. This sets up the entire neural network in memory along with the weights assigned to each layer. Now, to do your predictions on unseen data, load the data, let it be one or more items, into the memory.
To give inputs to a machine learning model, you have to create a NumPy array, where you have to input the values of the features you used to train your machine learning model. Then we can use that array in the model. predict() method, and at the end, it will give the predicted value as an output based on the inputs.
If someone is still struggling to make predictions on images, here is the optimized code to load the saved model and make predictions:
# Modify 'test1.jpg' and 'test2.jpg' to the images you want to predict on from keras.models import load_model from keras.preprocessing import image import numpy as np # dimensions of our images img_width, img_height = 320, 240 # load the model we saved model = load_model('model.h5') model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # predicting images img = image.load_img('test1.jpg', target_size=(img_width, img_height)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) images = np.vstack([x]) classes = model.predict_classes(images, batch_size=10) print classes # predicting multiple images at once img = image.load_img('test2.jpg', target_size=(img_width, img_height)) y = image.img_to_array(img) y = np.expand_dims(y, axis=0) # pass the list of multiple images np.vstack() images = np.vstack([x, y]) classes = model.predict_classes(images, batch_size=10) # print the classes, the images belong to print classes print classes[0] print classes[0][0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With