TensorFlow.js 是一个开源库,允许你使用 JavaScript 在浏览器和 Node.js 中运行机器学习模型。这使得在客户端和服务器端进行机器学习推理成为可能。

特点

  • 浏览器兼容性:可以在所有主流浏览器中运行。
  • Node.js 支持:可以在 Node.js 环境中运行,适用于服务器端应用。
  • 模型转换:可以轻松地将 TensorFlow 模型转换为 TensorFlow.js 模型。
  • 社区支持:拥有活跃的社区和丰富的文档。

快速开始

要在浏览器中使用 TensorFlow.js,你可以通过以下步骤开始:

  1. 引入 TensorFlow.js 库。
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
  1. 创建一个 TensorFlow 模型。
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
  1. 训练模型。
const xs = tf.tensor2d([-1, 0, 1, 2, 3, 4], [6, 1]);
const ys = tf.tensor2d([-3, -1, 1, 3, 5, 7], [6, 1]);

model.fit(xs, ys, {epochs: 250}).then(() => {
  console.log('model.fit finished.');
});
  1. 使用模型进行预测。
model.predict(tf.tensor2d([10], [1, 1])).print();

深入学习

要了解更多关于 TensorFlow.js 的信息,请访问我们的官方文档

TensorFlow.js Logo