開始使用 TensorFlow.js

TensorFlow.js 是 JavaScript 程式庫,用於在 Web 瀏覽器和 Node.js 中訓練及部署機器學習模型。本教學課程說明如何開始使用 TensorFlow.js,方法是在瀏覽器中訓練最小模型,並使用該模型進行預測。

範例程式碼可在 GitHub 上取得。

必要條件

若要完成本教學課程,您的開發環境中需要安裝下列項目

安裝範例

取得原始碼並安裝依附元件

  1. 複製或下載 tfjs-examples 存放區。
  2. 變更至 getting-started 目錄:cd tfjs-examples/getting-started
  3. 安裝依附元件: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>

標頭中的 <script> 元素會載入 TensorFlow.js 程式庫,而主體結尾的 <script> 元素會載入機器學習指令碼。

如需其他取得 TensorFlow.js 依附元件的方法,請參閱設定教學課程

執行範例

執行範例並查看結果

  1. tfjs-examples/getting-started 目錄中,執行 yarn watch
  2. 在瀏覽器中前往 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 開發人員,正在尋找 Web ML 的實務簡介,請查看 Google 開發人員影片課程「Web 開發人員適用的機器學習」。本課程將說明如何在您的網站和應用程式中使用 TensorFlow.js。

前往 Web ML 課程

編寫 ML 程式,無需直接處理張量

如果您想開始使用機器學習,而無需管理最佳化工具或張量操作,請查看 ml5.js 程式庫。

ml5.js 程式庫是以 TensorFlow.js 為基礎建構,可在 Web 瀏覽器中透過簡潔易懂的 API 存取機器學習演算法和模型。

查看 ml5.js

安裝 TensorFlow.js

瞭解如何在 Web 瀏覽器或 Node.js 中安裝 TensorFlow.js 以進行實作。

安裝 TensorFlow.js

將預先訓練模型轉換為 TensorFlow.js

瞭解如何將預先訓練模型從 Python 轉換為 TensorFlow.js。

Keras 模型 GraphDef 模型

從現有的 TensorFlow.js 程式碼學習

tfjs-examples 存放區針對使用 TensorFlow.js 的各種 ML 工作提供小型範例實作。

在 GitHub 上檢視 tfjs-examples

將 TensorFlow.js 模型的行為視覺化

tfjs-vis 是一個小型程式庫,用於在 Web 瀏覽器中進行視覺化,適用於 TensorFlow.js。

在 GitHub 上檢視 tfjs-vis See Demo

準備資料以使用 TensorFlow.js 進行處理

TensorFlow.js 支援使用 ML 最佳做法處理資料。

檢視文件