Overview
A simple method of computing {% k %} nearest neighbors is to compute a distance between each point and the point in question. The the dataset is sorted by the computed distance. The top {% k %} records are used to infer the result of the algorithm.
Example
The following example sorts a dataset by the distance from each point to the given point.
let data = await $url('/lib/machine-learning/nearest-neighbor/v1.0.0/site/sample.json');
var metric = (p,q) =>{
//return a distance meaure between p and q
return Math.sqrt((p.point1 - q.point1)*(p.point1 - q.point1) + (p.point2 - q.point2)*(p.point2 - q.point2))
};
let q = data[0];
let neighbors = $list(data).map(p => {
return {
item: p,
distance: metric(p, q)
}
}).sort(p => p.distance);
Try it!