Skip to content

Instantly share code, notes, and snippets.

@tonyreina
Last active June 7, 2020 02:06
Show Gist options
  • Save tonyreina/4f96a6272794a179c34cbabe847f6bf6 to your computer and use it in GitHub Desktop.
Save tonyreina/4f96a6272794a179c34cbabe847f6bf6 to your computer and use it in GitHub Desktop.
# !/usr/bin/env python
"""
Copyright (c) 2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the 'License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an 'AS IS' BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
import sys
import argparse
from pathlib import Path
import tensorflow as tf
from tensorflow.python.framework import graph_util
from tensorflow.python.framework import graph_io
import tensorflow.keras.backend as K
def setKerasOptions():
K._LEARNING_PHASE = tf.constant(0)
K.set_learning_phase(False)
K.set_learning_phase(0)
K.set_image_data_format('channels_last')
def getInputParameters():
parser = argparse.ArgumentParser()
parser.add_argument('--input_model', '-m', required=True, type=str, help='Path to Keras model.')
parser.add_argument('--num_outputs', '-no', required=False, type=int, help='Number of outputs. 1 by default.', default=1)
return parser
def export_keras_to_tf(input_model, output_model, num_output):
print('Loading Keras model: ', input_model)
setKerasOptions()
keras_model = tf.keras.models.load_model(input_model, compile=False)
predictions = [None] * num_output
prediction_node_names = [None] * num_output
for i in range(num_output):
prediction_node_names[i] = 'output_node' + str(i)
predictions[i] = tf.identity(keras_model.outputs[i], name=prediction_node_names[i])
sess = K.get_session()
with sess.as_default():
print(' --- Extracting default graph.')
def_graph = sess.graph.as_graph_def()
print(' --- Converting variables to constants.')
constant_graph = tf.compat.v1.graph_util.convert_variables_to_constants(sess, def_graph, prediction_node_names)
print(' --- Removing training nodes.')
infer_graph = tf.compat.v1.graph_util.remove_training_nodes(constant_graph)
graph_io.write_graph(infer_graph, '.', output_model, as_text=True)
def main():
argv = getInputParameters().parse_args()
input_model = argv.input_model
num_output = argv.num_outputs
output_model = str(Path(input_model).name) + '.pb'
prediction_node_names = export_keras_to_tf(input_model, output_model, num_output)
print('Output nodes are:', prediction_node_names)
print('Saved as TF frozen model to: ', output_model)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment