本文件說明如何在瀏覽器環境和 Node.js 中安裝及使用 TensorFlow.js。
瀏覽器設定
有兩種建議的方式可在以瀏覽器為基礎的專案中使用 TensorFlow.js
如果您是網頁開發新手,或之前未使用過 JavaScript 組建工具,建議您先試試看指令碼標記方法。如果您通常會將網頁資產組合或處理,或您計畫編寫較大型的應用程式,則應考慮使用組建工具。
使用指令碼標記
若要使用指令碼標記取得 TensorFlow.js,請將下列程式碼新增至您的主要 HTML 檔案
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest/dist/tf.min.js"></script>
以下範例說明如何在瀏覽器中定義及訓練模型
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>TensorFlow.js browser example</title>
<!-- Load TensorFlow.js from a script tag -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest/dist/tf.min.js"></script>
</head>
<body>
<h1>TensorFlow.js example</h1>
<h2>Open the console to see the results.</h2>
<script>
// Define a model for linear regression. The script tag makes `tf` available
// as a global variable.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
// Generate some synthetic data for training.
const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);
// Train the model using the data.
model.fit(xs, ys, {epochs: 10}).then(() => {
// Use the model to do inference on a data point the model hasn't seen before:
model.predict(tf.tensor2d([5], [1, 1])).print();
// Open the browser devtools to see the output
});
</script>
</body>
</html>
若要執行範例,請按照下列步驟操作
- 將範例文件儲存到名為
index.html
的檔案中。 按兩下
index.html
以在預設瀏覽器中開啟。或者,您可以在與
index.html
相同的目錄中執行npx http-server
來提供index.html
。(如果您收到安裝http-server
的權限提示,請輸入y
。)然後在瀏覽器中前往https://127.0.0.1:8080
。開啟瀏覽器控制台以查看指令碼的輸出。
重新整理頁面以查看新的 (而且很可能不同的) 預測。
從 NPM 安裝
若要從 NPM 安裝 TensorFlow.js,請使用 npm CLI 或 yarn。
NPM
npm install @tensorflow/tfjs
Yarn
yarn add @tensorflow/tfjs
以下範例說明如何匯入 TensorFlow.js、定義模型,以及訓練模型。
import * as tf from '@tensorflow/tfjs';
// Define a model for linear regression.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
// Generate some synthetic data for training.
const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);
// Train the model using the data.
model.fit(xs, ys, {epochs: 10}).then(() => {
// Use the model to do inference on a data point the model hasn't seen before:
model.predict(tf.tensor2d([5], [1, 1])).print();
// Open the browser devtools to see the output
});
Node.js 設定
若要在 Node.js 中使用 TensorFlow.js,請使用 npm CLI 或 yarn 完成下列其中一個安裝選項。
若要進一步瞭解如何在 Node.js 中使用 TensorFlow.js,請參閱 Node.js 指南。如需其他安裝資訊,請參閱 TensorFlow.js for Node.js 存放區。
選項 1:安裝具有原生 C++ 繫結的 TensorFlow.js。
tfjs-node
模組在 Node.js 執行階段下的 JavaScript 應用程式中提供原生 TensorFlow 執行,並由 TensorFlow C 二進位檔加速。
安裝 tfjs-node
NPM
npm install @tensorflow/tfjs-node
Yarn
yarn add @tensorflow/tfjs-node
以下範例說明如何匯入 tfjs-node
、定義模型,以及訓練模型。
// Use `tfjs-node`. Note that `tfjs` is imported indirectly by `tfjs-node`.
const tf = require('@tensorflow/tfjs-node');
// Define a simple model.
const model = tf.sequential();
model.add(tf.layers.dense({units: 100, activation: 'relu', inputShape: [10]}));
model.add(tf.layers.dense({units: 1, activation: 'linear'}));
model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
const xs = tf.randomNormal([100, 10]);
const ys = tf.randomNormal([100, 1]);
// Train the model.
model.fit(xs, ys, {
epochs: 100,
callbacks: {
onEpochEnd: (epoch, log) => console.log(`Epoch ${epoch}: loss = ${log.loss}`)
}
});
選項 2:安裝適用於 GPU 的 TensorFlow.js
(僅限 Linux) 如果您的系統具有支援 CUDA 的 NVIDIA® GPU,則可以使用 GPU 套件來提升效能。
安裝 tfjs-node-gpu
NPM
npm install @tensorflow/tfjs-node-gpu
Yarn
yarn add @tensorflow/tfjs-node-gpu
以下範例說明如何匯入 tfjs-node-gpu
、定義模型,以及訓練模型。
// Use `tfjs-node-gpu`. Note that `tfjs` is imported indirectly by `tfjs-node-gpu`.
const tf = require('@tensorflow/tfjs-node-gpu');
// Define a simple model.
const model = tf.sequential();
model.add(tf.layers.dense({units: 100, activation: 'relu', inputShape: [10]}));
model.add(tf.layers.dense({units: 1, activation: 'linear'}));
model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
const xs = tf.randomNormal([100, 10]);
const ys = tf.randomNormal([100, 1]);
// Train the model.
model.fit(xs, ys, {
epochs: 100,
callbacks: {
onEpochEnd: (epoch, log) => console.log(`Epoch ${epoch}: loss = ${log.loss}`)
}
});
選項 3:安裝純 JavaScript 版本
tfjs
模組與您在瀏覽器中使用的套件相同。就效能而言,這是 Node.js 選項中最慢的。
安裝 tfjs
NPM
npm install @tensorflow/tfjs
Yarn
yarn add @tensorflow/tfjs
以下範例說明如何匯入 tfjs
、定義模型,以及訓練模型。
// Use `tfjs`.
const tf = require('@tensorflow/tfjs');
// Define a simple model.
const model = tf.sequential();
model.add(tf.layers.dense({units: 100, activation: 'relu', inputShape: [10]}));
model.add(tf.layers.dense({units: 1, activation: 'linear'}));
model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
const xs = tf.randomNormal([100, 10]);
const ys = tf.randomNormal([100, 1]);
// Train the model.
model.fit(xs, ys, {
epochs: 100,
callbacks: {
onEpochEnd: (epoch, log) => console.log(`Epoch ${epoch}: loss = ${log.loss}`)
}
});
TypeScript
如果您在 TypeScript 專案中使用 TensorFlow.js,而且已啟用嚴格的 Null 值檢查,則可能需要在 tsconfig.json
中設定 skipLibCheck: true
,以避免編譯期間發生錯誤。