如何在Node.js(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);

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

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

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

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 ?

}
karen8848 回答:如何在Node.js(tensorflow.js)中训练模型?

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

  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])

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

 labelArray = [0,1,2] // maybe 0 for dog,1 for cat and 2 for birds

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

 tensorLabels = tf.oneHot(tf.tensor1d(labelArray,'int32'),3);

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

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.flatten()),model.add(tf.layers.dense({units: 3,activation: 'softmax'}));

然后可以训练模型

model.fit(tensorFeatures,tensorLabels)

如果数据集包含很多图像,则需要创建一个tfDataset。 answer讨论了原因。

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(imagePath) ;
    const label = tf.tensor1d(labelArray(classImageIndex))
    index++;
    yield {xs: feature,ys: label};
  }
}

const ds = tf.data.generator(dataGenerator);

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


以上内容是针对nodejs的培训。要在浏览器中进行这样的处理,可以将genFeatureTensor编写如下:

function load(url){
  return new Promise((resolve,reject) => {
    const im = new Image()
        im.crossOrigin = 'anonymous'
        im.src = 'url'
        im.onload = () => {
          resolve(im)
        }
   })
}

genFeatureTensor = image => {
  const img = await loadImage(image);
  return tf.browser.fromPixels(image);
}

一个警告是,繁重的处理可能会阻塞浏览器中的主线程。这是网络工作者发挥作用的地方。

,

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

他们的工作是:

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

然后火车

数据集的构建如下:

  1. 图片

大图像分为n个垂直块。 (n为chunkSize)

考虑大小为2的chunkSize。

给出图像1的像素矩阵:

  1 2 3
  4 5 6

鉴于图像2的像素矩阵为

  7 8 9
  1 2 3

结果数组将是 1 2 3 4 5 6 7 8 9 1 2 3(以某种方式连接一维)

因此,基本上在处理结束时,就有一个大缓冲区表示

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

  1. 标签

对于分类问题,这种格式已经做了很多。他们不使用数字分类,而是采用布尔数组。 要预测10个课程中的7个,我们将考虑 [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,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,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);
  }

}
,

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

index.html标题:

   <script src="https://unpkg.com/@tensorflow-models/knn-classifier"></script>

index.html正文:

    <button id="class-a">Add A</button>
    <button id="class-b">Add B</button>
    <button id="class-c">Add C</button>

index.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));

    ....

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

完整的代码在本教程中。 [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

,

TL; DR

MNIST是图像识别Hello World。认真学习后,您脑海中的这些问题很容易解决。


问题设置:

您写的主要问题是

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

在您的代码块内。对于那些人,我从Tensorflow.js示例部分的示例(MNIST示例)中找到了完美的答案。我的以下链接提供了纯javascript和node.js版本以及Wikipedia的说明。我将在必要的水平上讲解它们,以回答您心中的主要问题,并且还将添加观点,说明您自己的图像和标签与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;
}

注释:

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,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;
}

注释:

在这里,标签也是文件中的字节数据。在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
  });

注释:

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)}`);

注意:

在数据科学领域,这也是这次,最令人着迷的部分是要知道该模型在测试新数据且没有标签的情况下如何生存,是否可以为它们添加标签?因为那是评估部分,现在可以为我们打印一些数字。

损失和准确性:[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] How to interpret "loss" and "accuracy" for a machine learning model

本文链接:https://www.f2er.com/3066317.html

大家都在问