TensorFlow.js 是 TensorFlow 的 JavaScript 实现,支持在浏览器或 Node.js 环境中训练和部署机器学习模型。
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs">script>
或使用 包管理器:
npm install @tensorflow/tfjs
npm install @tensorflow/tfjs-node
Node.js 环境下还可以选择
@tensorflow/tfjs-node-gpu
获得 GPU 加速支持。
const tensor = tf.tensor([1, 2, 3, 4], [2, 2]);
tensor.print();
输出:
[[1, 2],
[3, 4]]
TensorFlow.js 提供了丰富的张量运算,如矩阵乘法、加减、转置等。
const a = tf.tensor([[1, 2], [3, 4]]);
const b = tf.tensor([[5, 6], [7, 8]]);
const result = tf.matMul(a, b);
result.print();
const model = tf.sequential();
model.add(tf.layers.dense({units: 32, inputShape: [50], activation: 'relu'}));
model.add(tf.layers.dense({units: 1, activation: 'linear'}));
const input = tf.input({shape: [50]});
const dense1 = tf.layers.dense({units: 32, activation: 'relu'}).apply(input);
const output = tf.layers.dense({units: 1, activation: 'linear'}).apply(dense1);
const model = tf.model({inputs: input, outputs: output});
model.compile({
optimizer: 'sgd',
loss: 'meanSquaredError'
});
// 假设 xs 和 ys 是 Tensor
await model.fit(xs, ys, {
epochs: 10,
batchSize: 32
});
const model = await tf.loadLayersModel('https://example.com/model.json');
await model.save('downloads://my-model'); // 浏览器下载
await model.save('file://path-to-save'); // Node.js 保存到文件系统
TensorFlow.js 不会自动回收内存,需手动处理:
tf.tidy(() => {
const y = tf.add(a, b);
y.print();
}); // 自动释放内部中间张量
手动释放:
tensor.dispose();
场景 | 技术栈 |
---|---|
浏览器推理/训练 | TensorFlow.js + WebGL/WebGPU |
Node.js 推理/训练 | TensorFlow.js Node Bindings |
混合端部署 | 将模型转换成不同端适用格式 |
张量是 TensorFlow.js 的核心数据结构,用于存储和操作数据。TensorFlow.js 提供了丰富的运算 API 实现高效的数值计算。
float32
(默认)、int32
、bool
、complex64
、string
。维度 | 含义 | 示例 |
---|---|---|
0D | 标量 | tf.scalar(42) |
1D | 向量 | tf.tensor1d([1, 2, 3]) |
2D | 矩阵 | tf.tensor2d([[1, 2], [3, 4]]) |
3D+ | 高维数组(张量) | tf.tensor3d([...]) |
const t1 = tf.tensor([1, 2, 3, 4], [2, 2]);
const t2 = tf.tensor2d([[1, 2], [3, 4]]);
tf.zeros([2, 3]).print();
tf.ones([2, 2]).print();
tf.eye(3).print(); // 单位矩阵
tf.range(0, 10, 2).print(); // 0, 2, 4, 6, 8
TensorFlow.js 提供无副作用的函数式 API,每次运算都会返回新张量。
const a = tf.tensor([1, 2]);
const b = tf.tensor([3, 4]);
tf.add(a, b).print(); // [4, 6]
tf.mul(a, b).print(); // [3, 8]
const m1 = tf.tensor2d([[1, 2], [3, 4]]);
const m2 = tf.tensor2d([[5, 6], [7, 8]]);
tf.matMul(m1, m2).print();
const x = tf.tensor1d([1, 2, 3]);
const y = tf.scalar(2);
tf.mul(x, y).print(); // 每个元素乘2
const t = tf.tensor2d([[1,2,3],[4,5,6]]);
t.reshape([3,2]).print();
t.slice([0,1], [2,2]).print(); // 从 (0,1) 开始取 2x2 子矩阵
张量和中间结果默认不会自动释放,需要手动管理。
tf.tidy(() => {
const a = tf.tensor1d([1, 2, 3]);
const b = a.square();
b.print();
}); // 离开 tidy 后自动释放 a 和 b
const t = tf.tensor([1, 2, 3]);
t.dispose();
console.log(tf.memory());
某些操作是异步的,例如从张量取值:
const t = tf.tensor([1, 2, 3]);
t.data().then(data => console.log(data)); // TypedArray
t.array().then(arr => console.log(arr)); // 普通数组
在 Node.js 或浏览器 async/await 环境:
const data = await t.data();
console.log(data);
@tensorflow/tfjs-node
或 @tensorflow/tfjs-node-gpu
获得更高性能。MobileNet 是一种轻量级卷积神经网络,用于高效的图像分类与特征提取,适合在浏览器、移动端和边缘设备运行。
npm install @tensorflow/tfjs
或 在 HTML 中引入:
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs">script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet">script>
import * as mobilenet from '@tensorflow-models/mobilenet';
// 或在浏览器中
// const mobilenet = window.mobilenet;
const model = await mobilenet.load({
version: 2, // MobileNet V2
alpha: 1.0 // 模型宽度系数(0.25 ~ 1.0)
});
const img = document.getElementById('img'); // HTMLImageElement 或 Canvas
const predictions = await model.classify(img);
console.log(predictions);
// [
// {className: 'Egyptian cat', probability: 0.75},
// {className: 'tabby, tabby cat', probability: 0.15},
// ...
// ]
const activation = model.infer(img, true);
activation.print(); // 返回一个张量,可用于后续自定义分类器训练
参数 | 含义 | 默认值 |
---|---|---|
version |
模型版本(1 或 2) | 1 |
alpha |
宽度缩放系数,减小模型大小 | 1.0(完整模型) |
推荐:
- 快速推理:
version: 2, alpha: 0.5
- 更高准确率:
version: 2, alpha: 1.0
tf.browser.fromPixels(img)
)tf.tidy
自动释放中间张量内存<img id="img" src="cat.jpg" />
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs">script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet">script>
<script>
async function run() {
const img = document.getElementById('img');
const model = await mobilenet.load({version: 2, alpha: 0.75});
const predictions = await model.classify(img);
console.log(predictions);
}
run();
script>
TensorFolw.js
张量和运算
MobileNet 模型