← Lesson
Nearest Neighbors
Joeven
Run
Reset
Python loads on first run
import math # 2-d toy: (x0, x1) labeled 0=search, 1=sql train = [ ([0.1, 0.9], 0), ([0.2, 0.8], 0), ([0.0, 1.0], 0), ([0.9, 0.1], 1), ([0.8, 0.2], 1), ([1.0, 0.0], 1), ] def dist(a, b): return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b))) def knn(x, k=3): scored = sorted((dist(x, p), y) for p, y in train) votes = [y for _, y in scored[:k]] # majority; tie -> first return 1 if votes.count(1) > votes.count(0) else 0, votes for name, x in [("docs question", [0.15, 0.85]), ("revenue question", [0.85, 0.15])]: yhat, votes = knn(x, k=3) label = "sql" if yhat == 1 else "search" print(name, "votes", votes, "->", label)
Run to execute this in your browser. Nothing is sent to a server.