如何在 TensorFlow 中打印 Tensor 对象的值?
- 2024-12-25 08:51:00
- admin 原创
- 150
问题描述:
我一直在使用 TensorFlow 中矩阵乘法的入门示例。
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
当我打印产品时,它将其显示为一个Tensor
对象:
<tensorflow.python.framework.ops.Tensor object at 0x10470fcd0>
但是我怎么知道的价值product
?
以下没有帮助:
print product
Tensor("MatMul:0", shape=TensorShape([Dimension(1), Dimension(1)]), dtype=float32)
我知道图表在 上运行Sessions
,但是有什么方法可以Tensor
在不运行图表的情况下检查对象的输出吗session
?
解决方案 1:
评估对象实际值的最简单[A]Tensor
方法是将其传递给Session.run()
方法,或者Tensor.eval()
在您有默认会话时调用(即在with tf.Session():
块中,或参见下文)。一般来说[B],如果不在会话中运行某些代码,则无法打印张量的值。
如果您正在试验编程模型,并且想要一种简单的方法来评估张量,tf.InteractiveSession
您可以在程序开始时打开一个会话,然后将该会话用于所有Tensor.eval()
(和Operation.run()
) 调用。当到处传递对象很繁琐时,这在交互式设置(如 shell 或 IPython 笔记本)中会更容易。Session
例如,以下内容在 Jupyter 笔记本中有效:
with tf.Session() as sess: print(product.eval())
对于如此小的表达式来说,这可能看起来很傻,但 Tensorflow 1.x 中的一个关键思想是延迟执行:构建一个大而复杂的表达式非常便宜,并且当您想要评估它时,后端(您连接到的)Session
能够更有效地安排它的执行(例如并行执行独立部分并使用 GPU)。
[答]:要打印张量的值而不将其返回到 Python 程序,可以使用tf.print()
运算符,正如Andrzej 在另一个答案中所建议的那样。根据官方文档:
为了确保操作符运行,用户需要将生成的操作符传递给 的
tf.compat.v1.Session
运行方法,或者通过 指定将操作符作为执行操作的控制依赖项tf.compat.v1.control_dependencies([print_op]
),并将其打印到标准输出。
另请注意:
在 Jupyter 笔记本和 colab 中,
tf.print
打印到笔记本单元输出。它不会写入笔记本内核的控制台日志。
[B]:如果给定张量的值可以有效计算,您可能能够使用该tf.get_static_value()
函数来获取给定张量的常数值。
解决方案 2:
虽然其他答案是正确的,即在评估图表之前无法打印该值,但它们并没有讨论在评估图表后实际打印图表内部值的一种简单方法。
无论何时评估图形(使用run
或eval
),查看张量的值的最简单方法是使用Print
如本例所示的操作:
# Initialize session
import tensorflow as tf
sess = tf.InteractiveSession()
# Some tensor we want to print the value of
a = tf.constant([1.0, 3.0])
# Add print operation
a = tf.Print(a, [a], message="This is a: ")
# Add more elements of the graph using a
b = tf.add(a, a)
现在,每当我们评估整个图时,例如使用b.eval()
,我们得到:
I tensorflow/core/kernels/logging_ops.cc:79] This is a: [1 3]
解决方案 3:
重申其他人所说的话,不运行图表就不可能检查值。
对于那些想要简单示例来打印值的人来说,下面是一个简单的代码片段。该代码无需任何修改即可在 ipython 笔记本中执行
import tensorflow as tf
#define a variable to hold normal random values
normal_rv = tf.Variable( tf.truncated_normal([2,3],stddev = 0.1))
#initialize the variable
init_op = tf.initialize_all_variables()
#run the graph
with tf.Session() as sess:
sess.run(init_op) #execute init_op
#print the random values that we sample
print (sess.run(normal_rv))
输出:
[[-0.16702934 0.07173464 -0.04512421]
[-0.02265321 0.06509651 -0.01419079]]
解决方案 4:
在Tensorflow 1.x
import tensorflow as tf
tf.enable_eager_execution()
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
#print the product
print(product) # tf.Tensor([[12.]], shape=(1, 1), dtype=float32)
print(product.numpy()) # [[12.]]
在 Tensorflow 2.x 中,默认启用 Eager 模式。因此以下代码适用于 TF2.0。
import tensorflow as tf
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
#print the product
print(product) # tf.Tensor([[12.]], shape=(1, 1), dtype=float32)
print(product.numpy()) # [[12.]]
解决方案 5:
不,如果不运行图形(执行session.run()
),您将无法看到张量的内容。您唯一能看到的是:
张量的维数(但我认为对于TF 的操作列表来说,计算它并不难)
用于生成张量的操作类型(
transpose_1:0
,random_uniform:0
)张量中元素的类型 (
float32
)
我没有在文档中找到这一点,但我相信变量(以及一些常量)的值不是在分配时计算的。
看一下这个例子:
import tensorflow as tf
from datetime import datetime
dim = 7000
0:00:00.003261
第一个例子,我只是启动一个随机数的常数张量,无论 dim ( )如何,运行时间大致相同
startTime = datetime.now()
m1 = tf.truncated_normal([dim, dim], mean=0.0, stddev=0.02, dtype=tf.float32, seed=1)
print datetime.now() - startTime
在第二种情况下,常数实际上被评估并且值被分配,时间显然取决于 dim ( 0:00:01.244642
)
startTime = datetime.now()
m1 = tf.truncated_normal([dim, dim], mean=0.0, stddev=0.02, dtype=tf.float32, seed=1)
sess = tf.Session()
sess.run(m1)
print datetime.now() - startTime
您可以通过计算某些东西来使其更加清晰(d = tf.matrix_determinant(m1)
记住时间会流逝O(dim^2.8)
)
PS:我发现文档中对此进行了解释:
Tensor 对象是操作结果的符号句柄,但实际上并不保存操作输出的值。
解决方案 6:
tf.keras.backend.eval
对于评估小表达式很有用。
tf.keras.backend.eval(op)
兼容 TF 1.x 和 TF 2.0。
最小可验证示例
from tensorflow.keras.backend import eval
m1 = tf.constant([[3., 3.]])
m2 = tf.constant([[2.],[2.]])
eval(tf.matmul(m1, m2))
# array([[12.]], dtype=float32)
这很有用,因为您不必明确创建Session
或InteractiveSession
。
解决方案 7:
我认为你需要掌握一些基础知识。通过上面的示例,你已经创建了张量(多维数组)。但要使张量流真正发挥作用,你必须启动一个“会话”并在会话中运行你的“操作”。请注意“会话”和“操作”这两个词。你需要知道 4 件事才能使用张量流:
张量
运营
会议
图表
现在,根据您写出的内容,您已经给出了张量和操作,但您没有运行会话,也没有图形。张量(图形的边缘)流经图形并由操作(图形的节点)操纵。有默认图形,但您可以在会话中启动自己的图形。
当您说 print 时,您只能访问您定义的变量或常量的形状。
这样你就可以看到你缺少了什么:
with tf.Session() as sess:
print(sess.run(product))
print (product.eval())
希望有帮助!
解决方案 8:
在 Tensorflow 2.0+(或在 Eager 模式环境中)中,您可以调用.numpy()
方法:
import tensorflow as tf
matrix1 = tf.constant([[3., 3.0]])
matrix2 = tf.constant([[2.0],[2.0]])
product = tf.matmul(matrix1, matrix2)
print(product.numpy())
解决方案 9:
根据以上答案,您可以使用特定的代码片段像这样打印产品:
import tensorflow as tf
#Initialize the session
sess = tf.InteractiveSession()
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
#print the product
print(product.eval())
#close the session to release resources
sess.close()
解决方案 10:
我不确定我是否遗漏了这里,但我认为最简单和最好的方法是使用tf.keras.backend.get_value
API。
print(product)
>>tf.Tensor([[12.]], shape=(1, 1), dtype=float32)
print(tf.keras.backend.get_value(product))
>>[[12.]]
解决方案 11:
通过启用Eager Execution,您可以在不运行会话中的图形的情况下检查 TensorObject 的输出。
只需添加以下两行代码:
`import tensorflow.contrib.eager as tfe
tfe.enable_eager_execution()`
就在你之后import tensorflow
。
print product
示例中
的输出现在将是:tf.Tensor([[ 12.]], shape=(1, 1), dtype=float32)
请注意,从现在起(2017 年 11 月),您必须安装 Tensorflow 夜间版本才能启用 Eager Execution。预构建的 wheel 可在此处找到。
解决方案 12:
您可以使用 Keras,一行答案就是使用eval
如下方法:
import keras.backend as K
print(K.eval(your_tensor))
解决方案 13:
请注意,这tf.Print()
将更改张量名称。如果您要打印的张量是占位符,则向其提供数据将失败,因为在提供过程中找不到原始名称。例如:
import tensorflow as tf
tens = tf.placeholder(tf.float32,[None,2],name="placeholder")
print(eval("tens"))
tens = tf.Print(tens,[tens, tf.shape(tens)],summarize=10,message="tens:")
print(eval("tens"))
res = tens + tens
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(res))
输出为:
python test.py
Tensor("placeholder:0", shape=(?, 2), dtype=float32)
Tensor("Print:0", shape=(?, 2), dtype=float32)
Traceback (most recent call last):
[...]
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'placeholder' with dtype float
解决方案 14:
您应该将 TensorFlow Core 程序视为由两个独立的部分组成:
构建计算图。
运行计算图。
因此对于下面的代码,您只需构建计算图。
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
您还需要初始化 TensorFlow 程序中的所有变量,您必须明确调用特殊操作,如下所示:
init = tf.global_variables_initializer()
现在您已构建了图并初始化了所有变量,下一步是评估节点,您必须在会话中运行计算图。会话封装了 TensorFlow 运行时的控制和状态。
以下代码创建一个 Session 对象,然后调用其 run 方法来运行足够的计算图来进行评估product
:
sess = tf.Session()
// run variables initializer
sess.run(init)
print(sess.run([product]))
解决方案 15:
试试这个简单的代码!(它是不言自明的)
import tensorflow as tf
sess = tf.InteractiveSession() # see the answers above :)
x = [[1.,2.,1.],[1.,1.,1.]] # a 2D matrix as input to softmax
y = tf.nn.softmax(x) # this is the softmax function
# you can have anything you like here
u = y.eval()
print(u)
解决方案 16:
在 Tensorflow V2 中,使用以下方法打印张量的值:tf.keras.backend.print_tensor(x, message='')
解决方案 17:
在我执行此操作之前,即使阅读了所有答案,我也很难理解需要什么。TensofFlow 对我来说也是新的。
def printtest():
x = tf.constant([1.0, 3.0])
x = tf.Print(x,[x],message="Test")
init = (tf.global_variables_initializer(), tf.local_variables_initializer())
b = tf.add(x, x)
with tf.Session() as sess:
sess.run(init)
print(sess.run(b))
sess.close()
但您可能仍然需要执行会话返回的值。
def printtest():
x = tf.constant([100.0])
x = tf.Print(x,[x],message="Test")
init = (tf.global_variables_initializer(), tf.local_variables_initializer())
b = tf.add(x, x)
with tf.Session() as sess:
sess.run(init)
c = sess.run(b)
print(c)
sess.close()
解决方案 18:
您可以按如下方式在会话中打印出张量值:
import tensorflow as tf
a = tf.constant([1, 1.5, 2.5], dtype=tf.float32)
b = tf.constant([1, -2, 3], dtype=tf.float32)
c = a * b
with tf.Session() as sess:
result = c.eval()
print(result)
解决方案 19:
基本上,在 TensorFlow 中,当您创建任何类型的张量时,它们都会被创建并存储在其中,只有在运行 TensorFlow 会话时才能访问。假设您创建了一个常量张量,
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
而无需运行会话,您可以获得
op
:操作。计算此张量的操作。value_index
:一个 int。生成此张量的操作端点的索引。dtype
:DType。存储在此张量中的元素类型。
要获取这些值,您可以使用所需的张量运行一个会话,如下所示:
with tf.Session() as sess:
print(sess.run(c))
sess.close()
输出将会像这样:
数组([[1.,2.,3.],[4.,5.,6.]],dtype = float32)
解决方案 20:
启用 tensorflow 1.10 版本后引入的 Eager Execution,使用起来非常方便。
# Initialize session
import tensorflow as tf
tf.enable_eager_execution()
# Some tensor we want to print the value of
a = tf.constant([1.0, 3.0])
print(a)
解决方案 21:
使用https://www.tensorflow.org/api_docs/python/tf/print中提供的提示,我使用该log_d
函数打印格式化的字符串。
import tensorflow as tf
def log_d(fmt, *args):
op = tf.py_func(func=lambda fmt_, *args_: print(fmt%(*args_,)),
inp=[fmt]+[*args], Tout=[])
return tf.control_dependencies([op])
# actual code starts now...
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
with log_d('MAT1: %s, MAT2: %s', matrix1, matrix2): # this will print the log line
product = tf.matmul(matrix1, matrix2)
with tf.Session() as sess:
sess.run(product)
解决方案 22:
import tensorflow as tf
sess = tf.InteractiveSession()
x = [[1.,2.,1.],[1.,1.,1.]]
y = tf.nn.softmax(x)
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
print(product.eval())
tf.reset_default_graph()
sess.close()
解决方案 23:
tf.Print 现已弃用,以下介绍如何使用 tf.print(小写 p)代替。
虽然运行会话是一个不错的选择,但并不总是可行的方法。例如,您可能希望在特定会话中打印一些张量。
新的打印方法返回没有输出张量的打印操作:
print_op = tf.print(tensor_to_print)
由于它没有输出,因此您无法像使用 tf.Print 那样将其插入到图形中。相反,您可以将其添加到会话中的控制依赖项中,以便打印。
sess = tf.compat.v1.Session()
with sess.as_default():
tensor_to_print = tf.range(10)
print_op = tf.print(tensor_to_print)
with tf.control_dependencies([print_op]):
tripled_tensor = tensor_to_print * 3
sess.run(tripled_tensor)
有时,在较大的图中(可能部分在子函数中创建),将 print_op 传播到会话调用很麻烦。然后,可以使用 tf.tuple 将打印操作与另一个操作耦合,然后无论哪个会话执行代码,该操作都会与该操作一起运行。以下是完成的方法:
print_op = tf.print(tensor_to_print)
some_tensor_list = tf.tuple([some_tensor], control_inputs=[print_op])
# Use some_tensor_list[0] instead of any_tensor below.
解决方案 24:
它与 Tensorflow 版本 2.4.1 兼容:
import tensorflow as tf
tf.config.run_functions_eagerly(True) # Forces eager execution
# (...) your tensor named 'my_tensor' is created
print(my_tesor.numpy())
注意用@tf.function注释的方法:
长话短说:
如果 @tf.function 不是必需的,请尝试将其删除。当应用 @tf.function 时,代码将被编译为在图形模式下运行,该模式不直接支持 .numpy()。相反,请将其删除,以便函数可以默认在 eager 模式下运行 - 通过 chatGPT :-)。
最后,伙计们,考虑检查较新的 Tensorflow 版本,据我所知,它提供了更好的调试和值读取(内部状态)替代方案。
祝你好运!
解决方案 25:
问题:如何在 TensorFlow 中打印 Tensor 对象的值?
回答:
import tensorflow as tf
# Variable
x = tf.Variable([[1,2,3]])
# initialize
init = (tf.global_variables_initializer(), tf.local_variables_initializer())
# Create a session
sess = tf.Session()
# run the session
sess.run(init)
# print the value
sess.run(x)