RedFox
RedFox

Reputation: 1376

How to save TF2 trained model and use it again for inference?

I used the following tutorial program (python3) to train a model to classify images as cat or dog.

https://www.tensorflow.org/tutorials/images/classification

I could run this on my ubuntu computer but I want to save the trained model and try it again to test it with my own images.

Can you please point me to a code snippet to 1. save the trained model and 2. infer image.

Re @PSKP

I was able to save and load the model. Code is below.

import tensorflow as tf

dog = tf.keras.preprocessing.image.load_img(
   "mowgli.JPG", grayscale=False, color_mode='rgb', target_size=None,
    interpolation='nearest'
   )

 print(dog.size)

 model = tf.keras.models.load_model('dog-cat.h5')
 y_hat = model.predict(dog)

 print(y_hat)

But got this error at model.predict...

ValueError: Failed to find data adapter that can handle input: <class 'PIL.JpegImagePlugin.JpegImageFile'>, <class 'NoneType'>

Thank you

Upvotes: 0

Views: 430

Answers (1)

PSKP
PSKP

Reputation: 1375

We have number of ways of doing this. But I am showing you easiest way.

solution

import tensorflow as tf

# Train model

model.fit(...)

# Save Model
model.save("model_name.h5")

# Delete Model
del model

# Load Model
model = tf.keras.models.load_model('model_name.h5')

# Now you can use model for inference
y_hat = model.predict(test_X)

Edit

Solution to ValueError

The problem is your dog variable is not numpy array or tensorflow tensor. Before using it you should convert it into numpy array. And also model.predict(..) does not accept only single image so you should add one extra dimension.

import tensorflow as tf

dog = tf.keras.preprocessing.image.load_img(
   "mowgli.JPG", grayscale=False, color_mode='rgb', target_size=None,
    interpolation='nearest'
   )

# Convert to numpy array
dog = np.asarray(dog)

model = tf.keras.models.load_model('dog-cat.h5')

# Add extrac Dimension (it depends on your model)
# This is because dog has only one image. But predict takes multiple
dog = np.array([dog])

y_hat = model.predict(dog)

print(y_hat)

Find Other Solutions

Here

Upvotes: 2

Related Questions