Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple kNN classifier to determine if a given dog (weight, height) whether is a Labrador oder a Bernese Mountain Dog
// Training Data
const weightX = [40,42,42.5,48,50,51,37,38.5,42.5,44.5,45.5,46.5,43.5,51.5,52,47.0,49.5,48.0,48.5,50.5,38,30,35,38,32,30,33,36,36,40,41,37,34,32,31.5,35.5,36,37.5,37,40,38,39]
const heightY = [60,62,62,72,70.5,69.5,55,53.5,61,62,62.5,65,65.5,69,70.5,62.5,59,58,61,64,58,52,54,56,50,48,50.5,51.5,57,59,58,55,52,50,51,49,49.5,52,53,55,52,56.5]
// Label – 0 stands for Berner Sennenhund, 1 for Labrador Retriever
const label = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
const k = 4;
const distances = [];
function getDistances (dogWx, dogHy) {
for (var i=0; i < weightX.length; i++) {
// calculating distance between the points
const dx = weightX[i] - dogWx;
const dy = heightY[i] - dogHy;
const d = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
const label = getLabel(i);
// creating distance objects and push them to the distances array with index, distance, label
const distance = [i, d, label];
distances.push(distance);
// Sort distances in descending order
distances.sort(function(a,b) {
return a[1] - b[1];
});
}
}
function getLabel(index) {
return label[index];
}
function getNearestNeighbors(k, testDataX, testDataY) {
var sum = 0;
getDistances (testDataX, testDataY);
//
for (var i=0; i < k; i++) {
console.log(distances[i])
sum += distances[i][2];
}
const knn = sum / k;
if (knn < 0.5) {
console.log("Berner Sennenhund");
} else {
console.log("Labrador Retriever");
}
}
// Run
getNearestNeighbors(k, 39, 55);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.