簡體   English   中英

如何在 TensorFlow 中打印 Tensor 對象的值?

[英]How to print the value of a Tensor object in TensorFlow?

我一直在使用 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運行圖形嗎?

評估Tensor對象實際值的最簡單[A]方法是將其傳遞給Session.run()方法,或者在您有默認會話時(即在with tf.Session(): Tensor.eval()調用Tensor.eval() with tf.Session():阻止,或見下文)。 通常[B] ,如果不在會話中運行某些代碼,則無法打印張量的值。

如果您正在試驗編程模型,並且想要一種簡單的方法來評估張量, tf.InteractiveSession允許您在程序開始時打開一個會話,然后將該會話用於所有Tensor.eval() (和Operation.run() Tensor.eval() Operation.run() ) 調用。 這在交互式設置中會更容易,例如 shell 或 IPython 筆記本,因為到處傳遞Session對象很乏味。 例如,以下內容適用於 Jupyter 筆記本:

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

對於這么小的表達式來說,這可能看起來很愚蠢,但是 Tensorflow 1.x 中的一個關鍵思想是延遲執行:構建一個大而復雜的表達式非常便宜,並且當您想要評估它時,后端(以您與Session連接的Session )能夠更有效地安排其執行(例如並行執行獨立部分和使用 GPU)。


[A]:要打印張量的值而不將其返回到 Python 程序,您可以使用tf.print()運算符,正如Andrzej 在另一個答案中建議的那樣 根據官方文檔:

為了確保操作符運行,用戶需要將生成的 op 傳遞給tf.compat.v1.Session的 run 方法,或者通過指定tf.compat.v1.control_dependencies([print_op] ),打印到標准輸出。

另請注意:

在 Jupyter 筆記本和 colab 中, tf.print打印到筆記本單元輸出。 它不會寫入筆記本內核的控制台日志。

[B]:如果可以有效計算給定張量的值,您也許可以使用tf.get_static_value()函數來獲取其常數值。

雖然其他答案是正確的,在您評估圖形之前您無法打印該值,但他們並沒有討論一種在評估圖形后實際打印值的簡單方法。

在計算圖形時(使用runeval )查看張量值的最簡單方法是使用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]

重申其他人所說的話,不運行圖表就無法檢查值。

對於任何尋找簡單示例來打印值的人來說,一個簡單的片段如下。 代碼在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]]

不,如果不運行圖形(執行session.run() ),您就無法看到張量的內容。 你能看到的只有:

  • 張量的維數(但我認為對於 TF的操作列表計算它並不難)
  • 將用於生成張量的操作類型( transpose_1:0 , random_uniform:0
  • 張量中的元素類型( float32

我沒有在文檔中找到這個,但我相信變量的值(和一些常量在賦值時沒有計算)。


看看這個例子:

import tensorflow as tf
from datetime import datetime
dim = 7000

第一個例子,我只是啟動一個隨機數的常數張量,與暗淡0:00:00.0032610: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_determinant(m1) ,記住時間將在O(dim^2.8)

PS我發現它在文檔中有解釋:

Tensor 對象是操作結果的符號句柄,但實際上並不保存操作輸出的值。

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

我認為你需要掌握一些基本知識。 通過上面的示例,您已經創建了張量(多維數組)。 但是要使張量流真正起作用,您必須啟動一個“會話”並在會話中運行您的“操作”。 注意“會話”和“操作”這兩個詞。 您需要了解 4 件事才能使用 tensorflow:

  1. 張量
  2. 操作
  3. 會話
  4. 圖表

現在根據你寫的內容,你已經給出了張量和操作,但你沒有運行會話也沒有圖表。 張量(圖的邊)流經圖並由操作(圖的節點)操縱。 有默認圖表,但您可以在會話中啟動您的圖表。

當您說 print 時,您只能訪問您定義的變量或常量的形狀。

所以你可以看到你錯過了什么:

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

希望能幫助到你!

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)

這很有用,因為您不必顯式創建SessionInteractiveSession

根據上面的答案,使用您的特定代碼片段,您可以像這樣打印產品:

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

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

您可以檢查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 nightly build 才能啟用 Eager Execution。 預制輪子可以在這里找到。

請注意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 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]))

您可以使用 Keras,單行答案將是使用eval方法,如下所示:

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

試試這個簡單的代碼! (這是不言自明的)

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)

我不確定我是否在這里遺漏了,但我認為最簡單和最好的方法是使用tf.keras.backend.get_value API。

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

即使在閱讀了所有答案之后,我也很難理解需要什么,直到我執行此操作。 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 V2 中,使用以下方法打印張量的值: tf.keras.backend.print_tensor(x, message='')

您可以按如下方式打印會話中的張量值:

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)

基本上,在 tensorflow 中,當您創建任何類型的張量時,它們都會被創建並存儲在其中,只有在您運行 tensorflow 會話時才能訪問它們。 假設你已經創建了一個常數張量
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
無需運行會話,您就可以獲得
- op :一個操作。 計算此張量的操作。
- value_index :一個整數。 生成此張量的操作端點的索引。
- dtype :一個D型。 存儲在此張量中的元素類型。

要獲取值,您可以使用所需的張量運行會話,如下所示:

with tf.Session() as sess:
    print(sess.run(c))
    sess.close()

輸出將是這樣的:

數組([[1., 2., 3.], [4., 5., 6.]], dtype=float32)

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

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

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.

問題:如何在 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM