如何在Node.js(tensorflow.js)中训练模型?

Ale*_*lex 10 javascript training-data node.js tensorflow tensorflow.js

我想做一个图像分类器,但是我不懂python。Tensorflow.js使用我熟悉的javascript。可以用它训练模型吗?要这样做的步骤是什么?坦白说,我不知道从哪里开始。

我唯一想到的是如何加载“移动网络”,该网络显然是一组经过预先训练的模型,并使用该模型对图像进行分类:

const tf = require('@tensorflow/tfjs'),
      mobilenet = require('@tensorflow-models/mobilenet'),
      tfnode = require('@tensorflow/tfjs-node'),
      fs = require('fs-extra');

const imageBuffer = await fs.readFile(......),
      tfimage = tfnode.node.decodeImage(imageBuffer),
      mobilenetModel = await mobilenet.load();  

const results = await mobilenetModel.classify(tfimage);
Run Code Online (Sandbox Code Playgroud)

可以,但是对我没有用,因为我想使用带有创建的标签的图像来训练自己的模型。

=======================

说我有一堆图像和标签。如何使用它们训练模型?

const myData = JSON.parse(await fs.readFile('files.json'));

for(const data of myData){
  const image = await fs.readFile(data.imagePath),
        labels = data.labels;

  // how to train, where to pass image and labels ?

}
Run Code Online (Sandbox Code Playgroud)

gro*_*dzi 10

考虑示例https://codelabs.developers.google.com/codelabs/tfjs-training-classfication/#0

他们所做的是:

  • 拍摄一个大的 png 图像(图像的垂直串联)
  • 拿一些标签
  • 构建数据集(data.js)

然后训练

数据集的构建如下:

  1. 图片

大图像被分成 n 个垂直块。(n 是块大小)

考虑大小为 2 的 chunkSize。

给定图像 1 的像素矩阵:

  1 2 3
  4 5 6
Run Code Online (Sandbox Code Playgroud)

给定图像 2 的像素矩阵是

  7 8 9
  1 2 3
Run Code Online (Sandbox Code Playgroud)

结果数组将是 1 2 3 4 5 6 7 8 9 1 2 3(不知何故的一维串联)

所以基本上在处理结束时,你有一个大缓冲区代表

[...Buffer(image1), ...Buffer(image2), ...Buffer(image3)]

  1. 标签

对于分类问题,这种格式做了很多。他们不使用数字进行分类,而是使用布尔数组。为了预测 10 个类中的 7 个,我们会考虑 [0,0,0,0,0,0,0,1,0,0] // 1 in 7e position, array 0-indexed

你可以做什么来开始

  • 拍摄您的图像(及其相关标签)
  • 将图像加载到画布
  • 提取其关联的缓冲区
  • 将所有图像的缓冲区连接为一个大缓冲区。xs 就是这样。
  • 获取所有关联的标签,将它们映射为布尔数组,并将它们连接起来。

下面,我子类化MNistData::load(其余的可以原样(除了在 script.js 中你需要实例化你自己的类)

我仍然生成 28x28 图像,在上面写一个数字,并获得完美的准确性,因为我不包括噪音或自愿错误的标签。


import {MnistData} from './data.js'

const IMAGE_SIZE = 784;// actually 28*28...
const NUM_CLASSES = 10;
const NUM_DATASET_ELEMENTS = 5000;
const NUM_TRAIN_ELEMENTS = 4000;
const NUM_TEST_ELEMENTS = NUM_DATASET_ELEMENTS - NUM_TRAIN_ELEMENTS;


function makeImage (label, ctx) {
  ctx.fillStyle = 'black'
  ctx.fillRect(0, 0, 28, 28) // hardcoded, brrr
  ctx.fillStyle = 'white'
  ctx.fillText(label, 10, 20) // print a digit on the canvas
}

export class MyMnistData extends MnistData{
  async load() { 
    const canvas = document.createElement('canvas')
    canvas.width = 28
    canvas.height = 28
    let ctx = canvas.getContext('2d')
    ctx.font = ctx.font.replace(/\d+px/, '18px')
    let labels = new Uint8Array(NUM_DATASET_ELEMENTS*NUM_CLASSES)

    // in data.js, they use a batch of images (aka chunksize)
    // let's even remove it for simplification purpose
    const datasetBytesBuffer = new ArrayBuffer(NUM_DATASET_ELEMENTS * IMAGE_SIZE * 4);
    for (let i = 0; i < NUM_DATASET_ELEMENTS; i++) {

      const datasetBytesView = new Float32Array(
          datasetBytesBuffer, i * IMAGE_SIZE * 4, 
          IMAGE_SIZE);

      // BEGIN our handmade label + its associated image
      // notice that you could loadImage( images[i], datasetBytesView )
      // so you do them by bulk and synchronize after your promises after "forloop"
      const label = Math.floor(Math.random()*10)
      labels[i*NUM_CLASSES + label] = 1
      makeImage(label, ctx)
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      // END you should be able to load an image to canvas :)

      for (let j = 0; j < imageData.data.length / 4; j++) {
        // NOTE: you are storing a FLOAT of 4 bytes, in [0;1] even though you don't need it
        // We could make it with a uint8Array (assuming gray scale like we are) without scaling to 1/255
        // they probably did it so you can copy paste like me for color image afterwards...
        datasetBytesView[j] = imageData.data[j * 4] / 255;
      }
    }
    this.datasetImages = new Float32Array(datasetBytesBuffer);
    this.datasetLabels = labels

    //below is copy pasted
    this.trainIndices = tf.util.createShuffledIndices(NUM_TRAIN_ELEMENTS);
    this.testIndices = tf.util.createShuffledIndices(NUM_TEST_ELEMENTS);
    this.trainImages = this.datasetImages.slice(0, IMAGE_SIZE * NUM_TRAIN_ELEMENTS);
    this.testImages = this.datasetImages.slice(IMAGE_SIZE * NUM_TRAIN_ELEMENTS);
    this.trainLabels =
        this.datasetLabels.slice(0, NUM_CLASSES * NUM_TRAIN_ELEMENTS);// notice, each element is an array of size NUM_CLASSES
    this.testLabels =
        this.datasetLabels.slice(NUM_CLASSES * NUM_TRAIN_ELEMENTS);
  }

}
Run Code Online (Sandbox Code Playgroud)


mic*_*ico 8

我找到了一个教程 [1] 如何使用现有模型来训练新类。主要代码部分在这里:

index.html 头:

   <script src="https://unpkg.com/@tensorflow-models/knn-classifier"></script>
Run Code Online (Sandbox Code Playgroud)

index.html 正文:

    <button id="class-a">Add A</button>
    <button id="class-b">Add B</button>
    <button id="class-c">Add C</button>
Run Code Online (Sandbox Code Playgroud)

索引.js:

    const classifier = knnClassifier.create();

    ....

    // Reads an image from the webcam and associates it with a specific class
    // index.
    const addExample = async classId => {
           // Capture an image from the web camera.
           const img = await webcam.capture();

           // Get the intermediate activation of MobileNet 'conv_preds' and pass that
           // to the KNN classifier.
           const activation = net.infer(img, 'conv_preds');

           // Pass the intermediate activation to the classifier.
           classifier.addExample(activation, classId);

           // Dispose the tensor to release the memory.
          img.dispose();
     };

     // When clicking a button, add an example for that class.
    document.getElementById('class-a').addEventListener('click', () => addExample(0));
    document.getElementById('class-b').addEventListener('click', () => addExample(1));
    document.getElementById('class-c').addEventListener('click', () => addExample(2));

    ....
Run Code Online (Sandbox Code Playgroud)

主要思想是使用现有网络进行预测,然后用您自己的标签替换找到的标签。

完整代码在教程中。[2] 中的另一个有前途的、更先进的。它需要严格的预处理,所以我只放在这里,我的意思是它更高级。

资料来源:

[1] https://codelabs.developers.google.com/codelabs/tensorflowjs-teachablemachine-codelab/index.html#6

[2] https://towardsdatascience.com/training-custom-image-classification-model-on-the-browser-with-tensorflow-js-and-angular-f1796ed24934


edk*_*ked 5

首先,图像需要转换为张量。第一种方法是创建包含所有特征的张量(分别包含所有标签的张量)。仅当数据集包含少量图像时,才应采用这种方式。

  const imageBuffer = await fs.readFile(feature_file);
  tensorFeature = tfnode.node.decodeImage(imageBuffer) // create a tensor for the image

  // create an array of all the features
  // by iterating over all the images
  tensorFeatures = tf.stack([tensorFeature, tensorFeature2, tensorFeature3])
Run Code Online (Sandbox Code Playgroud)

标签将是一个数组,指示每个图像的类型

 labelArray = [0, 1, 2] // maybe 0 for dog, 1 for cat and 2 for birds
Run Code Online (Sandbox Code Playgroud)

现在需要创建标签的热编码

 tensorLabels = tf.oneHot(tf.tensor1d(labelArray, 'int32'), 3);
Run Code Online (Sandbox Code Playgroud)

一旦有了张量,就需要创建训练模型。这是一个简单的模型。

const model = tf.sequential();
model.add(tf.layers.conv2d({
  inputShape: [height, width, numberOfChannels], // numberOfChannels = 3 for colorful images and one otherwise
  filters: 32,
  kernelSize: 3,
  activation: 'relu',
}));
model.add(tf.layers.dense({units: 3, activation: 'softmax'}));
Run Code Online (Sandbox Code Playgroud)

然后可以训练模型

model.fit(tensorFeatures, tensorLabels)
Run Code Online (Sandbox Code Playgroud)

如果数据集包含很多图像,则需要创建一个tfDataset。这个答案讨论了为什么。

const genFeatureTensor = image => {
      const imageBuffer = await fs.readFile(feature_file);
      return tfnode.node.decodeImage(imageBuffer)
}

const labelArray = indice => Array.from({length: numberOfClasses}, (_, k) => k === indice ? 1 : 0)

function* dataGenerator() {
  const numElements = numberOfImages;
  let index = 0;
  while (index < numFeatures) {
    const feature = genFeatureTensor ;
    const label = tf.tensor1d(labelArray(classImageIndex))
    index++;
    yield {xs: feature, ys: label};
  }
}

const ds = tf.data.generator(dataGenerator);
Run Code Online (Sandbox Code Playgroud)

并使用model.fitDataset(ds)训练模型

  • @Alex您能否用模型摘要和您正在加载的图像的形状更新您的问题?所有图像需要具有相同的形状,否则需要调整图像大小以进行训练 (3认同)

mic*_*ico 5

TL; 博士

MNIST 是图像识别 Hello World。学了之后,脑子里的这些问题就很容易解决了。


问题设置:

你写的主要问题是

 // how to train, where to pass image and labels ?
Run Code Online (Sandbox Code Playgroud)

在您的代码块内。对于那些我从 Tensorflow.js 示例部分的示例中找到的完美答案:MNIST 示例。我下面的链接有它的纯 javascript 和 node.js 版本以及维基百科解释。我将在回答您脑海中的主要问题所需的级别上进行讲解,我还将添加一些观点,您自己的图像和标签与 MNIST 图像集和使用它的示例有何关系。

第一件事:

代码片段。

在何处传递图像(Node.js 示例)

async function loadImages(filename) {
  const buffer = await fetchOnceAndSaveToDiskWithBuffer(filename);

  const headerBytes = IMAGE_HEADER_BYTES;
  const recordBytes = IMAGE_HEIGHT * IMAGE_WIDTH;

  const headerValues = loadHeaderValues(buffer, headerBytes);
  assert.equal(headerValues[0], IMAGE_HEADER_MAGIC_NUM);
  assert.equal(headerValues[2], IMAGE_HEIGHT);
  assert.equal(headerValues[3], IMAGE_WIDTH);

  const images = [];
  let index = headerBytes;
  while (index < buffer.byteLength) {
    const array = new Float32Array(recordBytes);
    for (let i = 0; i < recordBytes; i++) {
      // Normalize the pixel values into the 0-1 interval, from
      // the original 0-255 interval.
      array[i] = buffer.readUInt8(index++) / 255;
    }
    images.push(array);
  }

  assert.equal(images.length, headerValues[1]);
  return images;
}
Run Code Online (Sandbox Code Playgroud)

笔记:

MNIST 数据集是一个巨大的图像,其中在一个文件中有多个图像,例如拼图中的图块,每个图像大小相同,并排,就像 x 和 y 坐标表中的框。每个框有一个样本,标签数组中对应的 x 和 y 具有标签。从这个例子来看,把它转换成几种文件格式没什么大不了的,这样实际上一次只有一张图片交给while循环来处理。

标签:

async function loadLabels(filename) {
  const buffer = await fetchOnceAndSaveToDiskWithBuffer(filename);

  const headerBytes = LABEL_HEADER_BYTES;
  const recordBytes = LABEL_RECORD_BYTE;

  const headerValues = loadHeaderValues(buffer, headerBytes);
  assert.equal(headerValues[0], LABEL_HEADER_MAGIC_NUM);

  const labels = [];
  let index = headerBytes;
  while (index < buffer.byteLength) {
    const array = new Int32Array(recordBytes);
    for (let i = 0; i < recordBytes; i++) {
      array[i] = buffer.readUInt8(index++);
    }
    labels.push(array);
  }

  assert.equal(labels.length, headerValues[1]);
  return labels;
}
Run Code Online (Sandbox Code Playgroud)

笔记:

这里,标签也是文件中的字节数据。在 Javascript 世界中,根据您在起点的方法,标签也可以是一个 json 数组。

训练模型:

await data.loadData();

  const {images: trainImages, labels: trainLabels} = data.getTrainData();
  model.summary();

  let epochBeginTime;
  let millisPerStep;
  const validationSplit = 0.15;
  const numTrainExamplesPerEpoch =
      trainImages.shape[0] * (1 - validationSplit);
  const numTrainBatchesPerEpoch =
      Math.ceil(numTrainExamplesPerEpoch / batchSize);
  await model.fit(trainImages, trainLabels, {
    epochs,
    batchSize,
    validationSplit
  });
Run Code Online (Sandbox Code Playgroud)

笔记:

model.fit是执行此操作的实际代码行:训练模型。

整个事情的结果:

  const {images: testImages, labels: testLabels} = data.getTestData();
  const evalOutput = model.evaluate(testImages, testLabels);

  console.log(
      `\nEvaluation result:\n` +
      `  Loss = ${evalOutput[0].dataSync()[0].toFixed(3)}; `+
      `Accuracy = ${evalOutput[1].dataSync()[0].toFixed(3)}`);
Run Code Online (Sandbox Code Playgroud)

笔记:

在数据科学中,也是这一次,最令人着迷的部分是了解模型在新数据测试和没有标签的情况下有多好,它可以标记或不标记吗?因为那是现在向我们打印一些数字的评估部分。

损失和准确性:[4]

损失越低,模型越好(除非模型过度拟合训练数据)。损失是在训练和验证时计算的,它的相互作用是模型对这两组的表现。与准确性不同,损失不是百分比。它是训练或验证集中每个示例的错误总和。

..

模型的准确率通常是在模型参数学习和固定之后确定的,并且没有发生学习。然后将测试样本馈送到模型中,并在与真实目标进行比较后记录模型所犯的错误数(零一损失)。


更多信息:

在 github 页面中,在 README.md 文件中,有一个教程链接,其中更详细地解释了 github 示例中的所有内容。


[1] https://github.com/tensorflow/tfjs-examples/tree/master/mnist

[2] https://github.com/tensorflow/tfjs-examples/tree/master/mnist-node

[3] https://en.wikipedia.org/wiki/MNIST_database

[4]如何解释机器学习模型的“loss”和“accuracy”