Skip to content

Instantly share code, notes, and snippets.

@benman1
Created December 12, 2018 15:21
Show Gist options
  • Save benman1/7bac6efd5bacefee2b3d5578629ff053 to your computer and use it in GitHub Desktop.
Save benman1/7bac6efd5bacefee2b3d5578629ff053 to your computer and use it in GitHub Desktop.
keras model conversion/save; convert keras format (hdf5) into tensorflow SavedModelBuilder (protobuf)
import tensorflow as tf
from tensorflow.python.saved_model import tag_constants
from tensorflow.python.saved_model.signature_def_utils_impl import predict_signature_def
KERAS_HDF5 = 'weights.hdf5'
EXPORT_PATH = '/tmp/tf_model/' # where to save the tensorflow model
model = create_model(params) # build and compile the architecture
model.load_weights(KERAS_HDF5)
# initialize variables, session, graph
sess = tf.keras.backend.get_session()
graph = tf.get_default_graph()
init=tf.global_variables_initializer()
sess.run(init)
with graph.as_default():
temp_export_path = EXPORT_PATH
# Saving
builder = tf.saved_model.builder.SavedModelBuilder(temp_export_path)
signature = predict_signature_def(inputs={'state': model.input},
outputs={t.name: t for t in model.outputs})
builder.add_meta_graph_and_variables(sess, [tag_constants.SERVING],
signature_def_map={
tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature})
builder.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment