Jennifer95
Jennifer95

Reputation: 13

How to use a saved model in Keras to predict and classify an image?

I trained a model hand position classifier with Keras and I ended up saving the model with the code (model.save('model.h5') ) now i'm traying to predict an image using this model is it doable? if yes could you give me some examples please ? PS:my data is provided as a CSV file

Upvotes: 1

Views: 7199

Answers (3)

Vishnuvardhan Janapati
Vishnuvardhan Janapati

Reputation: 3288

Here I am providing an example of saving a tensorflow.keras model to model_path folder under current directory. This works well with most recent tensorflow (TF2.0.0rc2). I will update this description if there is any change in near future. Follow the example code below and change data loading, shape etc.

Saving and loading entire model

import tensorflow as tf
from tensorflow import keras
mnist = tf.keras.datasets.mnist

#import data
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

# create a model
def create_model():
  model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(512, activation=tf.nn.relu),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10, activation=tf.nn.softmax)
    ])
# compile the model
  model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
  return model

# Create a basic model instance
model=create_model()

model.fit(x_train, y_train, epochs=1)
loss, acc = model.evaluate(x_test, y_test,verbose=1)
print("Original model, accuracy: {:5.2f}%".format(100*acc))

# Save entire model to a HDF5 file
model.save('./model_path/my_model.h5')

# Recreate the exact same model, including weights and optimizer.
new_model = keras.models.load_model('./model_path/my_model.h5')
loss, acc = new_model.evaluate(x_test, y_test)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))

model.save approach saves everything:

  • The weight values
  • The model's architecture
  • The optimizer configuration
  • Training config (what passed to compile)

As model.save saves training config, we don't need to compile the model after restoring using keras.models.load_model

Upvotes: 0

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48437

First of all, you have to import the saved model using load_model function.

from keras.models import load_model
model = load_model('model.h5')

Before you will predict the result for a new given input you have to invoke compile method.

classifier.compile(loss='your_loss', optimizer='your_optimizer', metrics=['your_metrics'])

After compiling, you're done to deal with new images.

from keras.preprocessing import image

test_image= image.load_img(picturePath, target_size = (img_width, img_height)) 
test_image = image.img_to_array(test_image)
test_image = numpy.expand_dims(test_image, axis = 0)
test_image = test_image.reshape(img_width, img_height)
result = model.predict(test_image)   

Upvotes: 4

Jennifer95
Jennifer95

Reputation: 13

when i run the code posting by @Mihai Alexandru-Ionut

# dimensions of our images
img_width, img_height = 313, 220

# load the model we saved
model = load_model('hmodel.h5')
sgd = optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy','mse'])

test_image= image.load_img('/Images/1.jpg',target_size = (img_width, img_height))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = model.predict(test_image)

i get the following error: line 113, in _standardize_input_data 'with shape ' + str(data_shape)) ValueError: Error when checking : expected dense_1_input to have 2 dimensions, but got array with shape (1, 313, 220, 3) could somoeone help me to fix this error

Upvotes: 0

Related Questions