<p>TL;DR:如果您可以将这两个计算定义为Python函数,那么您应该这样做。如果不能,则在TensorFlow中有更高级的功能来序列化和导入图,这允许您从不同的源合成图。</p>
<p>在TensorFlow中,一种方法是将不相交的计算构建为单独的<code>tf.Graph</code>对象,然后使用<a href="https://www.tensorflow.org/api_docs/python/tf/Graph#as_graph_def" rel="noreferrer">^{<cd2>}</a>将它们转换为序列化的协议缓冲区:</p>
<pre><code>with tf.Graph().as_default() as g_1:
input = tf.placeholder(tf.float32, name="input")
y = f(input)
# NOTE: using identity to get a known name for the output tensor.
output = tf.identity(y, name="output")
gdef_1 = g_1.as_graph_def()
with tf.Graph().as_default() as g_2: # NOTE: g_2 not g_1
input = tf.placeholder(tf.float32, name="input")
z = g(input)
output = tf.identity(y, name="output")
gdef_2 = g_2.as_graph_def()
</code></pre>
<p>然后您可以使用<a href="https://www.tensorflow.org/api_docs/python/tf/import_graph_def" rel="noreferrer">^{<cd5>}</a>将<code>gdef_1</code>和<code>gdef_2</code>组合成第三个图:</p>
<pre><code>with tf.Graph().as_default() as g_combined:
x = tf.placeholder(tf.float32, name="")
# Import gdef_1, which performs f(x).
# "input:0" and "output:0" are the names of tensors in gdef_1.
y, = tf.import_graph_def(gdef_1, input_map={"input:0": x},
return_elements=["output:0"])
# Import gdef_2, which performs g(y)
z, = tf.import_graph_def(gdef_2, input_map={"input:0": y},
return_elements=["output:0"]
</code></pre>