您可以使用 npm cli 工具或 yarn 安装 TensorFlow.js。
选项 1:使用原生 C++ 绑定安装 TensorFlow.js。
yarn add @tensorflow/tfjs-node
或
npm install @tensorflow/tfjs-node
选项 2:(仅限 Linux)如果您的系统搭载具备 CUDA 支持的 NVIDIA® GPU,请使用 GPU 软件包以获得更高性能。
yarn add @tensorflow/tfjs-node-gpu
或
npm install @tensorflow/tfjs-node-gpu
选项 3:安装纯净版 JavaScript。这是性能最慢的选项。
yarn add @tensorflow/tfjs
或
npm install @tensorflow/tfjs
请参见示例代码以了解 Node.js 用法
// Optional Load the binding: // Use '@tensorflow/tfjs-node-gpu' if running with GPU. require('@tensorflow/tfjs-node');
// Train a simple model: const model = tf.sequential(); model.add(tf.layers.dense({units: 100, activation: 'relu', inputShape: [10]})); model.add(tf.layers.dense({units: 1, activation: 'linear'})); model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
const xs = tf.randomNormal([100, 10]); const ys = tf.randomNormal([100, 1]);
model.fit(xs, ys, { epochs: 100, callbacks: { onEpochEnd: (epoch, log) => console.log(Epoch ${epoch}: loss = ${log.loss}
) } });
TypeScript
使用 TypeScript 时,如果您的项目使用严格的 null 检查,则可能需要在 tsconfig.json
文件中设置 skipLibCheck: true
,否则在编译过程中会遇到错误。