Code / AI & ML Basics / Unit 2: Classifiers: which group is it?

Distance and nearest neighbour दूरी और सबसे नज़दीकी पड़ोसी

Lesson 4 of 13 · about 14 minutes · Euclidean distance and the simplest classifier.

⚡ 0 XP

Step 1 of 2

How far apart are two fruits?

Draw each fruit as a dot: x = sweetness, y = weight. Similar fruits sit close together. The straight-line gap between two dots is the Euclidean distance — Pythagoras from Class 8!

distance = √((x1 - x2)² + (y1 - y2)²)

The same idea works with any number of features: for each feature, subtract, square, add them all up, then take the square root.

  • [0, 0] to [3, 4] → √(9 + 16) = 5
Example
const a = [0, 0];
const b = [3, 4];
const d = Math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2);
console.log(d);

Prints: 5

🎯 Challenge: Euclidean distance +10 XP

Write distance(a, b) where a and b are arrays of the same length (any length: 2, 3, …). Return the Euclidean distance: the square root of the sum of squared differences.

Try twice to unlock the solution (0/2)

script.jsCtrl ⏎
Console

Output from console.log appears here.

Checklist

Press Run to check your code.

  • distance([0, 0], [3, 4]) is 5
  • Same point → 0, order does not matter
  • Works with 3 features
Lesson notes (text version)

1. How far apart are two fruits?

Draw each fruit as a dot: x = sweetness, y = weight. Similar fruits sit close together. The straight-line gap between two dots is the Euclidean distance — Pythagoras from Class 8!

distance = √((x1 - x2)² + (y1 - y2)²)

The same idea works with any number of features: for each feature, subtract, square, add them all up, then take the square root.

  • [0, 0] to [3, 4] → √(9 + 16) = 5
                const a = [0, 0];
const b = [3, 4];
const d = Math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2);
console.log(d);
              

Challenge: Euclidean distance

Write distance(a, b) where a and b are arrays of the same length (any length: 2, 3, …). Return the Euclidean distance: the square root of the sum of squared differences.

2. The nearest neighbour

Here is a whole classifier in one sentence: a new fruit gets the label of the closest fruit we already know.

That is the nearest neighbour rule. “Training” is just remembering the examples; all the work happens when you predict:

  1. measure the distance from the new point to every training point
  2. find the smallest distance
  3. return that point’s label

Our rows look like { point: [sweetness, weight], label: "mango" }. (Scale your features first — remember normalising — or weight will boss everyone around.)

Challenge: Mango or lemon?

distance is ready. Write nearestLabel(train, point): go through every row of train, find the row whose row.point is closest to point, and return its label.

Search by task, life event, format or tool name, in English, हिंदी or Hinglish.