Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Keras Models --> TensorFlow SavedModel format
# Mostly copied from
# Changing it to use InceptionV3 instead of ResNet50
from keras.applications.inception_v3 import InceptionV3, preprocess_input, decode_predictions
from keras.preprocessing import image
import numpy as np
model = InceptionV3()
img_path = 'elephant.jpg'
img = image.load_img(img_path, target_size=(299, 299))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
print('Predicted:', decode_predictions(preds, top=3)[0])
# And now exporting to the TensorFlow SavedModel format.
# Documentation for the SavedModel format can be found here:
from keras import backend as K
import tensorflow as tf
signature = tf.saved_model.signature_def_utils.predict_signature_def(
inputs={'image': model.input}, outputs={'scores': model.output})
builder = tf.saved_model.builder.SavedModelBuilder('/tmp/my_saved_model')
# This model can be loaded in other langauges using the C API:
# TF_SessionOptions* opts = TF_NewSessionOptions();
# const char* tags[] = {"serve"}; // tf.saved_model.tag_constants.SERVING
# TF_LoadSessionFromSavedModel(opts, NULL, "/tmp/my_saved_model", tags, 1, graph, NULL, status);
# This is what is used by the:
# - Java API:
# - Go API:
# etc.

This comment has been minimized.

Copy link

Moeletji17 commented Jun 24, 2019

Thanks for sharing. This helped me save my tensorflow.keras models.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.