-
-
Save tanukid/bea3e41c3403c82d0c144058233ad61d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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