我正在探索 tensorflow 。 我有以下问题,我将在一个小代码片段中说明。 我不是在寻找最好的方法,我只是在探索所有选项
import tensorflow as tf
g = tf.Graph()
with g.as_default():
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b, name='c')
c_operation = g.get_operations()[2] # getting an tf.Operation object
# c_operation = g.get_operation_by_name('c') is another way to get
# testing input control dependencies , works fine
c_operation.control_inputs.append(g.get_operation_by_name('a'))
c_operation.control_inputs.append(g.get_operation_by_name('b'))
print(c_operation.control_inputs)
# now I am controlling the order of execution
# creating a session that uses graph g
sess = tf.Session(graph=g)
# v = sess.run(c) # this works
v = c_operation.run(session=sess) # but this returns None
所以我的问题是,tf.Operation.run 的目的是什么以及我应该如何使用它。我的代码有什么问题吗? c_operation.run 不应该返回结果操作的值。
关联的张量(此处为 c)是否保存这些值?我没有找到提取它们的方法(除了使用 sess.run(c)
最佳答案
在您的示例代码中,c
是 tf.Tensor
而c_operation
是tf.Operation
。 tf.Operation 表示生成 0 个或多个 tf.Tensor 的计算。
在 tf.Operation
上调用 run
会执行图中为此操作生成输入所需的所有操作,但不会返回任何内容 ( documentation )。在 tf.Tensor
上调用 eval
会执行生成它并返回其值 ( documentation ) 的操作。一般来说,如果您对该值感兴趣,您需要在 tf.Tensor
上调用 eval
。
例如:
# The following two lines are equivalent
v = sess.run(c)
v = c.eval(session=sess)
# The following two lines are equivalent, and neither returns a value
sess.run(c_operation)
c_operation.run(session=sess)
关于tensorflow tf.Operation run方法使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42487908/