Machine Learning from Scratch · Classifying
Classify a new fruit as an apple or a lemon by measuring how far it is from every known fruit and letting its nearest neighbours vote.
# Each fruit has a size and a sweetness, both from 1 to 10.
xs = [7, 8, 6, 3, 2, 4, 5]
ys = [8, 6, 7, 2, 4, 3, 5]
labels = ["apple", "apple", "apple", "lemon", "lemon", "lemon", "lemon"]
new_x, new_y = 6, 5 # a new fruit: is it an apple or a lemon?
k = 3 # ask its 3 nearest neighbours
distances = []
for i in range(len(xs)):
d = ((xs[i] - new_x) ** 2 + (ys[i] - new_y) ** 2) ** 0.5
distances.append((d, i))
distances.sort()
nearest = distances[:k]
votes = {}
for d, i in nearest:
label = labels[i]
votes[label] = votes.get(label, 0) + 1
prediction = max(votes, key=votes.get)
print("Prediction:", prediction)xs holds the size of each one, from 1 to 10.ys holds how sweet each one is. Together, xs[i] and ys[i] place fruit i on the chart: size across, sweetness up.labels holds the answer for each known fruit. On the chart, apples are red and lemons are amber. Apples are big and sweet (top right); lemons are small and sour (bottom left).k is how many neighbours get a vote. With k = 3, the 3 known fruits closest to the star will decide.(3.16, 0) is added to the list: the distance and which fruit it belongs to. A dashed line now joins the star to fruit 0, labelled with its length.(2.24, 1) is stored. One more dashed line on the chart.(2.0, 2) is stored. One more dashed line on the chart.(4.24, 3) is stored. One more dashed line on the chart.(4.12, 4) is stored. One more dashed line on the chart.(2.83, 5) is stored. One more dashed line on the chart.(1.0, 6) is stored. One more dashed line on the chart.sort() puts the list in order of distance, nearest first: (1, 6), (2, 2), (2.24, 1), (2.83, 5)...distances[:k] keeps the first 3: the lemon at 1, and the apples at 2 and 2.24. On the chart they get bold lines, inside a dashed circle.labels[6] is "lemon".votes.get(label, 0) reads the count so far, or 0 if there is none yet, then adds 1.max(votes, key=votes.get) picks the kind with the most votes: apple, 2 to 1. The star turns red: the new fruit is classified as an apple.