以下內容摘自Google開發者網站課程——機器學習速成課程
TensorFlow 的名稱源自張量,張量是任意維度的數組。借助 TensorFlow,您可以操控具有大量維度的張量。即便如此,在大多數情況下,您會使用以下一個或多個低維張量:
- 標量是零維數組(零階張量)。例如,
\'Howdy\'
或5
- 矢量是一維數組(一階張量)。例如,
[2, 3, 5, 7, 11]
或[5]
- 矩陣是二維數組(二階張量)。例如,
[[3.1, 8.2, 5.9][4.3, -2.7, 6.5]
TensorFlow 指令會創建、銷毀和操控張量。典型 TensorFlow 程序中的大多數代碼行都是指令。
TensorFlow 圖(也稱為計算圖或數據流圖)是一種圖數據結構。很多 TensorFlow 程序由單個圖構成,但是 TensorFlow 程序可以選擇創建多個圖。圖的節點是指令;圖的邊是張量。張量流經圖,在每個節點由一個指令操控。一個指令的輸出張量通常會變成后續指令的輸入張量。TensorFlow 會實現延遲執行模型,意味着系統僅會根據相關節點的需求在需要時計算節點。
張量可以作為常量或變量存儲在圖中。您可能已經猜到,常量存儲的是值不會發生更改的張量,而變量存儲的是值會發生更改的張量。不過,您可能沒有猜到的是,常量和變量都只是圖中的一種指令。常量是始終會返回同一張量值的指令。變量是會返回分配給它的任何張量的指令。
要定義常量,請使用 tf.constant
指令,並傳入它的值。例如:
x = tf.constant([5.2])
同樣,您可以創建如下變量:
y = tf.Variable([5])
或者,您也可以先創建變量,然后再如下所示地分配一個值(注意:您始終需要指定一個默認值):
y = tf.Variable([0])
y = y.assign([5])
定義一些常量或變量后,您可以將它們與其他指令(如 tf.add
)結合使用。在評估 tf.add
指令時,它會調用您的 tf.constant
或 tf.Variable
指令,以獲取它們的值,然后返回一個包含這些值之和的新張量。
圖必須在 TensorFlow 會話中運行,會話存儲了它所運行的圖的狀態:
將 tf.Session() 作為會話:
initialization = tf.global_variables_initializer()
print y.eval()
在使用 tf.Variable
時,您必須在會話開始時調用 tf.global_variables_initializer
,以明確初始化這些變量,如上所示。
簡單DEMO:

import tensorflow as tf with tf.Graph().as_default(): # Task 2: Simulate 10 throws of two dice. Store the results # in a 10x3 matrix. # We're going to place dice throws inside two separate # 10x1 matrices. We could have placed dice throws inside # a single 10x2 matrix, but adding different columns of # the same matrix is tricky. We also could have placed # dice throws inside two 1-D tensors (vectors); doing so # would require transposing the result. dice1 = tf.Variable(tf.random_uniform([10, 1], minval=1, maxval=7, dtype=tf.int32)) dice2 = tf.Variable(tf.random_uniform([10, 1], minval=1, maxval=7, dtype=tf.int32)) # We may add dice1 and dice2 since they share the same shape # and size. dice_sum = tf.add(dice1, dice2) # We've got three separate 10x1 matrices. To produce a single # 10x3 matrix, we'll concatenate them along dimension 1. resulting_matrix = tf.concat( values=[dice1, dice2, dice_sum], axis=1) with tf.Session() as sess: # The variables haven't been initialized within the graph yet, # so let's remedy that. sess.run(tf.global_variables_initializer()) print(resulting_matrix.eval())