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.
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.
A quick 3-question quiz on this lesson — instant feedback.
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.
Project-based AI / ML Foundations courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for AI / ML Foundations books — check the publication year so the examples match current versions.
Search Amazon →