Skip to content

Instantly share code, notes, and snippets.

@tanukid
Forked from abelmcelroy/whatever
Created November 11, 2017 22:32
Show Gist options
  • Save tanukid/0a6e76da3c08ce8820502b48ffe5aa18 to your computer and use it in GitHub Desktop.
Save tanukid/0a6e76da3c08ce8820502b48ffe5aa18 to your computer and use it in GitHub Desktop.
function KNN(kSize){
this.kSize = kSize;
this.points = [];
}
KNN.prototype.train = function(set){
this.points = this.points.concat(set)
}
KNN.prototype._distance =function(p1,p2){
var d = 0
for(var i = 0;i<p1.length;i++){
d+=Math.pow(p1[i]-p2[i],2)
}
return Math.sqrt(d)
}
KNW.prototype._distances = function(p){
var self = this;
var points = this.points.map(v=>{
return [self._distance(p,v[0]),v[1]]
}).sort((a,b)=>(a[0] - b[0]))
return points.splice(0,this.kSize)
}
Array.prototype.count = function(v){
var c = 0
for(var i =0;i<this.length;i++){
if(this[i]===v) c++
}
return c;
}
KNW.prototype._classify = function(closestNeighbors){
var classesCount = closestNeighbors.map(v=>this.count(v));
var max = Math.max.apply(null,classesCount)
return closestNeighbors[classesCount.indexOf(max)]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment