我一直在使用TensorFlow中矩阵乘法的介绍性示例。

matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

当我打印乘积时,它显示为一个张量对象:

<tensorflow.python.framework.ops.Tensor object at 0x10470fcd0>

但是我怎么知道产品的价值呢?

下面的方法不起作用:

print product
Tensor("MatMul:0", shape=TensorShape([Dimension(1), Dimension(1)]), dtype=float32)

我知道图在会话上运行,但是没有任何方法可以检查张量对象的输出而不在会话中运行图吗?


求一个Tensor对象的实际值最简单的方法是将它传递给session .run()方法,或者当你有一个默认会话(即在with tf.Session():块中,或见下文)时调用Tensor.eval()。一般来说[B],如果不在会话中运行一些代码,就不能打印张量的值。

如果你正在试验编程模型,想要一种简单的方法来求张量,tf。InteractiveSession允许你在程序开始时打开一个会话,然后将该会话用于所有的Tensor.eval()(和Operation.run())调用。这在交互设置中(比如shell或IPython笔记本)更容易,因为到处传递Session对象很乏味。例如,以下工作在Jupyter笔记本:

with tf.Session() as sess:  print(product.eval()) 

对于如此小的表达式来说,这可能看起来很愚蠢,但这是Tensorflow 1中的关键思想之一。x是延迟执行:构建一个大而复杂的表达式非常便宜,当你想计算它时,后端(你连接到一个会话)能够更有效地调度它的执行(例如并行执行独立的部分并使用gpu)。


[A]:要打印一个张量的值而不返回到你的Python程序,你可以使用tf.print()操作符,正如Andrzej在另一个答案中建议的那样。根据官方文件:

为了确保操作符运行,用户需要将生成的op传递给tf. compat_1 . session的run方法,或者通过指定tf. compat_1 .control_dependencies([print_op])将op作为已执行操作的控制依赖项,输出到标准输出。

还要注意:

在Jupyter笔记本和colabs中,tf。打印打印到笔记本单元格输出。它不会写入笔记本内核的控制台日志。

[B]:你可以使用tf.get_static_value()函数来获得给定张量的常数值,如果它的值是可以有效计算的。

不,你不能在不运行图(执行session.run())的情况下看到张量的内容。你能看到的只有:

张量的维数(但我假设对TF的操作列表计算它并不难) 用于生成张量(transpose_1:0, random_uniform:0)的操作类型。 张量中元素的类型(float32)

我没有在文档中找到这一点,但我相信变量的值(和一些常数在赋值时没有计算)。


看看这个例子:

import tensorflow as tf
from datetime import datetime
dim = 7000

第一个例子中,我刚刚启动了一个常数的随机数张量运行的时间几乎是相同的不管dim (0:00:00.003261)

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_行列式(m1),记住时间将以O(dim^2.8)为单位运行)

附注:我在文档中找到了解释:

张量对象是运算结果的符号句柄, 但是实际上并不保存操作输出的值。

虽然其他答案是正确的,即在对图求值之前不能打印值,但它们并没有谈到一种简单的方法,即一旦对图求值,就可以在图中实际打印值。

当图被求值(使用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.c eval(),我们得到:

I tensorflow/core/kernels/logging_ops.cc:79] This is a: [1 3]

重申其他人所说的,不运行图表是不可能检查值的。

下面是一个简单的代码片段,供寻找打印值的简单示例的人使用。代码可以在ipython notebook中执行,无需任何修改

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]]

基于上面的答案,使用特定的代码片段,您可以像这样打印产品:

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

试试这个简单的代码!(不言自明)

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)

我认为你需要掌握一些基本知识。通过上面的例子,你已经创建了张量(多维数组)。但是要让张量流真正工作,你必须启动一个“会话”,并在会话中运行你的“操作”。注意单词“session”和“operation”。 要使用张量流,你需要知道4件事:

张量 操作 会话 图

现在,从你写出来的东西中,你已经给出了张量和操作,但你没有运行会话,也没有图。张量(图的边)在图中流动,并由操作(图的节点)操作。有默认的图形,但你可以在会话中初始化你的。

当你说打印时,你只访问你定义的变量或常数的形状。

所以你可以看到你错过了什么:

 with tf.Session() as sess:     
           print(sess.run(product))
           print (product.eval())

希望能有所帮助!

请注意,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

你应该认为TensorFlow核心程序由两个独立的部分组成:

构建计算图。 运行计算图。

因此,对于下面的代码,您只需构建计算图。

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

通过启用即时执行,你可以检查TensorObject的输出,而不用在会话中运行图。

只需添加以下两行代码: 导入tensorflow.contrib.eager为tfe tfe.enable_eager_execution ()

在你导入tensorflow之后。

在你的例子中打印产品的输出现在将是: 特遣部队。张量([[12。[],形状=(1,1),dtype=float32)

请注意,从现在(2017年11月)开始,你必须每晚安装一个Tensorflow构建来实现快速执行。预建车轮可以在这里找到。

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

我发现即使在阅读了所有的答案之后,我也不容易理解需要什么,直到我执行了这个。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()

基本上,在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()

输出将是这样的:

array([[1st, 2nd, 3rd], [4th, 5th, 6th]], dtype=float32)

问题:如何在TensorFlow中打印一个张量对象的值?

答:

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)

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

在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,默认开启急切模式。因此下面的代码与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.]]

启用热切执行,这是在1.10版之后tensorflow中引入的。 它很容易使用。

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

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。

你可以使用Keras,一行回答将使用eval方法,如下所示:

import keras.backend as K
print(K.eval(your_tensor))

使用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)

特遣部队。Print现在已弃用,下面是如何使用tf。而是打印(小写p)。

虽然运行会话是一个很好的选择,但它并不总是正确的方法。例如,你可能想在一个特定的会话中打印一些张量。

新的print方法返回一个没有输出张量的打印操作:

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传播到会话调用是很麻烦的。然后,特遣部队。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.

在Tensorflow V2中,使用:tf.keras.backend打印张量的值。print_tensor (x,消息= ")

我不确定我是否遗漏了这里,但我认为最简单和最好的方法是使用tf.keras.backend。get_value API。

print(product)
>>tf.Tensor([[12.]], shape=(1, 1), dtype=float32)
print(tf.keras.backend.get_value(product))
>>[[12.]]

你可以打印出session中的张量值,如下所示:

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)