在浏览器中开发 ML 使用灵活直观的 API,使用低级 JavaScript 线性代数库或高级层 API 从头开始构建模型。
在 Node.js 中开发 ML 在 Node.js 运行时下使用相同的 TensorFlow.js API 执行原生 TensorFlow。
运行现有模型 使用 TensorFlow.js 模型转换器在浏览器中运行预先存在的 TensorFlow 模型。
重新训练现有 模型使用连接到浏览器或其他客户端数据的传感器数据重新训练预先存在的 ML 模型。
该存储库包含组合多个包的逻辑和脚本。
[hidecontent type="logged" desc="隐藏内容:登录后可查看"]
后端/平台:
如果您关心包的大小,您可以单独导入这些包。
如果您正在寻找 Node.js 支持,请查看TensorFlow.js Node 目录。
请务必查看与 TensorFlow.js 相关的所有项目库。
请务必查看我们的模型存储库,我们在 NPM 上托管预训练模型。
在您的 JavaScript 项目中获取 TensorFlow.js 的主要方法有两种:通过脚本标签 或从NPM安装它并使用Parcel、 WebPack或Rollup 等构建工具。
将以下代码添加到 HTML 文件中:
<html>
<head>
<!-- Load TensorFlow.js -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js"> </script>
<!-- Place your code in the script tag below. You can also use an external .js file -->
<script>
// Notice there is no 'import' statement. 'tf' is available on the index-page
// because of the script tag above.
// Define a model for linear regression.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
// Prepare the model for training: Specify the loss and the optimizer.
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
// Generate some synthetic data for training.
const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);
// Train the model using the data.
model.fit(xs, ys).then(() => {
// Use the model to do inference on a data point the model hasn't seen before:
// Open the browser devtools to see the output
model.predict(tf.tensor2d([5], [1, 1])).print();
});
</script>
</head>
<body>
</body>
</html>
在浏览器中打开该 HTML 文件,代码应该可以运行了!
使用yarn 或 npm将 TensorFlow.js 添加到您的项目中。注意:因为我们使用 ES2017 语法(例如import
),所以此工作流假定您使用现代浏览器或捆绑器/转译器将您的代码转换为旧浏览器可以理解的代码。查看我们的 示例 ,了解我们如何使用Parcel构建代码。但是,您可以自由使用您喜欢的任何构建工具。
import * as tf from '@tensorflow/tfjs';
// Define a model for linear regression.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
// Prepare the model for training: Specify the loss and the optimizer.
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
// Generate some synthetic data for training.
const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);
// Train the model using the data.
model.fit(xs, ys).then(() => {
// Use the model to do inference on a data point the model hasn't seen before:
model.predict(tf.tensor2d([5], [1, 1])).print();
});
我们支持从以下平台移植预训练模型:
请参考以下:
TensorFlow.js是 TensorFlow生态系统的一部分。欲了解更多信息:
tfjs
上的标签。[/hidecontent]