How to get most probable className from TensorFlow.js in Node

398 views Asked by At

What I want to do: I want to get the className with the highest probability from the TensorFlow.js image classification with mobileNet. I want to get the className as a String.

Problem: I have no clue how to isolate the className as a String. Is there a command for this? or do you have any idea how I can solve my problem?

My code:

theAi();

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

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

    const results = await mobilenetModel.classify(tfimage);
    console.log(results);
};

And the output:

[
  {
    className: 'chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour',
    probability: 0.5979475378990173
  },
  { className: 'vestment', probability: 0.14261281490325928 },
  { className: 'fountain', probability: 0.03441018983721733 }
]

So in this case I would want to get the String ('chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour').

1

There are 1 answers

1
Fedor  Petrov On BEST ANSWER

This is a pure javascript question. If you get this result, you can just search for m aximum:

const maxClass = result.reduce(function(prev, current) {
    return (prev.probability > current.probability) ? prev : current;
})["className"];