Python 如何打印张量';s值在tf.while\u循环中而不返回它?
我想要的是在tf.while_循环体中打印一个张量值,而不返回张量,但仍然使用计算图。下面我有一些简单的例子来解释我想要成功的原因以及我到目前为止所做的事情 方法1(工程): TF支持在评估模型时通过将TF.print操作引入图形来打印张量的选项,但这需要从主体返回张量:Python 如何打印张量';s值在tf.while\u循环中而不返回它?,python,tensorflow,printing,while-loop,tensor,Python,Tensorflow,Printing,While Loop,Tensor,我想要的是在tf.while_循环体中打印一个张量值,而不返回张量,但仍然使用计算图。下面我有一些简单的例子来解释我想要成功的原因以及我到目前为止所做的事情 方法1(工程): TF支持在评估模型时通过将TF.print操作引入图形来打印张量的选项,但这需要从主体返回张量: import tensorflow as tf import numpy as np x = tf.placeholder(tf.float32, [1]) def body(x): a = tf.constant
import tensorflow as tf
import numpy as np
x = tf.placeholder(tf.float32, [1])
def body(x):
a = tf.constant( np.array([2]) , dtype=tf.float32)
x = a + x
x = tf.Print(x,[x], summarize=100) <= print here (works)
return x
def condition(x):
return tf.reduce_sum(x) < 10
with tf.Session() as sess:
tf.global_variables_initializer().run()
result = tf.while_loop(cond=condition, body=body, loop_vars=[x])
result_out = sess.run([result], feed_dict={ x : np.zeros(1)})
print(result_out)
方法2(工程):
TF支持打印张量的选项,而无需使用渴望模式创建计算图。下例相同:
import tensorflow as tf
import numpy as np
tf.enable_eager_execution()
def body(x):
a = tf.constant(np.array([2]), dtype=tf.int32)
x = a + x
print(x) <= print here (works)
return x
def cond(x):
return tf.reduce_sum(x) < 10 # sum over an axis
x = tf.constant(0, shape=[1])
#result = tf.while_loop(cond=condition, body=body, loop_vars=(x,0))
result=tf.while_loop(cond, body, [x])
print(result)
方法3(失败):
我想要的是在图形环境中使用渴望执行打印张量(如所述:)
当然,在本例中,我从主体返回tensor
x
,但我想在循环内部打印 在第一种方法中,可以打印张量值而不返回它。例如:
x = tf.Print(x, [a])
在这种情况下,识别操作是否会产生副作用,即在评估时打印张量
a
的值。为什么第一种方法不可接受?如果您执行x=tf.Print(x[a],summary=100)
您将打印张量a
的值,而不返回此张量。我认为tf.Print仅用于打印返回的张量。非常感谢,它很有效。你能帮我把它贴出来作为答复吗?
tf.Tensor([2], shape=(1,), dtype=int32)
tf.Tensor([4], shape=(1,), dtype=int32)
tf.Tensor([6], shape=(1,), dtype=int32)
tf.Tensor([8], shape=(1,), dtype=int32)
tf.Tensor([10], shape=(1,), dtype=int32)
tf.Tensor([10], shape=(1,), dtype=int32)
import tensorflow as tf
import numpy as np
tfe = tf.contrib.eager
x = tf.placeholder(tf.int32, [1])
def my_py_func(x):
print(x) # It's eager!
def body(x):
a = tf.constant( np.array([2]) , dtype=tf.int32)
x = a + x
tfe.py_func(my_py_func, x, tf.int32) <= print here (does not work)
return x
def condition(x):
return tf.reduce_sum(x) < 10
with tf.Session() as sess:
tf.global_variables_initializer().run()
result = tf.while_loop(condition, body, [x])
result_out = sess.run([result], feed_dict={ x : np.zeros(1)} )
print(result_out)
TypeError: Expected list for 'input' argument to 'EagerPyFunc' Op, not Tensor("while/add:0", shape=(1,), dtype=int32).
x = tf.Print(x, [a])