From 593ab7fb14458fdc174d88f099dd52323aad999a Mon Sep 17 00:00:00 2001 From: Gary Chambers Date: Mon, 3 Dec 2012 13:26:38 +0000 Subject: [PATCH] Added helper methods to Model class for sorting & classifying --- src/model.js | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/src/model.js b/src/model.js index 6e7d8be..481a0dd 100644 --- a/src/model.js +++ b/src/model.js @@ -127,4 +127,59 @@ kNN.Model = (function( global, undefined ) }; return Model; + /** + * Arrange a list of points by + * ascending distance. + * + * @param {Array} points A multi-dimensional + * array containing [ point, distance ] + * @return {Array} Sorted array of points + */ + sortPoints = function sortPoints( points ) + return points.sort(function(a, b) + { + return a[1] < b[1] ? -1 : 1; + }; + /** + * Predict the category for a point + * based on its K-nearest neighbors + * @param {Number} K How many points to compare + * @param {Point} point + * @param {Array} neighbors An array of points + * @return {String} + */ + { + + bestScore, + force, + key, + i, n; + + categories = {}; + i = 0; + + for( ; i < K; i++ ) + { + n = neighbors[i]; + if( !categories.hasOwnProperty(n.category) ) + categories[ n.category ] = 0; + + + { + // choose randomly between the two + + { + { + force = true; + } + } + + if( force || categories[key] > bestScore ) + { + bestScore = categories[key]; + } + } + + return prediction; + }; })( this ); \ No newline at end of file -- 2.1.1