如何打印张量值,Keras / Tensorflow

时间:2018-10-10 07:33:14

标签: python keras keras-rl

我正在尝试从强化学习算法中了解一些代码。为此,我尝试打印张量的值。

我编写了一段简单的代码来说明我的意思。

import tensorflow as tf
from keras import backend as K

x = K.abs(-2.0)
tf.Print(x,[x], 'x')

目标是打印值“ 2”(绝对值-2)。但是我只得到以下信息:

Using TensorFlow backend.

Process finished with exit code 0

没有,我怎么能像print('...')语句那样打印值'2'?

3 个答案:

答案 0 :(得分:2)

如果您使用的是Jupyter Notebook,那么到目前为止,tf.Print()不兼容,并且将按照docs

所述将输出打印到Notebook的服务器输出中。

在tensorflow文档中,张量的描述方式如下:

  

编写TensorFlow程序时,您操纵并传递的主要对象是tf.Tensor。 tf.Tensor对象代表部分定义的计算,最终将产生一个值。

因此,您必须使用tf.Session()对其进行初始化才能获得它们的值。要打印值,请eval()

这是您想要的代码:

import tensorflow as tf
from keras import backend as K

x= K.abs(-2.0)
with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    print(x.eval())

初始化器对于实际初始化x很重要。

答案 1 :(得分:0)

要在TF 2.0及更高版本中打印张量

my_sample = tf.constant([[3,5,2,6], [2,8,3,1], [7,2,8,3]])
  1. 带有session.run()
    with tf.compat.v1.Session() as ses: print(ses.run(my_sample))

  2. 带有eval()的一行
    print(tf.keras.backend.eval(my_sample))

答案 2 :(得分:0)

出于学习目的,有时可以方便地打开急切执行的程序。启用急切执行后,TensorFlow将立即执行操作。然后,您可以简单地使用print或tensorflow.print()来打印出对象的值。

import tensorflow as tf
from keras import backend as K

tf.compat.v1.enable_eager_execution() # enable eager execution

x = K.abs(-2.0)
tf.Print(x,[x], 'x')

有关更多详细信息,请参见此处。 https://www.tensorflow.org/api_docs/python/tf/compat/v1/enable_eager_execution

相关问题