本书暂未推出简体中文版。现有版本:English。
High School Computer Science · 10–12 年级
19Classifying by Neighbours: the k-NN Algorithm
The town’s sorting office receives every item posted in the town, and each must go to the right belt: letters to one, packets to another, parcels to a third. A machine measures each item, its thickness in millimetres and its mass in grams, but nobody has written down a rule turning these two numbers into a belt. What the office does have is a pile of items already sorted by hand.
This chapter writes a program that sorts a new item by looking at the items already sorted that resemble it most. The idea is old and simple, it needs no rule written by hand, and its errors can be measured honestly, provided some items are kept aside for that purpose.
You already know
Pseudo-random numbers from a seed, met in the first book of the series, give data that are the same at every run. Floating-point numbers are approximations (chapter 4). sorted(t, key=f) sorts by a key (chapter 7); the cost of an algorithm counts its elementary operations (chapter 17).
19.1 Learning from labelled examples
Definition 19.1 (Labelled example, feature, class)
A labelled example is an item described by numbers, its features, together with the answer known for it, its class, also called its label.
Here an item is a tuple (thickness, mass, label), for instance (13.7, 541, "packet"). The items of the office are invented: parcels.py draws them from a seeded generator, with three classes that overlap, as real items do: a thick letter weighs as much as a thin packet.
"""Invented items of the town's sorting office: thickness (mm), mass (g), class."""
import random
# class: (how many, mean thickness, spread, mean mass, spread)
KINDS = {"letter": (100, 4, 2, 60, 40),
"packet": (130, 18, 8, 350, 180),
"parcel": (70, 40, 15, 550, 250)}
def make_items(seed=2026):
rng = random.Random(seed)
items = []
for label, (count, t, dt, m, dm) in KINDS.items():
for _ in range(count):
thickness = max(0.5, rng.gauss(t, dt))
mass = max(5.0, rng.gauss(m, dm))
items.append((round(thickness, 1), round(mass), label))
rng.shuffle(items)
return items
def split(items):
"""180 to learn from, 60 to choose k, 60 kept untouched until the end."""
return items[:180], items[180:240], items[240:]
Definition 19.2 (Training set, test set)
The training set is the set of labelled examples a method learns from. A test set is a set of labelled examples kept aside, never used for learning, on which the method’s answers are compared with the known classes.
The office keeps items to learn from, to make choices with, and that nobody looks at until the very end.
from collections import Counter
from parcels import make_items, split
items = make_items()
print(len(items), "items:", dict(Counter(label for _, _, label in items)))
for thickness, mass, label in items[:5]:
print(f" {thickness:5} mm {mass:5} g {label}")
train, validation, test = split(items)
print("split:", len(train), "to learn,", len(validation), "to choose k,",
len(test), "for the final test")
$ python show_data.py
300 items: {'letter': 100, 'packet': 130, 'parcel': 70}
0.5 mm 39 g letter
0.5 mm 49 g letter
3.2 mm 90 g letter
13.7 mm 541 g packet
58.7 mm 888 g parcel
split: 180 to learn, 60 to choose k, 60 for the final test
19.2 A distance between examples
“Resemble” needs a number. Two items are drawn as two points, one feature on each axis, and the distance between them is the length of the segment joining them, as the mathematics book computes it by Pythagoras’ theorem.
import math
def distance(a, b):
"""Euclidean distance between two items (thickness, mass, ...); labels ignored."""
return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
if __name__ == "__main__":
letter, packet, parcel = (3.0, 50, "?"), (20.0, 300, "?"), (45.0, 320, "?")
print("letter-packet:", distance(letter, packet))
print("packet-parcel:", distance(packet, parcel))
$ python distance.py
letter-packet: 250.57733337235433
packet-parcel: 32.01562118716424
The output hides a trap. The packet and the parcel differ by mm, the letter and the packet by mm; yet the distances say the opposite of what the eye sees on the thicknesses, because they are almost only differences of mass: g counts as , a millimetre counts as . The unit chosen for each feature decides how much it weighs.
Definition 19.3 (Scaling)
Scaling the features means changing each one by the same rule for every item so that all of them cover comparable ranges. Min-max scaling replaces a value of a feature by , where and are the smallest and largest values of that feature in the training set; the results lie between and on the training set.
"""Millimetres against grams: rescale each feature to the range 0 to 1."""
from distance import distance
from knn import neighbours, predict
from parcels import make_items, split
def scaler(train):
"""Min-max scaling, computed on the training set only."""
lo = [min(e[i] for e in train) for i in (0, 1)]
hi = [max(e[i] for e in train) for i in (0, 1)]
return lambda e: tuple((e[i] - lo[i]) / (hi[i] - lo[i]) for i in (0, 1)) + (e[2],)
if __name__ == "__main__":
train, _, _ = split(make_items())
s = scaler(train)
new = (12.0, 150, "?")
print("scaled new item:", tuple(round(v, 3) for v in s(new)[:2]))
def scaled(a, b):
return distance(s(a), s(b))
for e in neighbours(train, new, 7, dist=scaled):
print(f" {e[0]:5} mm {e[1]:5} g {e[2]:7} at {scaled(e, new):.3f}")
print("k = 7, scaled:", predict(train, new, 7, dist=scaled))
$ python scale.py
scaled new item: (0.137, 0.118)
13.9 mm 133 g packet at 0.026
11.5 mm 194 g packet at 0.036
15.2 mm 195 g packet at 0.053
13.6 mm 217 g packet at 0.058
7.3 mm 112 g letter at 0.064
12.6 mm 72 g packet at 0.064
6.8 mm 107 g letter at 0.071
k = 7, scaled: packet
The bounds come from the training set only: an item kept aside must not change the rule applied to it, or the test would no longer be a test. Scaled values are floating-point numbers; two distances that should be equal may differ in the last digits, which is one more reason to break ties by a fixed rule.
19.3 The k nearest neighbours vote
Method 19.4 (The k nearest neighbours)
To predict the class of a new item from a training set, with a whole number :
- compute the distance from to every example of the training set;
- keep the examples with the smallest distances, the nearest neighbours;
- answer the class that is most common among them; on a tie, a fixed rule decides, here the class of the nearest of the tied ones.
from collections import Counter
from distance import distance
from parcels import make_items, split
def neighbours(train, x, k, dist=distance):
return sorted(train, key=lambda e: dist(e, x))[:k]
def vote(near):
"""The most common class; a tie goes to the class of the nearest among them."""
count = Counter(label for _, _, label in near)
best = max(count.values())
return next(label for _, _, label in near if count[label] == best)
def predict(train, x, k, dist=distance):
return vote(neighbours(train, x, k, dist))
if __name__ == "__main__":
train, _, _ = split(make_items())
new = (12.0, 150, "?") # 12 mm, 150 g: which class?
for e in neighbours(train, new, 7):
print(f" {e[0]:5} mm {e[1]:5} g {e[2]:7} at {distance(e, new):6.1f}")
for k in [1, 3, 7]:
near = neighbours(train, new, k)
print(f"k = {k}: {predict(train, new, k)}",
dict(Counter(label for _, _, label in near)))
$ python knn.py
5.3 mm 159 g packet at 11.2
2.2 mm 141 g letter at 13.3
24.1 mm 156 g packet at 13.5
27.1 mm 144 g packet at 16.2
13.9 mm 133 g packet at 17.1
19.4 mm 166 g packet at 17.6
19.6 mm 167 g packet at 18.6
k = 1: packet {'packet': 1}
k = 3: packet {'packet': 2, 'letter': 1}
k = 7: packet {'packet': 6, 'letter': 1}
With the answer follows the single nearest example, however unusual it is; a larger smooths the answer by asking more examples. The two pictures below colour every point of the plane by the class the method would give it.
19.4 Measuring the error
Definition 19.5 (Error rate)
The error rate of a method on a set of labelled examples is the number of examples whose predicted class differs from the known class, divided by the number of examples.
On which examples? On the training set itself, never errs: each example’s nearest neighbour is itself, at distance . That says nothing about new items. The error must be measured on examples the method has not seen.
"""Errors on examples kept aside, for each k, with scaled features."""
from distance import distance
from knn import predict
from parcels import make_items, split
from scale import scaler
def error_rate(train, examples, k, dist):
wrong = sum(predict(train, x, k, dist) != x[2] for x in examples)
return wrong / len(examples)
train, validation, _ = split(make_items())
s = scaler(train)
def scaled(a, b):
return distance(s(a), s(b))
if __name__ == "__main__":
for k in range(1, 16):
on_train = error_rate(train, train, k, scaled)
on_validation = error_rate(train, validation, k, scaled)
print(f"k = {k:2}: error on the training set {on_train:6.1%},"
f" on the validation set {on_validation:6.1%}")
$ python error_rate.py
k = 1: error on the training set 0.0%, on the validation set 10.0%
k = 2: error on the training set 0.0%, on the validation set 10.0%
k = 3: error on the training set 6.1%, on the validation set 8.3%
k = 4: error on the training set 3.9%, on the validation set 6.7%
k = 5: error on the training set 5.6%, on the validation set 5.0%
k = 6: error on the training set 4.4%, on the validation set 6.7%
k = 7: error on the training set 6.7%, on the validation set 5.0%
k = 8: error on the training set 5.6%, on the validation set 5.0%
k = 9: error on the training set 8.3%, on the validation set 5.0%
k = 10: error on the training set 5.6%, on the validation set 6.7%
k = 11: error on the training set 7.8%, on the validation set 5.0%
k = 12: error on the training set 6.1%, on the validation set 6.7%
k = 13: error on the training set 8.9%, on the validation set 8.3%
k = 14: error on the training set 8.3%, on the validation set 6.7%
k = 15: error on the training set 8.9%, on the validation set 6.7%
Choosing is itself a kind of learning: the validation items serve to choose, and the test items, never used for any choice, give the honest final error. If were chosen on the test items, their error would flatter the method.
"""Choose k on the validation set: the smallest k with the fewest errors."""
from error_rate import error_rate, scaled, train, validation
errors = {k: error_rate(train, validation, k, scaled) for k in range(1, 16)}
best = min(errors.values())
chosen = min(k for k in errors if errors[k] == best)
print("lowest validation error:", f"{best:.1%}", "for k in",
[k for k in errors if errors[k] == best])
print("chosen: k =", chosen)
$ python choose_k.py
lowest validation error: 5.0% for k in [5, 7, 8, 9, 11]
chosen: k = 5
19.5 What the method cannot do, and its cost
The method learns nothing in advance: it keeps the whole training set and does all its work at each prediction. With examples, each prediction computes distances, then sorts them.
"""Every prediction measures its distance to every example: count them."""
from distance import distance
from knn import predict
from parcels import make_items, split
calls = 0
def counted(a, b):
global calls
calls += 1
return distance(a, b)
train, validation, test = split(make_items())
for examples, name in [(validation, "validation"), (validation + test, "both")]:
calls = 0
for x in examples:
predict(train, x, 5, dist=counted)
print(f"{len(examples):3} predictions ({name}) with {len(train)} examples:",
calls, "distances")
$ python knn_cost.py
60 predictions (validation) with 180 examples: 10800 distances
120 predictions (both) with 180 examples: 21600 distances
For predictions, distances, each taking a few operations per feature: a cost that grows like with features, plus the sorts. A post office handling a million items a day with a million examples would compute distances a day. Faster methods exist that organise the examples in advance, or learn a compact rule instead of keeping them all.
Remark 19.6
With many features, a further difficulty appears: in a space of many dimensions, almost all points are far from one another, and the nearest neighbour is hardly nearer than the others. The vote then means little. The series’ books on artificial intelligence take up these questions, and the methods that answer them.
History — Neighbours
The nearest-neighbour rule was described by the statisticians E. Fix and J. L. Hodges in a report long kept unpublished, finally printed in a statistics journal in 1989. In January 1967, T. Cover and P. Hart published an article proving that, with enough examples, the error of the rule with is at most twice the smallest error any rule could reach.
19.6 Exercises
Exercise 19.1 ★
Compute the distance between the items and , without scaling.
Solution
Solution of Exercise 19.1.
.
Exercise 19.2 ★
A tiny training set: A at , A at , B at , B at , A at . Which class does the method predict for with ?
Solution
Solution of Exercise 19.2.
Distances from : B and B at , A at , A at , A at . The three nearest are B, B, A: class B.
Exercise 19.3 ★
With the same training set, list the five examples from the nearest to the farthest from .
Solution
Solution of Exercise 19.3.
at ; at ; at ; at ; at .
Exercise 19.4 ★
A confusion table counts, for each true class (row), the predicted classes (columns). Compute the error rate.
| true \ predicted | letter | packet | parcel |
|---|---|---|---|
| letter | |||
| packet | |||
| parcel |
Solution
Solution of Exercise 19.4.
items in all; the diagonal, , is right; errors: .
Exercise 19.5 ★
Write distance(a, b) for items with any number of features, the label being the last element of each tuple.
Solution
Solution of Exercise 19.5.
def distance(a, b):
return math.sqrt(sum((x - y) ** 2 for x, y in zip(a[:-1], b[:-1])))
a[:-1] drops the label; zip pairs the features in order.
Exercise 19.6 ★★
To estimate the error without a validation set, a student predicts each item of the training set with predict(items, x, 1) of the chapter, and finds an error of for every data set. Find the fault and correct it.
Exercise 19.7 ★★
Write knn_predict(train, x, k), with ties broken by the class of the nearest of the tied ones.
Solution
Solution of Exercise 19.7.
def knn_predict(train, x, k):
near = sorted(train, key=lambda e: distance(e, x))[:k]
count = Counter(e[-1] for e in near)
best = max(count.values())
return next(e[-1] for e in near if count[e[-1]] == best)
near is in order of distance, so the first label reaching the best count belongs to the nearest of the tied classes. The tests compare it with the chapter’s predict on random sets.
Exercise 19.8 ★★
In the training set, thickness runs from to mm and mass from to g. Compute, with and without scaling, the distances from the new item to and to . Which is nearer in each case?
Exercise 19.9 ★★
A vote is written max(set(labels), key=labels.count), where labels is the list of the neighbours’ classes. On some items the program answers differently from one run to the next. Why?
Solution
Solution of Exercise 19.9.
On a tie, several labels have the same count, and max keeps the first one met. The order of a set of strings is not fixed: Python mixes a random value into the hash of strings at each start of the program, so the order, and the answer, may change from run to run. A fixed rule, such as the class of the nearest tied neighbour, removes the problem.
Exercise 19.10 ★★
In the output of error_rate.py, the training error is for . Explain why. Can it be different from for some data?
Solution
Solution of Exercise 19.10.
Each training example is its own nearest neighbour, at distance , and its class is its own answer. It can differ from if two examples have the same features and different classes: the sort may put the other one first. (With the output also shows : the second neighbour can only tie, and the tie goes to the nearest.)
Exercise 19.11 ★★
Write minmax(train), which returns a function scaling an item with bounds taken from train, for any number of features.
Solution
Solution of Exercise 19.11.
def minmax(train):
d = len(train[0]) - 1
lo = [min(e[i] for e in train) for i in range(d)]
hi = [max(e[i] for e in train) for i in range(d)]
def scale(e):
return tuple((e[i] - lo[i]) / (hi[i] - lo[i])
for i in range(d)) + (e[-1],)
return scale
The function returned remembers lo and hi. A feature with the same value everywhere would divide by ; it can simply be dropped, since it never separates two examples.
Exercise 19.12 ★★★
Give the cost of predicting items with examples and features, counting the operations on features for the distances and the comparisons for the sorts. What changes if the nearest are found by scans for the smallest remaining distance instead of a sort?
Solution
Solution of Exercise 19.12.
Each of the predictions computes distances of about operations each (a subtraction, a square and an addition per feature): , which grows like . Each prediction then sorts distances, about comparisons with a good sort, where is the number of halvings of : in all about . With scans for the smallest remaining distance, each scan makes about comparisons: per prediction instead of , better when is smaller than , as it is for and ().
Exercise 19.13 ★★★
Write loo_error(items, k), the leave-one-out error: each item is predicted from all the others, and the error rate is computed over all the items.
Solution
Solution of Exercise 19.13.
def loo_error(items, k):
wrong = 0
for i, x in enumerate(items):
others = items[:i] + items[i + 1:]
wrong += knn_predict(others, x, k) != x[-1]
return wrong / len(items)
True counts as in a sum. On the scaled training set it gives, for to , from to errors out of , between and : an estimate of the error that uses every example both for learning and for checking, never at the same time.
Exercise 19.14 ★★★
What does the method predict when equals the number of training examples? What error rate does it then have on the validation set of the chapter?
Solution
Solution of Exercise 19.14.
All examples are neighbours, whatever : the vote always gives the most common class of the training set. The method becomes the baseline, here always “packet”, with a validation error of .
Exercise 19.15 ★★★
Write weighted_predict(train, x, k), in which each of the neighbours votes with a weight . On the scaled validation set it makes errors with , where the plain vote makes , but errors for every from to . What do the two votes do differently?
Solution
Solution of Exercise 19.15.
def weighted_predict(train, x, k):
score = Counter()
for e in sorted(train, key=lambda e: distance(e, x))[:k]:
score[e[-1]] += 1 / (distance(e, x) + 1e-9)
return score.most_common(1)[0][0]
The small 1e-9 avoids a division by when is an example. The weighted vote lets a very near neighbour outvote several far ones: it behaves more like a small when one neighbour is very close, and the far neighbours added by a larger change it less. Hence it makes fewer errors over a wide range of large , but not at every : on items, a difference of two errors is too small to prefer one vote for good.
19.7 Problem: The Sorting Office
Problem 19.1
Weekend problem — does k-NN beat a rule of thumb?
The sorting office compares the method with the simplest possible rule, always answering the most common class of the training set, then chooses and the scaling on the validation set, and finally measures the error once, on the test set.
"""The weekend problem: k-NN against a baseline, unscaled and scaled."""
from collections import Counter
from distance import distance
from error_rate import error_rate, scaled
from parcels import make_items, split
train, validation, test = split(make_items())
common = Counter(label for _, _, label in train).most_common(1)[0][0]
for name, examples in [("validation", validation), ("test", test)]:
wrong = sum(x[2] != common for x in examples) / len(examples)
print(f"baseline, always '{common}', on the {name} set: {wrong:.1%}")
print(" k unscaled scaled (validation set)")
best = None
for k in range(1, 16):
raw, sc = (error_rate(train, validation, k, d) for d in (distance, scaled))
print(f"{k:2} {raw:9.1%} {sc:8.1%}")
if best is None or sc < best[1]:
best = (k, sc)
k = best[0]
print(f"chosen k = {k}; final error on the untouched test set:",
f"{error_rate(train, test, k, scaled):.1%}")
$ python sorting_office.py
baseline, always 'packet', on the validation set: 55.0%
baseline, always 'packet', on the test set: 68.3%
k unscaled scaled (validation set)
1 11.7% 10.0%
2 11.7% 10.0%
3 13.3% 8.3%
4 11.7% 6.7%
5 15.0% 5.0%
6 13.3% 6.7%
7 20.0% 5.0%
8 15.0% 5.0%
9 20.0% 5.0%
10 20.0% 6.7%
11 20.0% 5.0%
12 21.7% 6.7%
13 21.7% 8.3%
14 18.3% 6.7%
15 20.0% 6.7%
chosen k = 5; final error on the untouched test set: 6.7%
Part I — The data and a baseline.
- What are the features, and what is the class, of an item?
- Why are the items invented and drawn from a seeded generator?
- The training set has packets, letters and parcels. Which class does the baseline always answer?
- The validation set has packets out of . Check the baseline’s validation error.
- The test set has packets out of . Check the baseline’s test error. Why does it differ from the validation error?
Part II — k-NN without scaling.
- From the unscaled column, what is the smallest validation error, and for which ?
- How many validation items does a error stand for?
- Why does the unscaled error grow with ? Think of which feature decides the neighbours.
- Is the unscaled method still much better than the baseline?
Part III — Scaling.
- From the scaled column, which values of give the smallest validation error?
- The program keeps the first reaching the smallest error. Which is chosen?
- Why are the bounds of the scaling taken from the training set only?
- The scaled error for is , for it is . Explain the difference with the pictures of the decision regions.
- How many fewer validation errors does scaling make at ?
Part IV — The final test.
- What is the final test error, and how many test items does it stand for?
- With scaling, the test errors for to are : would have done better on the test set. Why must the office still keep ?
- The four test items in error are a parcel of mm and g, a packet of mm and g, a packet of mm and g, and a parcel of mm and g. Why are they hard?
- Every prediction computes distances. How many for a day of items?
- How could the office reduce the error further, without changing the method?
- State the result: the chosen , its test error, and the baseline’s test error.
Solution
Solution of Problem 19.1.
1. The features are the thickness in millimetres and the mass in grams; the class is letter, packet or parcel.
2. So that every run, and every reader, gets the same items and the same numbers, and no real data need be collected.
3. Packet, the most common.
4. wrong: .
5. wrong: . The two sets are different random samples, with fewer packets in the test set.
6. , for , and .
7. items.
8. Without scaling the mass decides almost alone. Packets and parcels overlap much more in mass than in thickness, so as grows, the neighbours by mass bring more items of the wrong class.
9. Yes: at worst , against .
10. , , , and , at .
11. .
12. The validation and test items must be treated exactly as a new item will be, by a rule fixed before they are seen; their values must not shape the rule that judges them.
13. With , every isolated example of a class inside another class’s region makes an island, and new items near it are misclassified; with such an example is outvoted, and the frontier is smoother.
14. is errors, is : six fewer.
15. : items out of .
16. The test set must stay untouched by every choice: choosing by its error would make that error an optimistic estimate. A difference of one item out of is also within what chance alone produces.
17. Each lies in the region of another class: a parcel as thin and light as a packet, a packet as thin as a letter, a packet of only g, a parcel among the packets. Their neighbours are mostly of the other class.
18. distances.
19. With more labelled examples, or with one more feature that separates the classes, such as the length or width of the item.
20. With scaling, the office chooses , whose error on the untouched test set is ( items out of ), against for the baseline that always answers “packet”.