tensorflow / tfjs

A WebGL accelerated JavaScript library for training and deploying ML models.
https://js.tensorflow.org
Apache License 2.0
18.37k stars 1.92k forks source link

knn classifier bug: -1 classification and NaN confidences when first classes are empty #1478

Closed oveddan closed 5 years ago

oveddan commented 5 years ago

If you create a knn classifier and add some classes that are not at the beginning, then run predictClass, you get a -1 class and some NaN confidence levels:

Sample code:

import * as knnClassifier from '@tensorflow-models/knn-classifier';

const testClassifications = async () => {
  const classifier = knnClassifier.create();

  classifier.addExample(tf.tensor2d([5, 2], [2, 1]), 1);
  classifier.addExample(tf.tensor2d([6, 1], [2, 1]), 2);

  const result = await classifier.predictClass(tf.tensor2d([3, 3], [2, 1]));

  console.log(result);
}

testClassifications();

Result is:

{
  classIndex: -1, 
  confidences: {
    1: 0
    2: NaN
  }
}
dsmilkov commented 5 years ago

Thanks. Sent a fix in https://github.com/tensorflow/tfjs-models/pull/188

dsmilkov commented 5 years ago

Hi Dan, we just released a new version of knn-classifier (1.1.0) on npm that supports arbitrary strings or numbers as class labels.