在此之前,我們介紹過用于自動微分的 TensorFlow API - 自動微分,優化機器學習模型的關鍵技術,這是機器學習的基本構建塊。在今天的教程中,我們將使用先前教程中介紹的 TensorFlow 基礎來進行一些簡單的機器學習。
TensorFlow 還包括一個更高級別的神經網絡 API(tf.keras),它提供了有用的抽象來減少樣板。我們強烈建議那些使用神經網絡的人使用更高級別的 API。但是,在這個簡短的教程中我們將從神經網絡訓練的基本原理來建立一個堅實的基礎。
設置
import tensorflow as tftf.enable_eager_execution()
變量
TensorFlow 中的張量是不可變的無狀態對象。然而,機器學習模型需要具有可變的狀態:隨著模型的訓練,計算預測的相同代碼應該隨著時間的推移而表現不同(希望具有較低的損失?。?。要表示在計算過程中需要改變的狀態,事實上您可以選擇依賴 Python 這種有狀態的編程語言:
# Using python statex = tf.zeros([10, 10])x += 2 # This is equivalent to x = x + 2, which does not mutate the original # value of xprint(x)
tf.Tensor([[2。2. 2. 2. 2. 2. 2. 2. 2. 2.] [2。2. 2. 2. 2. 2. 2. 2. 2. 2.] [2。2. 2. 2. 2. 2. 2. 2. 2. 2.] [2。2. 2. 2. 2. 2. 2. 2. 2. 2.] [2。2. 2. 2. 2. 2. 2. 2. 2. 2.] [2。2. 2. 2. 2. 2. 2. 2. 2. 2.] [2。2. 2. 2. 2. 2. 2. 2. 2. 2.] [2。2. 2. 2. 2. 2. 2. 2. 2. 2.] [2。2. 2. 2. 2. 2. 2. 2. 2. 2.] [2。2. 2. 2. 2. 2. 2. 2. 2. 2.]],shape =(10,10),dtype = float32)
但是,TensorFlow 內置了有狀態操作,這些操作通常比您所用的低級 Python 表示更易于使用。例如,為了表示模型中的權重,使用 TensorFlow 變量通常是方便有效的。
變量是一個存儲值的對象,當在 TensorFlow 計算中使用時,它將隱式地從該存儲值中讀取。有些操作(如:tf.assign_sub,tf.scatter_update 等)會操縱存儲在 TensorFlow 變量中的值。
v = tf.Variable(1.0)assert v.numpy() == 1.0# Re-assign the valuev.assign(3.0)assert v.numpy() == 3.0# Use `v` in a TensorFlow operation like tf.square() and reassignv.assign(tf.square(v))assert v.numpy() == 9.0
使用變量的計算在計算梯度時自動跟蹤。對于表示嵌入式的變量,TensorFlow 默認會進行稀疏更新,這樣可以提高計算效率和內存效率。
使用變量也是一種快速讓代碼的讀者知道這段狀態是可變的方法。
示例:擬合線性模型
現在讓我們把目前掌握的幾個概念 — 張量、梯度帶、變量 — 應用到構建和訓練一個簡單模型中去。這通常涉及幾個步驟:
1.定義模型。
2.定義損失函數。
3.獲取訓練數據。
4.運行訓練數據并使用 “優化器” 調整變量以匹配數據。
在本教程中,我們將介紹一個簡單線性模型的簡單示例:f(x) = x * W + b,它有兩個變量 —W 和 b。此外,我們將綜合數據,以便訓練好的模型具有 W = 3.0 和 b = 2.0。
定義模型
讓我們定義一個簡單的類來封裝變量和計算。
class Model(object): def __init__(self): # Initialize variable to (5.0, 0.0) # In practice, these should be initialized to random values. self.W = tf.Variable(5.0) self.b = tf.Variable(0.0) def __call__(self, x): return self.W * x + self.b model = Model()assert model(3.0).numpy() == 15.0
定義損失函數
損失函數測量給定輸入的模型輸出與期望輸出的匹配程度。讓我們使用標準的 L2 損失。
def loss(predicted_y, desired_y): return tf.reduce_mean(tf.square(predicted_y - desired_y))
獲取訓練數據
讓我們用一些噪音(noise)合成訓練數據。
TRUE_W = 3.0TRUE_b = 2.0NUM_EXAMPLES = 1000inputs = tf.random_normal(shape=[NUM_EXAMPLES])noise = tf.random_normal(shape=[NUM_EXAMPLES])outputs = inputs * TRUE_W + TRUE_b + noise
在我們訓練模型之前,讓我們想象一下模型現在的位置。我們將用紅色繪制模型的預測,用藍色繪制訓練數據。
import matplotlib.pyplot as pltplt.scatter(inputs, outputs, c='b')plt.scatter(inputs, model(inputs), c='r')plt.show()print('Current loss: '),print(loss(model(inputs), outputs).numpy())
Current loss:
7.92897
定義訓練循環
我們現在有了網絡和培訓數據。我們來訓練一下,使用訓練數據更新模型的變量 ( W 和 b),以便使用梯度下降減少損失。在 tf.train.Optimizer 實現中有許多梯度下降方案的變體。我們強烈建議使用這種實現,但本著從基本原理出發的精神,在這個特定的例子中,我們將自己實現基本的數學。
def train(model, inputs, outputs, learning_rate): with tf.GradientTape() as t: current_loss = loss(model(inputs), outputs) dW, db = t.gradient(current_loss, [model.W, model.b]) model.W.assign_sub(learning_rate * dW) model.b.assign_sub(learning_rate * db)
最后,讓我們反復運行訓練數據,看看 W 和 b 是如何發展的。
model = Model()# Collect the history of W-values and b-values to plot laterWs, bs = [], []epochs = range(10)for epoch in epochs: Ws.append(model.W.numpy()) bs.append(model.b.numpy()) current_loss = loss(model(inputs), outputs) train(model, inputs, outputs, learning_rate=0.1) print('Epoch %2d: W=%1.2f b=%1.2f, loss=%2.5f' % (epoch, Ws[-1], bs[-1], current_loss))# Let's plot it allplt.plot(epochs, Ws, 'r', epochs, bs, 'b')plt.plot([TRUE_W] * len(epochs), 'r--', [TRUE_b] * len(epochs), 'b--')plt.legend(['W', 'b', 'true W', 'true_b'])plt.show()
Epoch 0: W=5.00 b=0.00, loss=7.92897Epoch 1: W=4.64 b=0.35, loss=5.61977Epoch 2: W=4.35 b=0.64, loss=4.07488Epoch 3: W=4.11 b=0.88, loss=3.04133Epoch 4: W=3.91 b=1.07, loss=2.34987Epoch 5: W=3.75 b=1.23, loss=1.88727Epoch 6: W=3.62 b=1.36, loss=1.57779Epoch 7: W=3.51 b=1.47, loss=1.37073Epoch 8: W=3.42 b=1.55, loss=1.23221Epoch 9: W=3.35 b=1.62, loss=1.13954
下一步
在本教程中,我們介紹了變量 Variables,使用了到目前為止討論的 TensorFlow 基本原理構建并訓練了一個簡單的線性模型。
從理論上講,這幾乎是您使用 TensorFlow 進行機器學習研究所需要的全部內容。在實踐中,特別是對于神經網絡,更高級別的 APItf.keras 會更方便,因為它提供更高級別的構建塊(稱為 “層”),保存和恢復狀態的實用程序,一套損失函數,一套優化策略等等。
-
機器學習
+關注
關注
66文章
8501瀏覽量
134581 -
tensorflow
+關注
關注
13文章
330瀏覽量
61170
原文標題:帶你使用 TensorFlow 進行機器學習研究
文章出處:【微信號:tensorflowers,微信公眾號:Tensorflowers】歡迎添加關注!文章轉載請注明出處。
發布評論請先 登錄
關于 TensorFlow
谷歌深度學習插件tensorflow
干貨!教你怎么搭建TensorFlow深度學習開發環境!
TensorFlow的特點和基本的操作方式
labview+yolov4+tensorflow+openvion深度學習
TensorFlow的框架結構解析

評論