gpt4 book ai didi

python - 如何正确地将 tf.Print() 节点附加到我的 tensorflow 图?

转载 作者:太空宇宙 更新时间:2023-11-03 15:13:14 25 4
gpt4 key购买 nike

据我了解,我应该能够通过执行以下操作将打印运算符添加到我的图表中:

a = nn_ops.softmax(s)

a = tf.Print(a, [tf.shape(a)], message="This is shape a: ")

当执行图表时,应该打印a的形状。然而,这个语句不会为我产生任何输出(我正在运行 seq2seq tensorflow 教程,这个 softmax 属于注意力函数,所以它肯定会被执行)。

如果我做这样的事情,我确实会得到输出:

ph = tf.placeholder(tf.float32, [3,4,5,6])

ts = tf.shape(ph)

tp = tf.Print(ts, [ts], message="PRINT=")

sess = tf.Session()

sess.run(tp)

但是,在我的真实示例中,sess.run() 在 seq2seq_model.py 中被调用,如果我尝试在注意函数,tensorflow 提示:

您必须为占位符张量“encoder0”提供一个数据类型为 int32 的值

但此时我无法访问代码中的输入提要。我怎样才能解决这个问题?

最佳答案

如果您只想知道张量形状,通常可以在不运行图形的情况下推断出来。那么你就不需要tf.Print

例如,在第二个代码片段中,您可以使用:

ph = tf.placeholder(tf.float32, [3,4,5,6])
print(ph.get_shape())

如果您想查看取决于输入大小的形状(使用tf.shape),或者您想查看也取决于<的值/strong> 在输入上,如果不提供输入数据则无法完成。

例如,如果您训练模型,其中 xy 分别是您的样本和标签,则在不提供它们的情况下无法计算成本。

如果您有以下代码:

predictions = ...
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y_output, y_train))
cost = tf.Print(cost, [tf.shape(cost)], message='cost:')

尝试在不提供占位符值的情况下对其进行评估是行不通的:

sess.run(cost)
# error, no placeholder provided

但是这将按预期工作:

sess.run(cost, {x: x_train, y: y_train})

关于您的第一个代码片段。为了工作,需要执行 tf.Print 节点来打印消息。我怀疑在您的情况下,在进一步计算期间不会使用打印节点。

例如,以下代码不会产生输出:

import tensorflow as tf

a = tf.Variable([1., 2., 3])
b = tf.Variable([1., 2., 3])

c = tf.add(a, b)

# we create a print node, but it is never used
a = tf.Print(a, [tf.shape(a)], message='a.shape: ')

init = tf.global_variables_initializer()

with tf.Session() as sess:
sess.run(init)
print(sess.run(c))

但是,如果反转行以便在计算期间使用打印节点,您将看到输出:

a = tf.Print(a, [tf.shape(a)], message='a.shape: ')
# now c depends on the tf.Print node
c = tf.add(a, b)

关于python - 如何正确地将 tf.Print() 节点附加到我的 tensorflow 图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44074823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com