BeginnerCoder

Lesson 16 — k-NN (tiny)

k-nearest neighbours: ask your neighbours

k-NN classifies a new point by looking at the k closest labelled points and taking a majority vote of their labels. No training needed — the data itself is the model. sorted(points, key=...) orders points by a rule you give it; here, by distance to the new point.

from collections import Counter
Counter(["a", "b", "a"]).most_common(1)[0][0]   # "a"

Why it matters: k-NN is the simplest real classifier and the idea behind "find similar items" features everywhere.

Want it another way?
Task

Take the k nearest points and return the most common label among them. Expected: cat, dog.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with AI / ML Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.