Tensorflow如何评估不依赖于图形内的张量的代码?
如果我们有类似的话:
graph = tf.Graph()
with graph.as_default():
x = tf.constant([[1],[2]])
print("hi1")
y = tf.constant([[1],[1]])
print("hi2")
z = tf.add(x,y)
print("hi3")
with tf.Session(graph=graph) as sess:
z_output = sess.run([z])
如果只评估print()
之类的某个Tensor,我怎样才能确保执行z
语句?现在似乎所有这些都在程序运行后立即执行。
答案 0 :(得分:1)
TensorFlow 不执行图表外的代码(如那些print()
语句);相反,它由Python解释器以正常顺序执行。另一种方法是: TensorFlow仅评估涉及张量的程序位。 print()
语句将在您构建图形时执行,但由于它们不向图形添加任何节点,因此在您实际运行图形时它们不会再次执行(使用tf.Session()
如果我们更详细地看一下你的示例程序正在做什么,这可能是有意义的:
graph = tf.Graph() # Create a new graph to contain a TensorFlow program.
with graph.as_default(): # By default, all created nodes will be added to `graph`.
x = tf.constant([[1],[2]]) # Add a constant node to `graph`.
print("hi1") # Print a message *during graph construction*.
y = tf.constant([[1],[1]]) # Add a constant node to `graph`.
print("hi2") # Print a message *during graph construction*.
z = tf.add(x,y) # Add an addition node to `graph`.
print("hi3") # Print a message *during graph construction*.
with tf.Session(graph=graph) as sess: # Create a session for running `graph`.
z_output = sess.run([z]) # Run the node `z` and all nodes it depends on.
如果您希望TensorFlow运行某段代码,则必须将其添加到图表中。因此,TensorFlow提供了复制公共语言功能的机制,例如tf.Print()
,tf.while_loop()
等。