本指南讓您開始在TensorFlow中編程。在使用本指南以前, 請安裝TensorFlow。爲了充分利用本指南,您應該瞭解如下內容:node
TensorFlow提供了多個API。最低級別的API - TensorFlow核心 - 爲您提供完整的編程控制。咱們推薦TensorFlow Core用於機器學習研究人員和其餘須要對其模型進行精細控制的人員。更高層次的API創建在TensorFlow核心之上。這些更高級別的API一般比TensorFlow Core更容易學習和使用。另外,更高級別的API使得不一樣用戶之間的重複任務更容易和更一致。像tf.estimator這樣的高級API能夠幫助您管理數據集,估算器,培訓和推理。編程
本指南從TensorFlow核心教程開始。稍後,咱們演示如何在tf.estimator中實現相同的模型。瞭解TensorFlow核心原則將給你一個很好的思惟模型,說明當你使用更緊湊的更高級別的API時,內部是如何工做的。數組
TensorFlow中的數據中心單位是張量。一個張量由一組造成任意數量維數的原始值組成。張量的等級是它的維數。這裏是一些張量的例子:bash
3 # a rank 0 tensor; a scalar with shape []
[1., 2., 3.] # a rank 1 tensor; a vector with shape [3]
[[1., 2., 3.], [4., 5., 6.]] # a rank 2 tensor; a matrix with shape [2, 3]
[[[1., 2., 3.]], [[7., 8., 9.]]] # a rank 3 tensor with shape [2, 1, 3]
複製代碼
導入張量流微信
TensorFlow程序的規範導入語句以下所示:app
import tensorflow as tf
複製代碼
這使得Python能夠訪問全部 TensorFlow 的類,方法和符號。大多數文檔假定您已經完成了這個工做。機器學習
你可能會想到TensorFlow核心程序由兩個獨立的部分組成:ide
甲計算圖形是一系列排列成節點的圖形TensorFlow操做。咱們來構建一個簡單的計算圖。每一個節點將零個或多個張量做爲輸入,併產生張量做爲輸出。一種類型的節點是一個常量。像全部的TensorFlow常量同樣,它不須要輸入,而是輸出一個內部存儲的值。咱們能夠建立兩個浮點Tensors node1 ,node2以下所示:函數
node1 = tf.constant(3.0, dtype=tf.float32)
node2 = tf.constant(4.0) # also tf.float32 implicitly
print(node1, node2)
複製代碼
最後的打印聲明產生oop
Tensor("Const:0", shape=(), dtype=float32) Tensor("Const_1:0", shape=(), dtype=float32)
複製代碼
請注意,打印節點不會輸出值3.0,4.0正如您所指望的那樣。相反,它們是在評估時分別產生3.0和4.0的節點。爲了實際評估節點,咱們必須在會話中運行計算圖。會話封裝了TensorFlow運行時的控制和狀態。
下面的代碼建立一個Session對象,而後調用它的run方法來運行足夠的計算圖來評估node1和node2。經過在會話中運行計算圖以下:
sess = tf.Session()
print(sess.run([node1, node2]))
複製代碼
咱們看到了3.0和4.0的預期值:
[3.0, 4.0]
複製代碼
咱們能夠經過組合Tensor節點和操做來構建更復雜的計算(操做也是節點)。例如,咱們能夠添加咱們的兩個常量節點,併產生一個新的圖形以下:
from __future__ import print_function
node3 = tf.add(node1, node2)
print("node3:", node3)
print("sess.run(node3):", sess.run(node3))
複製代碼
最後兩個打印語句產生
node3: Tensor("Add:0", shape=(), dtype=float32)
sess.run(node3): 7.0
複製代碼
TensorFlow提供了一個名爲TensorBoard的實用程序,能夠顯示計算圖的圖片。下面是一個屏幕截圖,顯示了TensorBoard如何將圖形可視化:
就目前來看,這張圖並非特別有趣,由於它老是會產生一個不變的結果。圖形能夠被參數化來接受稱爲佔位符的外部輸入。一個佔位符是一個承諾後提供一個值。
a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
adder_node = a + b # + provides a shortcut for tf.add(a, b)
複製代碼
前面的三行有點像一個函數或lambda,咱們在其中定義兩個輸入參數(a和b),而後對它們進行操做。咱們能夠經過使用run方法的feed_dict參數將多個輸入的 具體值提供給佔位符來評估這個圖形。
print(sess.run(adder_node, {a: 3, b: 4.5}))
print(sess.run(adder_node, {a: [1, 3], b: [2, 4]}))
複製代碼
致使輸出
7.5 [ 3. 7.] 在TensorBoard中,圖形以下所示:
咱們能夠經過添加另外一個操做來使計算圖更加複雜。例如,
add_and_triple = adder_node * 3.
print(sess.run(add_and_triple, {a: 3, b: 4.5}))
複製代碼
產生輸出
22.5 在TensorBoard中,上面的計算圖以下所示:
在機器學習中,咱們一般須要一個能夠進行任意輸入的模型,好比上面的模型。爲了使模型可訓練,咱們須要可以修改圖形以得到具備相同輸入的新輸出。 變量容許咱們將可訓練參數添加到圖形中。它們被構形成一個類型和初始值:
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
x = tf.placeholder(tf.float32)
linear_model = W*x + b
複製代碼
常量在調用時被初始化tf.constant,其值永遠不會改變。相比之下,變量在調用時不會被初始化tf.Variable。要初始化TensorFlow程序中的全部變量,您必須顯式調用一個特殊的操做,以下所示:
init = tf.global_variables_initializer()
sess.run(init)
複製代碼
實現initTensorFlow子圖的一個句柄是初始化全部的全局變量,這一點很重要。在咱們調用以前sess.run,變量是未初始化的。
既然x是佔位符,咱們能夠同時評估linear_model幾個值, x以下所示:
print(sess.run(linear_model, {x: [1, 2, 3, 4]}))
複製代碼
產生輸出
[ 0. 0.30000001 0.60000002 0.90000004]
複製代碼
咱們已經建立了一個模型,但咱們不知道它有多好。爲了評估培訓數據模型,咱們須要一個y佔位符來提供所需的值,咱們須要編寫一個損失函數。
損失函數用於衡量當前模型距離提供的數據有多遠。咱們將使用線性迴歸的標準損失模型,它將當前模型和提供的數據之間的三角形的平方相加。linear_model - y建立一個向量,其中每一個元素是相應示例的錯誤增量。咱們打電話tf.square來解決這個錯誤。而後,咱們總結全部的平方偏差來建立一個標量,它使用下面的方法來抽象全部例子的錯誤tf.reduce_sum:
y = tf.placeholder(tf.float32)
squared_deltas = tf.square(linear_model - y)
loss = tf.reduce_sum(squared_deltas)
print(sess.run(loss, {x: [1, 2, 3, 4], y: [0, -1, -2, -3]}))
複製代碼
產生損失價值
23.66
複製代碼
咱們能夠手動從新分配的值提升這W和b爲-1和1變量的值,完美初始化爲提供的價值tf.Variable,但可使用操做等來改變tf.assign。例如, W=-1而且b=1是咱們模型的最佳參數。咱們能夠改變W, b所以:
fixW = tf.assign(W, [-1.])
fixb = tf.assign(b, [1.])
sess.run([fixW, fixb])
print(sess.run(loss, {x: [1, 2, 3, 4], y: [0, -1, -2, -3]}))
複製代碼
最後的印刷品顯示如今的損失是零。
0.0
複製代碼
咱們猜想的「完美」的價值觀W和b,但機器學習的整點自動找到正確的模型參數。咱們將在下一節展現如何完成這個。
tf.train API
複製代碼
機器學習的完整討論超出了本教程的範圍。可是,TensorFlow提供了優化器,能夠逐漸改變每一個變量,以最大限度地減小損失函數。最簡單的優化器是梯度降低。它根據相對於該變量的損失導數的大小來修改每一個變量。通常來講,手動計算符號派生是繁瑣和容易出錯的。所以,TensorFlow能夠自動生成衍生產品,僅使用該函數對模型進行描述tf.gradients。爲了簡單起見,優化程序一般會爲您執行此操做。例如,
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
複製代碼
sess.run(init) # reset values to incorrect defaults.
for i in range(1000):
sess.run(train, {x: [1, 2, 3, 4], y: [0, -1, -2, -3]})
複製代碼
print(sess.run([W, b]))
複製代碼
致使最終的模型參數:
[array([-0.9999969], dtype=float32), array([ 0.99999082], dtype=float32)]
複製代碼
如今咱們已經完成了機器學習!雖然這個簡單的線性迴歸模型不須要太多的TensorFlow核心代碼,可是更復雜的模型和方法將數據提供給模型須要更多的代碼。所以,TensorFlow爲常見的模式,結構和功能提供更高層次的抽象。咱們將在下一節學習如何使用這些抽象。
完整的程序 完成的可訓練線性迴歸模型以下所示:
import tensorflow as tf
# Model parameters
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
# Model input and output
x = tf.placeholder(tf.float32)
linear_model = W*x + b
y = tf.placeholder(tf.float32)
# loss
loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares
# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
# training data
x_train = [1, 2, 3, 4]
y_train = [0, -1, -2, -3]
# training loop
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init) # reset values to wrong
for i in range(1000):
sess.run(train, {x: x_train, y: y_train})
# evaluate training accuracy
curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train})
print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))
複製代碼
運行時產生
W: [-0.9999969] b: [ 0.99999082] loss: 5.69997e-11
複製代碼
請注意,損失是很是小的數字(很是接近零)。若是你運行這個程序,你的損失可能與上述損失不徹底同樣,由於模型是用僞隨機值初始化的。
這個更復雜的程序仍然能夠在 TensorBoard 中可視化
tf.estimator
複製代碼
tf.estimator 是一個高級的TensorFlow庫,它簡化了機器學習的機制,包括如下內容:
tf.estimator定義了許多常見的模型。
基本用法 注意線性迴歸程序變得簡單多了 tf.estimator:
# NumPy is often used to load, manipulate and preprocess data.
import numpy as np
import tensorflow as tf
# Declare list of features. We only have one numeric feature. There are many
# other types of columns that are more complicated and useful.
feature_columns = [tf.feature_column.numeric_column("x", shape=[1])]
# An estimator is the front end to invoke training (fitting) and evaluation
# (inference). There are many predefined types like linear regression,
# linear classification, and many neural network classifiers and regressors.
# The following code provides an estimator that does linear regression.
estimator = tf.estimator.LinearRegressor(feature_columns=feature_columns)
# TensorFlow provides many helper methods to read and set up data sets.
# Here we use two data sets: one for training and one for evaluation
# We have to tell the function how many batches
# of data (num_epochs) we want and how big each batch should be.
x_train = np.array([1., 2., 3., 4.])
y_train = np.array([0., -1., -2., -3.])
x_eval = np.array([2., 5., 8., 1.])
y_eval = np.array([-1.01, -4.1, -7, 0.])
input_fn = tf.estimator.inputs.numpy_input_fn(
{"x": x_train}, y_train, batch_size=4, num_epochs=None, shuffle=True)
train_input_fn = tf.estimator.inputs.numpy_input_fn(
{"x": x_train}, y_train, batch_size=4, num_epochs=1000, shuffle=False)
eval_input_fn = tf.estimator.inputs.numpy_input_fn(
{"x": x_eval}, y_eval, batch_size=4, num_epochs=1000, shuffle=False)
# We can invoke 1000 training steps by invoking the method and passing the
# training data set.
estimator.train(input_fn=input_fn, steps=1000)
# Here we evaluate how well our model did.
train_metrics = estimator.evaluate(input_fn=train_input_fn)
eval_metrics = estimator.evaluate(input_fn=eval_input_fn)
print("train metrics: %r"% train_metrics)
print("eval metrics: %r"% eval_metrics)
複製代碼
運行時,會產生相似的東西
train metrics: {'average_loss': 1.4833182e-08, 'global_step': 1000, 'loss': 5.9332727e-08}
eval metrics: {'average_loss': 0.0025353201, 'global_step': 1000, 'loss': 0.01014128}
複製代碼
請注意咱們的評估數據是如何有更高的損失,但仍然接近於零。這意味着咱們正在正確地學習。
自定義模型 tf.estimator不會將您鎖定在預約義的模型中。假設咱們想建立一個沒有內置到TensorFlow中的自定義模型。咱們仍然能夠保留數據集,餵養,培訓等的高層次抽象 tf.estimator。爲了說明,咱們將展現如何實現咱們本身的等價模型,以LinearRegressor使用咱們對低級別TensorFlow API的知識。
要定義一個適用的自定義模型tf.estimator,咱們須要使用 tf.estimator.Estimator。tf.estimator.LinearRegressor其實是一個子類tf.estimator.Estimator。Estimator咱們只是簡單地提供Estimator一個函數model_fn來講明 tf.estimator如何評估預測,訓練步驟和損失,而不是分類 。代碼以下:
import numpy as np
import tensorflow as tf
# Declare list of features, we only have one real-valued feature
def model_fn(features, labels, mode):
# Build a linear model and predict values
W = tf.get_variable("W", [1], dtype=tf.float64)
b = tf.get_variable("b", [1], dtype=tf.float64)
y = W*features['x'] + b
# Loss sub-graph
loss = tf.reduce_sum(tf.square(y - labels))
# Training sub-graph
global_step = tf.train.get_global_step()
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = tf.group(optimizer.minimize(loss),
tf.assign_add(global_step, 1))
# EstimatorSpec connects subgraphs we built to the
# appropriate functionality.
return tf.estimator.EstimatorSpec(
mode=mode,
predictions=y,
loss=loss,
train_op=train)
estimator = tf.estimator.Estimator(model_fn=model_fn)
# define our data sets
x_train = np.array([1., 2., 3., 4.])
y_train = np.array([0., -1., -2., -3.])
x_eval = np.array([2., 5., 8., 1.])
y_eval = np.array([-1.01, -4.1, -7., 0.])
input_fn = tf.estimator.inputs.numpy_input_fn(
{"x": x_train}, y_train, batch_size=4, num_epochs=None, shuffle=True)
train_input_fn = tf.estimator.inputs.numpy_input_fn(
{"x": x_train}, y_train, batch_size=4, num_epochs=1000, shuffle=False)
eval_input_fn = tf.estimator.inputs.numpy_input_fn(
{"x": x_eval}, y_eval, batch_size=4, num_epochs=1000, shuffle=False)
# train
estimator.train(input_fn=input_fn, steps=1000)
# Here we evaluate how well our model did.
train_metrics = estimator.evaluate(input_fn=train_input_fn)
eval_metrics = estimator.evaluate(input_fn=eval_input_fn)
print("train metrics: %r"% train_metrics)
print("eval metrics: %r"% eval_metrics)
複製代碼
運行時產生
train metrics: {'loss': 1.227995e-11, 'global_step': 1000}
eval metrics: {'loss': 0.01010036, 'global_step': 1000}
複製代碼
請注意,自定義model_fn()函數的內容與下層API的手動模型訓練循環很是類似。
文章是根據官方英文文檔翻譯而來,掃一掃個人微信公衆號一塊兒學習吧。
我的網站:
http://chaodongyang.com