简单介绍TensorFlow.js
简介

TensorFlow.js是一个开源的硬件加速JavaScript库,用于训练和部署机器学习模型。支援如下:
在浏览器中开发ML
使用灵活直观的API,使用低阶JavaScript线性代数库或高阶层API从头开始构建模型。
在Node.js中开发ML
Node.js执行时下使用相同的TensorFlow.js API执行本机TensorFlow。
执行现有模型
使用TensorFlow.js模型转换器直接在浏览器中执行预先存在的TensorFlow模型。
重新训练现有模型
使用连线到浏览器的感测器资料或其他客户端资料重新训练预先存在的ML模型。
目前github star 11K+,最新版本1.2.2, 如下截图:

TensorFlow.js 官网,如下截图
入门示例
html示例// 注意没有'import'语句。
// 定义线性回归模型
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
// 为训练准备模型:指定损失和优化程式。
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
// 为训练生成一些合成数据。
const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);
// 使用资料训练模型。
model.fit(xs, ys).then(() => {
// 开启浏览器devtools检视输出。
model.predict(tf.tensor2d([5], [1, 1])).print();
});
npm 示例
import * as tf from '@tensorflow/tfjs';
// 定义线性回归模型。
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
// 为训练准备模型:指定损失和优化程式。
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
// 为训练生成一些合成数据。
const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);
// 使用资料训练模型。
model.fit(xs, ys).then(() => {
model.predict(tf.tensor2d([5], [1, 1])).print();
});