一 學習目標:
學習 TensorFlow 編程模型的基礎知識,重點了解以下概念:
- 張量
- 指令
- 圖
- 會話
構建一個簡單的 TensorFlow 程序,使用該程序繪製一個默認圖並創建一個運行該圖的會話
二 概念概覽
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
,以明確初始化這些變量,如上所示。
**注意:**會話可以將圖分發到多個機器上執行(假設程序在某個分佈式計算框架上運行)。有關詳情,請參閱分佈式 TensorFlow。
總結
TensorFlow 編程本質上是一個兩步流程:
- 將常量、變量和指令整合到一個圖中。
- 在一個會話中評估這些常量、變量和指令。
創建一個簡單的 TensorFlow 程序
我們來看看如何編寫一個將兩個常量相加的簡單 TensorFlow 程序。
添加 import 語句
與幾乎所有 Python 程序一樣,您首先要添加一些 import
語句。
當然,運行 TensorFlow 程序所需的 import
語句組合取決於您的程序將要訪問的功能。至少,您必須在所有 TensorFlow 程序中添加 import tensorflow
語句:
import tensorflow as tf
請勿忘記執行前面的代碼塊(import
語句)。
其他常見的 import 語句包括:
import matplotlib.pyplot as plt # 數據集可視化。
import numpy as np # 低級數字 Python 庫。
import pandas as pd # 較高級別的數字 Python 庫。
TensorFlow 提供了一個默認圖。不過,我們建議您明確創建自己的 Graph
,以便跟蹤狀態(例如,您可能希望在每個單元格中使用一個不同的 Graph
)。
from __future__ import print_function
import tensorflow as tf
# Create a graph.
g = tf.Graph()
# Establish the graph as the "default" graph.
with g.as_default():
# Assemble a graph consisting of the following three operations:
# * Two tf.constant operations to create the operands.
# * One tf.add operation to add the two operands.
x = tf.constant(8, name="x_const")
y = tf.constant(5, name="y_const")
sum = tf.add(x, y, name="x_y_sum")
# Now create a session.
# The session will run the default graph.
with tf.Session() as sess:
print(sum.eval())
練習:引入第三個運算數
修改上面的代碼列表,以將三個整數(而不是兩個)相加:
- 定義第三個標量整數常量
z
,併爲其分配一個值4
。 - 將
sum
與z
相加,以得出一個新的和。
**提示:**請參閱有關 tf.add() 的 API 文檔,瞭解有關其函數簽名的更多詳細信息。
- 重新運行修改後的代碼塊。該程序是否生成了正確的總和?
# Create a graph.
g = tf.Graph()
# Establish our graph as the "default" graph.
with g.as_default():
# Assemble a graph consisting of three operations.
# (Creating a tensor is an operation.)
x = tf.constant(8, name="x_const")
y = tf.constant(5, name="y_const")
sum = tf.add(x, y, name="x_y_sum")
# Task 1: Define a third scalar integer constant z.
z = tf.constant(4, name="z_const")
# Task 2: Add z to `sum` to yield a new sum.
new_sum = tf.add(sum, z, name="x_y_z_sum")
# Now create a session.
# The session will run the default graph.
with tf.Session() as sess:
# Task 3: Ensure the program yields the correct grand total.
print(new_sum.eval())