Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

ml-knn

mljs5.5kMIT3.0.0

k-nearest neighbors algorithm

nearest, neighboor, classifier, machine, learning

readme

knn

NPM version build status npm download

A General purpose k-nearest neighbor classifier algorithm based on the k-d tree Javascript library develop by Ubilabs:

Installation

$ npm i ml-knn

API

new KNN(dataset, labels[, options])

Instantiates the KNN algorithm.

Arguments:

  • dataset - A matrix (2D array) of the dataset.
  • labels - An array of labels (one for each sample in the dataset).
  • options - Object with the options for the algorithm.

Options:

  • k - number of nearest neighbors (Default: number of labels + 1).
  • distance - distance function for the algorithm (Default: euclidean distance).

Example:

var dataset = [
  [0, 0, 0],
  [0, 1, 1],
  [1, 1, 0],
  [2, 2, 2],
  [1, 2, 2],
  [2, 1, 2]
];
var predictions = [0, 0, 0, 1, 1, 1];
var knn = new KNN(dataset, predictions);

predict(newDataset)

Predict the values of the dataset.

Arguments:

  • newDataset - A matrix that contains the dataset.

Example:

var dataset = [[0, 0, 0], [2, 2, 2]];

var ans = knn.predict(dataset);

toJSON()

Returns an object representing the model. This function is automatically called if JSON.stringify(knn) is used.
Be aware that the serialized model takes about 1.3 times the size of the input dataset (it actually is the dataset in a tree structure). Stringification can fail if the resulting string is too large.

KNN.load(model[, distance])

Loads a model previously exported by knn.toJSON(). If a custom distance function was provided, it must be passed again.

Check this cool blog post for a detailed example: https://hackernoon.com/machine-learning-with-javascript-part-2-da994c17d483

License

MIT

changelog

3.0.0 (2019-06-29)

chore

  • update dependencies and remove support for Node.js 6 (8727324)

BREAKING CHANGES

  • Node.js 6 is no longer supported.

2.1.3 (2017-10-26)

Bug Fixes

  • compute default k correctly (c69b522)

2.1.2 (2017-10-09)

Bug Fixes

  • allow strings and non-consecutive numbers labels for classification (574cac2)

2.1.1 (2017-08-21)

Bug Fixes

  • change default k to the number of classes + 1 (d493043)

2.1.0 (2017-07-11)

Features

2.0.1 (2017-07-11)

Bug Fixes

  • options object is optional (d735a00), closes #4

2.0.0 (2017-07-05)

Code Refactoring

  • remove train method (#3) (2212170)
  • use ES6 modules and change support to Node 8 and 6 (#2) (4df79a8)

Features

  • allow to predict a single point (f13c9f8)

BREAKING CHANGES

  • The train method has been removed. Instead the arguments must be passed to the KNN constructor.
  • This library now only supports Node.js 8 and 6.