tensorflow tf.Operation run方法使用

标签 tensorflow

我正在探索 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)

最佳答案

在您的示例代码中,ctf.Tensorc_operationtf.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/

相关文章:

docker - 访问在 nvidia-docker 容器中运行的 jupyter notebook 所需的登录密码

javascript - 无法通过在tensorflow.js中加载预训练模型(loadLayersModel)进行预测

python - 层序的输入 0 与预期的 ndim=3 层不兼容,发现 ndim=2。收到完整形状 : [None, 1]

python - 更改 tensorflow 对象检测中的优化器

python - 为什么 moving_mean 和 moving_variance 不在 tf.trainable_variables() 中?

python - Tensorflow 中的扩张卷积

python - Tensorflow Estimator API 在评估模式下保存图像摘要

tensorflow - 使用队列时张量板图的含义是什么?

python - 使用tensorflow.contrib.framework.python.ops.audio_ops.audio_spectrogram生成频谱图

python - 从 TF.record 数组中的行中选择随机值,该值可以是多少?