K-Nearest neighbor Algorithm

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

Implementation details

  • 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




just a bug hunter and problem addict

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Three laws of model explanation

Transfer learning for Classification in Ultra-small Biomedical Datasets

Hough Transformation

Using Machine Learning to Predict the Weather in Basel — Pt. 1 Data & Baselines

Summarizing The Great Gatsby using Natural Language Processing

What Is A Neural Network? : A 101 Guide To Artificial Neural Networks

What is Cross Validation and When to use Which Cross Validation

Your Complete Guide to Building Stateless Bots Using Rasa Stack

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
Abhishek Jakhotiya

Abhishek Jakhotiya

just a bug hunter and problem addict

More from Medium

Delving into Developing: Intro to JavaScript Complex Data Types

JavaScript Block Scope V/S Function Scope

Higher Order Functions

JavaScript Challenge: 66. Plus One