python - 来自 .meta .info .data 的 Tensorflow 卡住推理图和组合卡住推理图

标签 python tensorflow

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

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

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

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

  2. 如何合并两个或多个卡住推理图

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

更新

我在第一个问题上已经完成了一半 - 现在我有 frozen_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.

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

我真的很感激在这件事上的一些建议。

最佳答案

如果你写

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

在您的 convert_variables_to_constants 函数中,您将图中的每个节点都定义为输出节点,这当然行不通。 (这可能是您的 ValueError 的原因)

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

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

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

关于python - 来自 .meta .info .data 的 Tensorflow 卡住推理图和组合卡住推理图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50603972/

相关文章:

python - 在 for 循环中将多个按钮连接到同一函数

python - 如何设置 keras 自定义指标仅在纪元结束时调用?

python - 在 tensorflow 中嵌套控制依赖上下文

python - Keras 中拟合生成器输出的精度与手动计算的精度不同

python - 分割层输出时,Keras 抛出 `' Tensor' object has no attribute '_keras_shape'`

python - 在 Django 模板中按键访问字典

python - psycopg2.InterfaceError : connection already closed/pgr_astar

python - 按字长过滤句子

python - 从管道读取 STDIN 时获取用户输入?

python - Tensorflow混合两个多元分布