web-dev-qa-db-ja.com

Tensorflow 2.0ケラスモデルを.pbファイルに変換

私はケラスモデルを生成し、それを.h5ファイルに保存してから、後でUnityで使用するためにこれを.pbファイルに変換しようとしています。

私はここでいくつかの指示 convert tensorflow model to pb tensorflow に加えて、テンソルフロー1.0が最新バージョンであったときにさかのぼる他のいくつかの提案に従いましたが、同様の問題が発生します。

以下のコードでエラーが発生するのは、変数を定数に変換しようとしたときです。セッションで定義されたグラフに変数が含まれていないというメッセージが表示されます。 (私はテンソルフローの初心者なので、これが何を意味するのか正確にはわかりませんが、特に私のモデルとは関係がないと思います。)

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])

出力+エラーあり:

[<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
2
glipR

TensorFlowの モデルの保存と読み込みに関するチュートリアル をご覧ください。 model.save("path")を使用できます。拡張を含めない場合、モデルはSavedModel形式で保存されます。

import tensorflow as tf

pre_model = tf.keras.models.load_model("final_model.h5")
pre_model.save("saved_model")
1
jakub