TensorFlow.js 教程

什麼是 TensorFlow.js?
Tensorflow 是一個流行的 JavaScript 庫,用於 機器學習。
Tensorflow 允許我們在 瀏覽器 中訓練和部署機器學習。
Tensorflow 允許我們將機器學習功能新增到任何 Web 應用程式。
使用 TensorFlow
要使用 TensorFlow.js,請將以下指令碼標籤新增到您的 HTML 檔案中
示例
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.6.0/dist/tf.min.js"></script>
如果您想始終使用最新版本,請刪除版本號
示例 2
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
TensorFlow 由 Google Brain Team 開發,用於內部 Google 使用,並於 2015 年釋出為開源軟體。
2019 年 1 月,Google 開發者釋出了 TensorFlow.js,這是 TensorFlow 的 JavaScript 實現。
Tensorflow.js 的設計旨在提供與用 Python 編寫的原始 TensorFlow 庫相同的功能。
張量
TensorFlow.js 是一個用於定義和操作 張量 的 JavaScript 庫。
TensorFlow.js 中的主要資料型別是 Tensor。
Tensor 與多維陣列非常相似。
Tensor 包含一個或多個維度中的值

Tensor 具有以下主要屬性
屬性 | 描述 |
---|---|
dtype | 資料型別 |
rank | 維度數量 |
shape | 每個維度的尺寸 |
在機器學習中,“維度”有時與“秩”互換使用。
[10, 5] 是一個 2 維張量或 2 階張量。
此外,“維度”一詞可以指代一維的大小。
示例:在 2 維張量 [10, 5] 中,第一個維度的維度是 10。
建立張量
TensorFlow 中的主要資料型別是 Tensor。
Tensor 可以使用 tf.tensor() 方法從任何 N 維陣列建立
示例 1
const myArr = [[1, 2, 3, 4]];
const tensorA = tf.tensor(myArr);
示例 2
const myArr = [[1, 2], [3, 4]];
const tensorA = tf.tensor(myArr);
示例 3
const myArr = [[1, 2], [3, 4], [5, 6]];
const tensorA = tf.tensor(myArr);
張量形狀
Tensor 也可以從 陣列 和 shape 引數建立
示例 1
const myArr = [1, 2, 3, 4]
const shape = [2, 2];
const tensorA = tf.tensor(myArr, shape);
示例 2
const tensorA = tf.tensor([1, 2, 3, 4], [2, 2]);
示例 3
const myArr = [[1, 2], [3, 4]];
const shape = [2, 2];
const tensorA = tf.tensor(myArr, shape);
檢索張量值
您可以使用 tensor.data() 獲取張量背後的 資料
示例
const myArr = [[1, 2], [3, 4]];
const shape = [2, 2];
const tensorA = tf.tensor(myArr, shape);
tensorA.data().then(data => display(data));
function display(data) {
document.getElementById("demo").innerHTML = data;
}
您可以使用 tensor.array() 獲取張量背後的 陣列
示例
const myArr = [[1, 2], [3, 4]];
const shape = [2, 2];
const tensorA = tf.tensor(myArr, shape);
tensorA.array().then(array => display(array[0]));
function display(data) {
document.getElementById("demo").innerHTML = data;
}
const myArr = [[1, 2], [3, 4]];
const shape = [2, 2];
const tensorA = tf.tensor(myArr, shape);
tensorA.array().then(array => display(array[1]));
function display(data) {
document.getElementById("demo").innerHTML = data;
}
您可以使用 tensor.rank 獲取張量的 秩
示例
const myArr = [1, 2, 3, 4];
const shape = [2, 2];
const tensorA = tf.tensor(myArr, shape);
document.getElementById("demo").innerHTML = tensorA.rank;
您可以使用 tensor.shape 獲取張量的 形狀
示例
const myArr = [1, 2, 3, 4];
const shape = [2, 2];
const tensorA = tf.tensor(myArr, shape);
document.getElementById("demo").innerHTML = tensorA.shape;
您可以使用 tensor.dtype 獲取張量的 資料型別
示例
const myArr = [1, 2, 3, 4];
const shape = [2, 2];
const tensorA = tf.tensor(myArr, shape);
document.getElementById("demo").innerHTML = tensorA.dtype;
張量資料型別
Tensor 可以具有以下資料型別
- bool
- int32
- float32(預設)
- complex64
- string
建立張量時,可以將資料型別指定為第三個引數
示例
const myArr = [1, 2, 3, 4];
const shape = [2, 2];
const tensorA = tf.tensor(myArr, shape, "int32");