TensorFlow.js 是一个开源库,允许你在浏览器和 Node.js 中运行 TensorFlow 模型。以下是一些 TensorFlow.js 的基础教程,帮助你快速上手。

快速开始

  1. 安装 TensorFlow.js 首先,你需要安装 TensorFlow.js。你可以通过以下命令安装:

    npm install @tensorflow/tfjs
    
  2. 创建一个简单的模型 下面是一个简单的线性回归模型的例子:

    const tf = require('@tensorflow/tfjs');
    
    const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
    const ys = tf.tensor2d([1, 2, 3, 4], [4, 1]);
    
    const model = tf.sequential();
    model.add(tf.layers.dense({units: 1, inputShape: [1]}));
    model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
    
    model.fit(xs, ys, {epochs: 250}).then(() => {
      console.log('Model trained!');
    });
    
  3. 模型评估 完成训练后,你可以使用以下代码来评估模型:

    model.evaluate(xs, ys).then((result) => {
      console.log('Mean squared error:', result);
    });
    

进阶教程

想要更深入地了解 TensorFlow.js?以下是一些进阶教程:

图像识别

想要在浏览器中使用 TensorFlow.js 进行图像识别?试试这个例子:

const img = new Image();
img.src = 'https://example.com/image.jpg';

img.onload = () => {
  const tensor = tf.fromPixels(img);
  const model = await tf.loadLayersModel('/path/to/your/model.json');
  const prediction = model.predict(tensor);
  console.log(prediction);
};

希望这些教程能帮助你更好地了解和使用 TensorFlow.js!🚀