接受的答案确实连接了两个图,但它不会恢复集合、全局变量和可训练变量。经过详尽的搜索,我找到了一个更好的解决方案:
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())
您还可以直接从文件中导入元图。