TensorFlow.js 教程
什么是 TensorFlow.js?
一个流行的 JavaScript 库,用于机器学习。
让我们在浏览器中训练和部署机器学习模型。
让我们将机器学习功能添加到任何 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 团队 开发供 Google 内部使用,但于 2015 年作为开放软件发布。
2019 年 1 月,Google 开发人员发布了 TensorFlow.js,这是 TensorFlow 的 JavaScript 实现。
Tensorflow.js 旨在提供与用 Python 编写的原始 TensorFlow 库相同的功能。
张量
TensorFlow.js 是一个 JavaScript 库 定义和操作 张量。
张量与多维数组非常相似。
张量包含(一个或多个)维度形状的数值。
张量具有以下主要属性:
房产 | 描述 |
---|---|
dtype | 数据类型 |
rank | 维数 |
shape | 每个维度的大小 |
创建张量
可以从任何 N 维数组创建张量:
实例 1
const tensorA = tf.tensor([[1, 2], [3, 4]]);
实例 2
const tensorA = tf.tensor([[1, 2], [3, 4], [5, 6]]);
张量形状
张量也可以由 array 和 shape 参数创建:
实例1
const shape = [2, 2];
const tensorA = tf.tensor([1, 2, 3, 4], shape);
实例2
const tensorA = tf.tensor([1, 2, 3, 4], [2, 2]);
实例3
const tensorA = tf.tensor([[1, 2], [3, 4]], [2, 2]);
张量数据类型
张量可以有以下数据类型:
- bool
- int32
- float32 (default)
- complex64
- string
创建张量时,可以指定数据类型为第三个参数:
实例
const tensorA = tf.tensor([1, 2, 3, 4], [2, 2], "int32");
/*
Results:
tensorA.rank = 2
tensorA.shape = 2,2
tensorA.dtype = int32
*/
检索张量值
您可以使用 tensor.data() 获取张量背后的数据:
实例
const tensorA = tf.tensor([[1, 2], [3, 4]]);
tensorA.data().then(data => display(data));
// 返回: 1,2,3,4
function display(data) {
document.getElementById("demo").innerHTML = data;
}
您可以使用 tensor.array() 获取张量后面的数组:
实例
const tensorA = tf.tensor([[1, 2], [3, 4]]);
tensorA.array().then(array => display(array[0]));
// 返回: 1,2
function display(data) {
document.getElementById("demo").innerHTML = data;
}