【问题标题】:connect input and output tensors of two different graphs tensorflow连接两个不同图 tensorflow 的输入和输出张量
【发布时间】:2017-03-17 13:26:23
【问题描述】:

我有 2 个 ProtoBuf 文件,我目前通过调用分别加载和转发它们中的每一个 -

out1=session.run(graph1out, feed_dict={graph1inp:inp1})

紧随其后

final=session.run(graph2out, feed_dict={graph2inp:out1})

其中graph1inp和graph1out是graph 1的输入节点和输出节点> 和 graph 2

的类似术语

现在,我想将 graph1out 与 graph2inp 连接起来,这样我只需运行 graph2out 同时用 inp1 喂养 graph1inp。换句话说,以这样一种方式连接 2 个相关图的输入和输出张量,即一次运行足以对两个经过训练的 ProtoBuf 文件进行推理。

【问题讨论】:

    标签: tensorflow protocol-buffers


    【解决方案1】:

    假设您的 Protobuf 文件包含序列化的tf.GraphDef protos,您可以使用tf.import_graph_def() 的input_map 参数连接两个图:

    # Import graph1.
    graph1_def = ...  # tf.GraphDef object
    out1_name = "..."  # name of the graph1out tensor in graph1_def.
    graph1out, = tf.import_graph_def(graph1_def, return_elements=[out_name])
    
    # Import graph2 and connect it to graph1.
    graph2_def = ...  # tf.GraphDef object
    inp2_name = "..."  # name of the graph2inp tensor in graph2_def.
    out2_name = "..."  # name of the graph2out tensor in graph2_def.
    graph2out, = tf.import_graph_def(graph2_def, input_map={inp2_name: graph1out},
                                     return_elements=[out2_name])
    

    【讨论】:

    • 非常感谢,正是我想要的。
    • 太棒了!感谢帮助我!
    • 我得到“input_map 中的‘输出’在图中不存在(input_map 条目:decoder_inputs:0->outputs:0)”——不太清楚为什么。显然,第二张图中不存在“输出”。知道可能出了什么问题吗?
    【解决方案2】:

    接受的答案确实连接了两个图,但它不会恢复集合、全局变量和可训练变量。经过详尽的搜索,我找到了一个更好的解决方案:

    import tensorflow as tf
    from tensorflow.python.framework import meta_graph
    
    with tf.Graph().as_default() as graph1:
        input = tf.placeholder(tf.float32, (None, 20), name='input')
        output = tf.identity(input, name='output')
    
    with tf.Graph().as_default() as graph2:
        input = tf.placeholder(tf.float32, (None, 20), name='input')
        output = tf.identity(input, name='output')
    
    graph = tf.get_default_graph()
    x = tf.placeholder(tf.float32, (None, 20), name='input')
    

    我们使用tf.train.export_meta_graph 导出也CollectionDef 和meta_graph.import_scoped_meta_graph 导入它。这是连接发生的地方,特别是在input_map 参数中。

    meta_graph1 = tf.train.export_meta_graph(graph=graph1)
    meta_graph.import_scoped_meta_graph(meta_graph1, input_map={'input': x}, import_scope='graph1')
    out1 = graph.get_tensor_by_name('graph1/output:0')
    
    meta_graph2 = tf.train.export_meta_graph(graph=graph2)
    meta_graph.import_scoped_meta_graph(meta_graph2, input_map={'input': out1}, import_scope='graph2')
    

    现在图表已连接,并且正在重新映射全局变量。

    print(tf.global_variables())
    

    您还可以直接从文件中导入元图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 2022-01-22
      • 2017-02-06
      • 2019-01-07
      相关资源
      最近更新 更多