K-Nearest neighbor Algorithm

classify a person into fat ,healthy and thin based on height and weight

Implementation details

Consider a two sets of dots in the space, red dots and blue dots. If I were to give you a random point and ask you color of the point what would you do? You would say red if the point was closer to red cluster and blue if the point was near the blue cluster. That’s what we are going to do.

  • Measure the distance between unknown point and all the points
  • Sort the Nodes from minimum distance to maximum distance
  • Take k number of Nodes. If majority of them say blue, it’s blue
var Node = function(label,x,y){
this.label = label;
this.x = x;
this.y = y;
// [genere, kisses,fights]var trainData = [
var Nodes = [];
for(var i=0;i<trainData.length;i++){
var l = trainData[i][0],
x = trainData[i][1],
y = trainData[i][2];
Nodes.push(new Node(l,x,y));
Node.prototype.distanceFrom = function(node){
var sqrDist = Math.pow(this.x - node.x,2)
+ Math.pow(this.y-node.y,2);
return Math.sqrt(sqrDist);
var k = 3;
function whichGenere(node){
var dists = [];
for(var i=0;i<Nodes.length;i++){
var d = node.distanceFrom(Nodes[i]);
//sort the array
var sortedArr = dists.sort(function(a,b){
return a.d-b.d;

var votes = {'Action':0,'Romance':0};

for(var i=0;i<k;i++){

if(votes.Romance>votes.Action) return 'Romance';
else return 'Action';

// 5 kisses and 0 fights should output romance.
console.log(whichGenere(new Node('',5,0)));
  • number of comic scenes
  • number of horror scenes
  • number of emotional scenes



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store