1. 程式人生 > 其它 >tf調不到keras怎麼 回事_tf.Keras模型轉換為pb檔案

tf調不到keras怎麼 回事_tf.Keras模型轉換為pb檔案

技術標籤:tf調不到keras怎麼 回事

def keras_model_to_frozen_graph():
    """ convert keras h5 model file to frozen graph(.pb file)
    """
    import tensorflow as tf
    from tensorflow.python.framework import graph_io
    from tensorflow.keras.applications.inception_v3 import InceptionV3

    def freeze_graph(graph, session, output_node_names, model_name):
        with graph.as_default():
            graphdef_inf = tf.graph_util.remove_training_nodes(graph.as_graph_def())
            graphdef_frozen = tf.graph_util.convert_variables_to_constants(session, graphdef_inf, output_node_names)
            graph_io.write_graph(graphdef_frozen, "tmp", os.path.basename(model_name) + ".pb", as_text=False)

    tf.keras.backend.set_learning_phase(0) # this line most important
    model = load_net()
    model_name = './models/mymodel.h5'
    model.load_weights(model_name)
    session = tf.keras.backend.get_session()
    freeze_graph(session.graph, session, [out.op.name for out in model.outputs], model_name)