KNN Classifier for TensorFlow.js
npm install @tensorflow-models/knn-classifierThis package provides a utility for creating a classifier using the
K-Nearest Neighbors
algorithm.
This package is different from the other packages in this repository in that it
doesn't provide a model with weights, but rather a utility for constructing a
KNN model using activations from another model or any other tensors you can
associate with a class/label.
You can see example code here.
##### via Script Tag
``html



###### via NPM
`js
const tf = require('@tensorflow/tfjs');
const mobilenetModule = require('@tensorflow-models/mobilenet');
const knnClassifier = require('@tensorflow-models/knn-classifier');// Create the classifier.
const classifier = knnClassifier.create();
// Load mobilenet.
const mobilenet = await mobilenetModule.load();
// Add MobileNet activations to the model repeatedly for all classes.
const img0 = tf.browser.fromPixels(document.getElementById('class0'));
const logits0 = mobilenet.infer(img0, true);
classifier.addExample(logits0, 0);
const img1 = tf.browser.fromPixels(document.getElementById('class1'));
const logits1 = mobilenet.infer(img1, true);
classifier.addExample(logits1, 1);
// Make a prediction.
const x = tf.browser.fromPixels(document.getElementById('test'));
const xlogits = mobilenet.infer(x, true);
console.log('Predictions:');
console.log(classifier.predictClass(xlogits));
`API
#### Creating a classifier
knnClassifier is the module name, which is automatically included when you use
the