Lesson 1 of 6

k-Nearest Neighbors

15 pts

Explanation

k-Nearest Neighbors (k-NN) is one of the simplest classifiers: to predict a new point's label, find the k closest points in the training data (using something like straight-line distance) and have them vote. No training loop, no gradient descent — the "model" is just the stored data plus a distance calculation done at prediction time.

Visual explanation

Read this from left to right: what goes in, what happens, and what comes out.

New example
Find nearest neighbours
Majority vote

A new dot is placed among labelled dots; the nearest neighbours choose its label.

In plain language

K-nearest neighbours predicts by looking at the most similar known examples nearby and letting them vote.

Remember

KNN asks: which known examples are closest?

What to do

Complete the distance function (straight-line/Euclidean distance between two 2D points), then run it.

Validation questionDoes your distance function use the Pythagorean formula: sqrt of the sum of squared differences?

Code Lab

JavaScript

Fill in distance(a, b) using the Euclidean distance formula, then run it.

Console

Click Run to execute your code and see console output here.