簡體   English   中英

TensorFlow中的一切都是Tensor,包括操作嗎?

[英]Is everything a Tensor in TensorFlow, including operations?

我一直在閱讀關於核心圖結構的文檔似乎對TensorFlow實際上做的和文檔有什么不同(除非我有一個誤解,我認為我這樣做)。

文檔說有Operation對象Tensor對象 它提供了這樣的例子,因此我嘗試創建一些並詢問python它們是什么類型。 首先讓我們做一個常數:

c = tf.constant(1.0)

print c #Tensor("Const_1:0", shape=(), dtype=float32)
print type(c) #<class 'tensorflow.python.framework.ops.Tensor'>

它說它是一個Tensor。 大! 有意義,它甚至給我有關其內容的信息。

我做了一個與我期望的操作相同的實驗:

W = tf.Variable(tf.truncated_normal([784, 10], mean=0.0, stddev=0.1))
b = tf.Variable(tf.constant(0.1, shape=[10]))
Wx = tf.matmul(x, W)
print Wx #Tensor("MatMul:0", shape=(?, 10), dtype=float32)
print type(Wx) #<class 'tensorflow.python.framework.ops.Tensor'>

但是,正如您所看到的,Tensor流表示Wx和c都是相同的類型。 這是否意味着沒有操作對象或者我做錯了什么?

tf.Varible是一個張量,然后你為它賦值,即一個操作,一個賦值操作。 或者你使用tf.mul(),這也是一個操作

有手術。 您可以通過graph.get_operations()獲取graph中所有操作的列表(您可以通過tf.get_default_graph()sess.graph或適合您情況的任何內容獲取graph )。

只是在Python中,像tf.mul這樣的東西tf.mul返回乘法運算產生的張量(其他一切都會令人討厭,因為它是你在進一步操作中用作輸入的張量)。

我不是專家,但也許這會讓事情變得清晰起來。

x = tf.constant(1, shape=[10, 10])
y = tf.constant(1, shape=[10, 10])
z = tf.matmul(x, y, name='operation')
# print(z)
# tf.Tensor 'operation:0' shape=(10, 10) dtype=int32
# z is a placeholder for the result of multiplication of x and y
# but it has an operation attached to it
# print(z.op)
# tensorflow.python.framework.ops.Operation at 0x10bfe40f0
# and so do x and y
# print(x.op)
# 
ses = tf.InteractiveSession()
# now that we are in a session, we have an operation graph
ses.graph.get_operation_by_name('operation')
# tensorflow.python.framework.ops.Operation at 0x10bfe40f0
# same operation that we saw attached to z
ses.graph.get_operations()
# shows a list of three operations, just as expected
# this way you can define the graph first and then run all the operations in a session

我對TensorFlow不太熟悉,但它似乎是一個基本概念, Wxtf.matmul(x, W)輸出的符號句柄 所以你實際創建了一個Operation,但是訪問Wx會給你一個結果的表示(即使它在你運行一個會話之前沒有計算)。

請查看TensorFlow常見問題解答以獲取更詳細的說明。

在tensorflow的上下文之外考慮這個,只是在基礎python中。 假設你這樣做:

def f(x):
    return(x+1)

x = 0

print(type(x))
print(type(f(x)))

在這兩種情況下你都得到int ,對嗎? 但是如果你這樣做會怎樣

type(f)

在這種情況下,您將獲得一個function 與tensorflow相同:操作結果的類型是新的張量,但操作本身的類型不是張量。

暫無
暫無

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

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