2

I'm generating a keras model and saving it to a .h5 file, then trying to convert this to a .pb file for use in unity later on.

I've followed some of the instructions here convert tensorflow model to pb tensorflow as well as a few other suggestions which seem to date back to when tensorflow 1.0 was the latest version, but they give similar problems.

The error I'm getting in the code below is when I try to convert variables to constants: It complains that my variables are not in the graph defined by the session. (I'm a noob to tensorflow so I don't exactly know what this means, but I don't think it has to do with my model in particular.)

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
from keras import backend as K

tf.keras.backend.set_learning_phase(0)

pre_model = tf.keras.models.load_model("final_model.h5")

print(pre_model.inputs)
print(pre_model.outputs)

def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):
    """
    Freezes the state of a session into a pruned computation graph.

    Creates a new computation graph where variable nodes are replaced by
    constants taking their current value in the session. The new graph will be
    pruned so subgraphs that are not necessary to compute the requested
    outputs are removed.
    @param session The TensorFlow session to be frozen.
    @param keep_var_names A list of variable names that should not be frozen,
                          or None to freeze all the variables in the graph.
    @param output_names Names of the relevant graph outputs.
    @param clear_devices Remove the device directives from the graph for better portability.
    @return The frozen graph definition.
    """
    from tensorflow.compat.v1.graph_util import convert_variables_to_constants
    graph = session.graph
    with graph.as_default():
        freeze_var_names = list(set(v.op.name for v in tf.compat.v1.global_variables()).difference(keep_var_names or []))
        output_names = output_names or []
        output_names += [v.op.name for v in tf.compat.v1.global_variables()]
        # Graph -> GraphDef ProtoBuf
        input_graph_def = graph.as_graph_def()
        if clear_devices:
            for node in input_graph_def.node:
                node.device = ""
        frozen_graph = convert_variables_to_constants(session, input_graph_def,
                                                      output_names, freeze_var_names)
        return frozen_graph


frozen_graph = freeze_session(tf.compat.v1.keras.backend.get_session(), output_names=[out.op.name for out in pre_model.outputs])

With outputs + error:

[<tf.Tensor 'conv2d_1_input:0' shape=(None, 28, 28, 1) dtype=float32>]
[<tf.Tensor 'dense_2/Identity:0' shape=(None, 10) dtype=float32>]
File "saveGraph.py", line 40, in freeze_session
    output_names, freeze_var_names)
  File "C:\Users\jgoer\AppData\Roaming\Python\Python37\site-packages\tensorflow_core\python\util\deprecation.py", line 324, in new_func
    return func(*args, **kwargs)
  File "C:\Users\jgoer\AppData\Roaming\Python\Python37\site-packages\tensorflow_core\python\framework\graph_util_impl.py", line 277, in convert_variables_to_constants
    inference_graph = extract_sub_graph(input_graph_def, output_node_names)
  File "C:\Users\jgoer\AppData\Roaming\Python\Python37\site-packages\tensorflow_core\python\util\deprecation.py", line 324, in new_func
    return func(*args, **kwargs)
  File "C:\Users\jgoer\AppData\Roaming\Python\Python37\site-packages\tensorflow_core\python\framework\graph_util_impl.py", line 197, in extract_sub_graph    
    _assert_nodes_are_present(name_to_node, dest_nodes)
File "C:\Users\jgoer\AppData\Roaming\Python\Python37\site-packages\tensorflow_core\python\framework\graph_util_impl.py", line 152, in _assert_nodes_are_present
    assert d in name_to_node, "%s is not in graph" % d
AssertionError: dense_2/Identity is not in graph
glipR
  • 23
  • 1
  • 4

1 Answers1

5

Look at TensorFlow's tutorial on saving and loading models. You can use model.save("path"), and if you do not include an extension, the model will be saved in the SavedModel format.

import tensorflow as tf

pre_model = tf.keras.models.load_model("final_model.h5")
pre_model.save("saved_model")
jkr
  • 17,119
  • 2
  • 42
  • 68