TensorFlowJS 基础
1、什么是tfjs
TensorFlow.js 是一个 JavaScript 库,用于在浏览器
和 Node.js 训练和部署机器学习模型
。
了解开始的更多方式,请参阅下面的部分。
2、学习大纲
3、数据
张量(Tensor)和变量(Variable)是 TensorFlow.js 中数据的主要表现形式。
3.1、张量(Tensor)
定义: 一组数值形成一个或多
个维
度的数组
。 张量实例具有定义数组形状的形状属性。张量是 TensorFlow.js 中数据的中心单位
,也是 Tensorflow.js 中数据的主要表现形式
(可以简单的理解为 n 为数组,是数据的中心单位)
3.1.1 shape 参数
张量是 n 维数组,shape 就是说明张量具体是几维几行几列的数组,具体使用,如下所示:
// 张量
const tf = require('@tensorflow/tfjs');
const shape = [2, 3] // 2维2行3列
const a = tf.tensor([1, 2, 3, 4, 5, 6], shape)
a.print()
// 输出:[[1, 2, 3]
// ,[4, 5, 6]]
const b = tf.tensor([[1, 2, 3] ,[4, 5, 6]])
b.print()
// 输出:[[1, 2, 3]
// ,[4, 5, 6]]
3.1.2 维度数据
虽然可以直接使用tensor方法,但还是推荐使用下面的函数来增强代码的可读性
tf.scalar(零维), tf.tensor1d(一维), tf.tensor2d(二维), tf.tensor3d(三维)、tf.tensor4d(四维)以及 tf.ones(值全是1)或者tf.zeros(值全是0)
// 张量维度
const tf = require('@tensorflow/tfjs');
// 0维
const a = tf.scalar(3.14)
a.print()
// 2维
const b = tf.tensor2d([[2, 3, 4], [5, 6, 7]])
b.print()
// 全是0 shape
const c = tf.zeros([2, 3])
c.print()
// 全是1 shape
const d = tf.ones([3, 5])
d.print()
在 TensorFlow.js 中,张量是不变的; 一旦创建你就不能改变它们的值。 但是,您可以对它们执行操作来生成新的张量。
3.2、变量(Variable)
Variables 变量是通过张量
进行初始化
得到的。不像 Tensor 的值不可变,变量的值是可变
的。你可以使用变量的 assign
方法分配
一个新的 tensor
到这个变量上,这是变量就会改变:
// 变量
const tf = require('@tensorflow/tfjs');
const initValue = tf.zeros([5]);
const a = tf.variable(initValue); // 初始化a
a.print(); // 输出: [0, 0, 0, 0, 0]
const updatValue = tf.tensor1d([0, 1, 0, 1, 0]);
a.assign(updatValue); // 更新 a的值
a.print(); // 输出: [0, 1, 0, 1, 0]
由此我们可以得出一个结论:变量由张量生成,且张量不可变而变量可变。
4、模型
- 在 Tensorflow.js 中,一个模型就是一个给定一些输入将会产生特定的输出的函数。简单来说,
一个模型就是一个函数,只是它完成了特定的任务
- 在 TensorFlow.js 中有两种方式来创建模型:
- 一种是通过操作(ops)来直接完成模型本身所做的工作
- 另外一种就是通过高级API
tf.model
来创建一个模型(神经网络
),显然第二种是更容易的
4.1、ops创建模型
// Ops创建模型
const tf = require('@tensorflow/tfjs');
function predict(input) {
// y = a * x ^ 2 + b * x + c 二元一次方程
return tf.tidy(() => {
const x = tf.scalar(input);
const ax2 = a.mul(x.square());
const bx = b.mul(x);
const y = ax2.add(bx).add(c);
return y;
});
}
// tf.scalar(零维)
const a = tf.scalar(2);
const b = tf.scalar(4);
const c = tf.scalar(8);
const result = predict(2); // 2 * x ^ 2 + 4 * x + 8
result.print() // 24
如上所示,我们定义的 predict 函数就是一个模型,对于给定的输入
,我们就可以得到预测的输出
。
注:所有的数字都需要经过tf.scalar() 张量
处理
4.2、tf.model创建模型
用 TensorFlow.js 中的 tf.model 方法(这里的 model 并不是真正可以调用的方法,而是一个总称
,比如实际上可以调用的是 tf.sequential 模型),这在深度学习中是非常流行的概念。 下面的代码就创建了 tf.sequential 模型:
//线性模型类
const tf = require('@tensorflow/tfjs');
export default class LinearModel {
// 训练模型
async trainModel(xs, ys) {
// 创建神经网络模型
this.linearModel = tf.sequential();
// 添加一层
this.linearModel.add(tf.layers.dense({
units: 1, // 输出空间的纬度
inputShape: [1], // 只有一个参数
}));
this.linearModel.compile({
loss: 'meanSquaredError', //均方误差
optimizer: 'sgd', // 随机梯度下降
});
// 开始模型训练
await this.linearModel.fit(
tf.tensor2d(xs),
tf.tensor2d(ys),
{ epochs: 1000 }
);
}
predict(value) {
return Array.from(
this.linearModel
.predict(tf.tensor2d([value], [1, 1]))
.dataSync()
)
}
async save() {
await this.linearModel.save('localstorage://linearModel');
// await this.linearModel.save('downloads://linearModel');
console.log('训练完成!')
}
}
5、内存管理
因为 TensorFlow.js 使用了GPU来加速数学运算,因此当 tensorflow 处理张量和变量时就有必要来管理 GPU 内存。在 TensorFlow.js 中,我们可以通过dispose
和tf.tidy
这两种方法来管理内存
5.1、dispose
您可以在张量或变量上调用dispose来清除它并释放其GPU内存:
const x = tf.tensor2d([[0, 2], [4, 6]]);
const x2 = x.square();
x.dispose();
x2.dispose();
5.2、tf.tidy
进行大量的张量操作时使用dispose可能会很麻烦。 TensorFlow.js提供了另一个函数tf.tidy,它对JavaScript中的常规范围起到类似的作用,不同的是它针对GPU支持的张量
tf.tidy执行一个函数并清除所有创建的中间张量,释放它们的GPU内存。 它不清除内部函数的返回值。
const average = tf.tidy(() => {
const y = tf.tensor1d([1, 2, 3, 4]);
const z = tf.ones([4]);
return y.sub(z).square().mean(); // (y-z)^2/n
});
average.print()
参考文档:怎样用 TensorFlow.js 创建基本的 AI 模型?-js教程-PHP中文网 参考文档:TensorFlow.js (google.cn) 参考文档:TensorflowJS_肖朋伟-