5

我试图从强化学习算法中理解一些代码。为了做到这一点,我试图打印张量的值。

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

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' 呢?

4

3 回答 3

5

如果您使用的是 Jupyter Notebook,那么tf.Print()到目前为止不兼容,并且会将输出打印到 Notebook 的服务器输出,如文档中所述

在 tensorflow 文档中,以下是 Tensor 的描述方式:

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

因此,您必须用 a 初始化它们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 很重要。

于 2018-10-10T08:09:45.330 回答
1

在 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))

于 2020-03-18T12:07:15.127 回答
0

出于学习目的,有时打开 Eager Execution 会很方便。启用急切执行后,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

于 2020-04-09T15:04:35.003 回答