【问题标题】:Tensorflow frozen inference graph from .meta .info .data and combining frozen inference graphs来自 .meta .info .data 的 TensorFlow 冻结推理图和组合冻结推理图
【发布时间】:2018-11-09 06:24:25
【问题描述】:

我是 tensorflow 的新手,目前正在努力解决一些问题:

  1. 如何在没有管道配置的情况下从 .meta .data .info 获取冻结的推理图

    我想实时检查预先训练的交通标志检测模型。模型包含 3 个文件 - .meta .data .info,但我找不到信息,如何在没有管道配置的情况下将它们转换为冻结推理图。我发现的所有东西要么已经过时,要么需要管道配置。

    另外,我尝试自己训练模型,但我认为问题在于 .ppa 文件(GTSDB 数据集),因为使用 .png 或 .jpg 一切正常。

  2. 如何组合两个或多个冻结推理图

    我已经在我自己的数据集上成功地训练了模型(检测某些特定对象),但我希望该模型能够与一些预先训练的模型一起使用,例如更快的 rcnn inception 或 ssd mobilenet。我知道我必须加载两个模型,但我不知道如何让它们同时工作,甚至有可能吗?

更新

我在第一个问题上已经完成了一半 - 现在我有 freeze_model.pb,问题出在输出节点名称中,我很困惑,不知道该放什么,所以经过数小时的“调查”,得到了工作代码:

import os, argparse

import tensorflow as tf

# The original freeze_graph function
# from tensorflow.python.tools.freeze_graph import freeze_graph

dir = os.path.dirname(os.path.realpath(__file__))

def freeze_graph(model_dir):
    """Extract the sub graph defined by the output nodes and convert
    all its variables into constant
    Args:
        model_dir: the root folder containing the checkpoint state file
        output_node_names: a string, containing all the output node's names,
                            comma separated
    """
    if not tf.gfile.Exists(model_dir):
        raise AssertionError(
            "Export directory doesn't exists. Please specify an export "
            "directory: %s" % model_dir)

    # if not output_node_names:
    #     print("You need to supply the name of a node to --output_node_names.")
    #     return -1

    # We retrieve our checkpoint fullpath
    checkpoint = tf.train.get_checkpoint_state(model_dir)
    input_checkpoint = checkpoint.model_checkpoint_path

    # We precise the file fullname of our freezed graph
    absolute_model_dir = "/".join(input_checkpoint.split('/')[:-1])
    output_graph = absolute_model_dir + "/frozen_model.pb"
    # We clear devices to allow TensorFlow to control on which device it will load operations
    clear_devices = True

    # We start a session using a temporary fresh Graph
    with tf.Session(graph=tf.Graph()) as sess:

        # We import the meta graph in the current default Graph
        saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=clear_devices)

        # We restore the weights
        saver.restore(sess, input_checkpoint)

        # We use a built-in TF helper to export variables to constants
        output_graph_def = tf.graph_util.convert_variables_to_constants(
            sess, # The session is used to retrieve the weights
            tf.get_default_graph().as_graph_def(), # The graph_def is used to retrieve the nodes
            [n.name for n in tf.get_default_graph().as_graph_def().node] # The output node names are used to select the usefull nodes
        )

        # Finally we serialize and dump the output graph to the filesystem
        with tf.gfile.GFile(output_graph, "wb") as f:
            f.write(output_graph_def.SerializeToString())
        print("%d ops in the final graph." % len(output_graph_def.node))

    return output_graph_def

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--model_dir", type=str, default="", help="Model folder to export")
    # parser.add_argument("--output_node_names", type=str, default="", help="The name of the output nodes, comma separated.")
    args = parser.parse_args()

    freeze_graph(args.model_dir)

我不得不更改几行 - 删除 --output_node_names 并将 output_graph_def 中的 output_node_names 更改为 [n.name for n in tf.get_default_graph().as_graph_def().node] 现在我遇到了新问题 - 我无法将 .pb 转换为 .pbtxt,错误是:

ValueError: Input 0 of node prefix/Variable/Assign was passed float from prefix/Variable:0 incompatible with expected float_ref.

再一次,关于这个问题的信息已经过时了——我发现的所有东西都至少有一年的历史了。我开始认为 freeze_graph 的修复不正确,这就是我遇到新错误的原因。

我非常感谢您对此事的一些建议。

【问题讨论】:

标签: python tensorflow


【解决方案1】:

如果你写

[n.name for n in tf.get_default_graph().as_graph_def().node]

在您的 convert_variables_to_constants 函数中,您将图形具有的每个节点定义为输出节点,这当然不起作用。 (这可能是您的 ValueError 的原因)

您需要找到实际输出节点的名称,最好的方法通常是在 tensorboard 中查看经过训练的模型并分析那里的图形,或者打印出图形的每个节点。通常打印出来的最后一个节点是您的输出节点(如果您将其用作优化器,则忽略名称中包含“渐变”或“亚当”的所有内容)

执行此操作的简单方法(在恢复会话后插入):

gd = sess.graph.as_graph_def()
for node in gd.node:
    print(node.name)

【讨论】:

    猜你喜欢
    • 2019-05-27
    • 2023-01-31
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    • 2022-07-02
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    相关资源
    最近更新 更多