TensorFlow.js 是一個用於在 Web 瀏覽器和 Node.js 中訓練及部署機器學習模型的 JavaScript 庫。本教程將透過在瀏覽器中訓練一個極簡模型並利用該模型進行預測,向您展示如何開始使用 TensorFlow.js。
示例程式碼可在 GitHub 上找到。
先決條件
要完成本教程,您的開發環境需要安裝以下內容:
安裝示例
獲取原始碼並安裝依賴項
- 克隆或下載 tfjs-examples 倉庫。
- 進入
getting-started目錄:cd tfjs-examples/getting-started。 - 安裝依賴項:
yarn install。
如果您檢視 package.json 檔案,可能會注意到 TensorFlow.js 並不是一個依賴項。這是因為該示例透過 CDN 載入 TensorFlow.js。以下是來自 index.html 的完整 HTML 程式碼。
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"> </script>
</head>
<body>
<h4>Tiny TFJS example<hr/></h4>
<div id="micro-out-div">Training...</div>
<script src="./index.js"> </script>
</body>
</html>
位於 head 中的 <script> 元素載入了 TensorFlow.js 庫,而位於 body 末尾的 <script> 元素則載入了機器學習指令碼。
關於引入 TensorFlow.js 的其他方式,請參閱設定教程。
執行示例
執行示例並檢視結果
- 在
tfjs-examples/getting-started目錄中,執行yarn watch。 - 在瀏覽器中導航至
http://127.0.0.1:1234。
您應該會看到一個頁面標題,下方顯示一個數字,如 38.31612014770508。具體數字會有所波動,但應接近 39。
剛剛發生了什麼?
當 index.js 被載入時,它會使用滿足方程 $ y = 2x - 1 $ 的 $ x $ 和 $ y $ 值來訓練一個 tf.sequential 模型。
// Create a simple model.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
// Prepare the model for training: Specify the loss and the optimizer.
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
// Generate some synthetic data for training. (y = 2x - 1)
const xs = tf.tensor2d([-1, 0, 1, 2, 3, 4], [6, 1]);
const ys = tf.tensor2d([-3, -1, 1, 3, 5, 7], [6, 1]);
// Train the model using the data.
await model.fit(xs, ys, {epochs: 250});
然後,它會針對未見的 $ x $ 值 20 預測出一個 $ y $ 值,並更新 DOM 以顯示該預測結果。
// Use the model to do inference on a data point the model hasn't seen.
// Should print approximately 39.
document.getElementById('micro-out-div').innerText =
model.predict(tf.tensor2d([20], [1, 1])).dataSync();
$ 2 * 20 - 1 $ 的結果是 39,因此預測出的 $ y $ 值應該大約為 39。
接下來做什麼
本教程提供了一個使用 TensorFlow.js 在瀏覽器中訓練模型的極簡示例。如需更深入地瞭解如何使用 JavaScript 訓練模型,請參閱 TensorFlow.js 指南。
更多入門方式
以下是開始使用 TensorFlow.js 和 Web ML 的更多途徑。
觀看 TensorFlow.js Web ML 課程
如果您是一位希望獲得 Web ML 實踐介紹的 Web 開發人員,請檢視谷歌開發者影片課程“面向 Web 開發人員的機器學習”(Machine Learning for Web Developers)。該課程展示瞭如何在您的網站和應用程式中使用 TensorFlow.js。
編寫機器學習程式而無需直接處理張量
如果您想在不管理最佳化器或進行張量操作的情況下開始機器學習,請檢視 ml5.js 庫。
ml5.js 庫構建於 TensorFlow.js 之上,透過簡潔、易用的 API 在 Web 瀏覽器中提供對機器學習演算法和模型的訪問。
安裝 TensorFlow.js
瞭解如何安裝 TensorFlow.js 以便在 Web 瀏覽器或 Node.js 中實現。
將預訓練模型轉換為 TensorFlow.js
學習如何將預訓練模型從 Python 轉換為 TensorFlow.js。
學習現有的 TensorFlow.js 程式碼
tfjs-examples 倉庫提供了使用 TensorFlow.js 進行各種機器學習任務的小型實現示例。
視覺化您的 TensorFlow.js 模型行為
tfjs-vis 是一個旨在與 TensorFlow.js 配合使用的 Web 瀏覽器視覺化小型庫。
為 TensorFlow.js 處理準備資料
TensorFlow.js 支援使用機器學習最佳實踐來處理資料。