计算机科学 · 第 2 册 · 10–12 年级

High School Computer Science

本书暂未推出简体中文版。现有版本: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.

Sorting by hand: each item is weighed and measured, then put in the crate of its class.
Sorting by hand: each item is weighed and measured, then put in the crate of its class.

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:]
Listing 19.1. The invented items: a seeded generator, and a split into three parts. code/grade-11/08-k-nearest-neighbours/listings/parcels.py

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 180180 items to learn from, 6060 to make choices with, and 6060 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")
Listing 19.2. A first look at the items. code/grade-11/08-k-nearest-neighbours/listings/show_data.py
$ 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
Output 19.1. Three hundred items, three classes, five shown, and the split.
The 180 items of the training set. Letters sit near the corner; packets and parcels overlap over a wide band.
The 180180 items of the training set. Letters sit near the corner; packets and parcels overlap over a wide band.

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))
Listing 19.3. The Euclidean distance between two items. code/grade-11/08-k-nearest-neighbours/listings/distance.py
$ python distance.py
letter-packet: 250.57733337235433
packet-parcel: 32.01562118716424
Output 19.2. The packet looks closer to the parcel than to the letter.

The output hides a trap. The packet and the parcel differ by 2525 mm, the letter and the packet by 1717 mm; yet the distances say the opposite of what the eye sees on the thicknesses, because they are almost only differences of mass: 250250 g counts as 250250, a millimetre counts as 11. 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 vv of a feature by (v−lo)/(hi−lo)(v - \mathit{lo}) / (\mathit{hi} - \mathit{lo}), where lo\mathit{lo} and hi\mathit{hi} are the smallest and largest values of that feature in the training set; the results lie between 00 and 11 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))
Listing 19.4. Min-max scaling, computed on the training set, and the new neighbours. code/grade-11/08-k-nearest-neighbours/listings/scale.py
$ 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
Output 19.3. After scaling, the seven nearest items to 1212 mm, 150150 g.

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 xx from a training set, with a whole number k≥1k \ge 1:

  1. compute the distance from xx to every example of the training set;
  2. keep the kk examples with the smallest distances, the kk nearest neighbours;
  3. 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)))
Listing 19.5. The vote of the kk nearest neighbours, and one new item. code/grade-11/08-k-nearest-neighbours/listings/knn.py
$ 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}
Output 19.4. Without scaling: the seven nearest to 1212 mm, 150150 g, and the votes for k=1k = 1, 33, 77.
A new item x and its five nearest neighbours, joined to it; the dashed circle passes through the fifth. Four of the five are squares, so x is given the class of the squares.
A new item xx and its five nearest neighbours, joined to it; the dashed circle passes through the fifth. Four of the five are squares, so xx is given the class of the squares.

With k=1k = 1 the answer follows the single nearest example, however unusual it is; a larger kk 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.

The class predicted at each point of a grid, with scaled features: blue for letter, green for packet, red for parcel. With k = 1 the frontier between packet and parcel is ragged and leaves islands; with k = 7 it is smoother.
The class predicted at each point of a grid, with scaled features: blue for letter, green for packet, red for parcel. With k=1k = 1 the frontier between packet and parcel is ragged and leaves islands; with k=7k = 7 it is smoother.

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, k=1k = 1 never errs: each example’s nearest neighbour is itself, at distance 00. 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%}")
Listing 19.6. The error rate for each kk, on the training set and on the validation set. code/grade-11/08-k-nearest-neighbours/listings/error_rate.py
$ 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%
Output 19.5. The training error is 00 for k=1k = 1 and 22; the validation error tells more.

Choosing kk is itself a kind of learning: the 6060 validation items serve to choose, and the 6060 test items, never used for any choice, give the honest final error. If kk 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)
Listing 19.7. The smallest kk with the fewest validation errors. code/grade-11/08-k-nearest-neighbours/listings/choose_k.py
$ python choose_k.py
lowest validation error: 5.0% for k in [5, 7, 8, 9, 11]
chosen: k = 5
Output 19.6. Five values of kk tie; the smallest is chosen.
The validation error against k. Scaling lowers it for every k: with scaled features it stays between 5 and 10\,\%, while without scaling it climbs towards 20\,\% as k grows.
The validation error against kk. Scaling lowers it for every kk: with scaled features it stays between 55 and 10 %10\,\%, while without scaling it climbs towards 20 %20\,\% as kk grows.

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 nn examples, each prediction computes nn 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")
Listing 19.8. Counting the distances computed. code/grade-11/08-k-nearest-neighbours/listings/knn_cost.py
$ python knn_cost.py
 60 predictions (validation) with 180 examples: 10800 distances
120 predictions (both) with 180 examples: 21600 distances
Output 19.7. 180180 distances per prediction, whatever kk.

For mm predictions, m×nm \times n distances, each taking a few operations per feature: a cost that grows like m×n×dm \times n \times d with dd features, plus the sorts. A post office handling a million items a day with a million examples would compute 101210^{12} 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 k=1k = 1 is at most twice the smallest error any rule could reach.

19.6 Exercises

Exercise 19.1 ★

Compute the distance between the items (2 mm,30 g)(2~\text{mm}, 30~\text{g}) and (5 mm,34 g)(5~\text{mm}, 34~\text{g}), without scaling.

Solution

Solution of Exercise 19.1.

(5−2)2+(34−30)2=9+16=5\sqrt{(5 - 2)^2 + (34 - 30)^2} = \sqrt{9 + 16} = 5.

Exercise 19.2 ★

A tiny training set: A at (1,1)(1, 1), A at (2,1)(2, 1), B at (4,3)(4, 3), B at (5,4)(5, 4), A at (3,2)(3, 2). Which class does the method predict for (4,4)(4, 4) with k=3k = 3?

Solution

Solution of Exercise 19.2.

Distances from (4,4)(4, 4): B (4,3)(4, 3) and B (5,4)(5, 4) at 11, A (3,2)(3, 2) at 5≈2.24\sqrt{5} \approx 2.24, A (2,1)(2, 1) at 13\sqrt{13}, A (1,1)(1, 1) at 18\sqrt{18}. 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 (3.5,3)(3.5, 3).

Solution

Solution of Exercise 19.3.

(4,3)(4, 3) at 0.50.5; (3,2)(3, 2) at 1.25≈1.12\sqrt{1.25} \approx 1.12; (5,4)(5, 4) at 3.25≈1.80\sqrt{3.25} \approx 1.80; (2,1)(2, 1) at 6.25=2.5\sqrt{6.25} = 2.5; (1,1)(1, 1) at 10.25≈3.20\sqrt{10.25} \approx 3.20.

Exercise 19.4 ★

A confusion table counts, for each true class (row), the predicted classes (columns). Compute the error rate.

true \ predictedletterpacketparcel
letter25251100
packet11171711
parcel00111414
Solution

Solution of Exercise 19.4.

6060 items in all; the diagonal, 25+17+14=5625 + 17 + 14 = 56, is right; 44 errors: 4/60≈6.7 %4/60 \approx 6.7\,\%.

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 00 for every data set. Find the fault and correct it.

Solution

Solution of Exercise 19.6.

Each item is among the examples it is predicted from: its nearest neighbour is itself, at distance 00, and votes for its own class. The item must be left out: predict x = items[i] from items[:i] + items[i + 1:], as in exercise 19.13.

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 100100 random sets.

Exercise 19.8 ★★

In the training set, thickness runs from 0.50.5 to 84.784.7 mm and mass from 55 to 12311231 g. Compute, with and without scaling, the distances from the new item (12,150)(12, 150) to (5.3,159)(5.3, 159) and to (13.9,133)(13.9, 133). Which is nearer in each case?

Solution

Solution of Exercise 19.8.

Without scaling: to (5.3,159)(5.3, 159), 6.72+92≈11.2\sqrt{6.7^2 + 9^2} \approx 11.2; to (13.9,133)(13.9, 133), 1.92+172≈17.1\sqrt{1.9^2 + 17^2} \approx 17.1: the first is nearer. With scaling, the differences are divided by 84.284.2 and 12261226: to (5.3,159)(5.3, 159), 0.07962+0.00732≈0.080\sqrt{0.0796^2 + 0.0073^2} \approx 0.080; to (13.9,133)(13.9, 133), 0.02262+0.01392≈0.026\sqrt{0.0226^2 + 0.0139^2} \approx 0.026: the second is nearer, as the output of scale.py shows. Without scaling, 99 g weigh more than 6.76.7 mm; with it, 6.76.7 mm are a large part of the thickness range.

Exercise 19.9 ★★

A vote is written max(set(labels), key=labels.count), where labels is the list of the kk 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 00 for k=1k = 1. Explain why. Can it be different from 00 for some data?

Solution

Solution of Exercise 19.10.

Each training example is its own nearest neighbour, at distance 00, and its class is its own answer. It can differ from 00 if two examples have the same features and different classes: the sort may put the other one first. (With k=2k = 2 the output also shows 00: 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 00; it can simply be dropped, since it never separates two examples.

Exercise 19.12 ★★★

Give the cost of predicting mm items with nn examples and dd features, counting the operations on features for the distances and the comparisons for the sorts. What changes if the kk nearest are found by kk scans for the smallest remaining distance instead of a sort?

Solution

Solution of Exercise 19.12.

Each of the mm predictions computes nn distances of about 3d3d operations each (a subtraction, a square and an addition per feature): 3mnd3mnd, which grows like m×n×dm \times n \times d. Each prediction then sorts nn distances, about n⋅h(n)n \cdot h(n) comparisons with a good sort, where h(n)h(n) is the number of halvings of nn: in all about m(3nd+n⋅h(n))m(3nd + n \cdot h(n)). With kk scans for the smallest remaining distance, each scan makes about nn comparisons: knkn per prediction instead of n⋅h(n)n \cdot h(n), better when kk is smaller than h(n)h(n), as it is for k=5k = 5 and n=180n = 180 (h(180)=7h(180) = 7).

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 11 in a sum. On the scaled training set it gives, for k=1k = 1 to 1515, from 1414 to 2020 errors out of 180180, between 88 and 11 %11\,\%: 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 kk equals the number nn of training examples? What error rate does it then have on the validation set of the chapter?

Solution

Solution of Exercise 19.14.

All nn examples are neighbours, whatever xx: 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 33/60=55 %33/60 = 55\,\%.

Exercise 19.15 ★★★

Write weighted_predict(train, x, k), in which each of the kk neighbours votes with a weight 1/distance1/\text{distance}. On the scaled validation set it makes 55 errors with k=5k = 5, where the plain vote makes 33, but 33 errors for every kk from 66 to 1212. 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 00 when xx is an example. The weighted vote lets a very near neighbour outvote several far ones: it behaves more like a small kk when one neighbour is very close, and the far neighbours added by a larger kk change it less. Hence it makes fewer errors over a wide range of large kk, but not at every kk: on 6060 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 kk 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%}")
Listing 19.9. The baseline, the choice of kk and the final test. code/grade-11/08-k-nearest-neighbours/listings/sorting_office.py
$ 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%
Output 19.8. The baseline, the validation errors with and without scaling, and the final error.

Part I — The data and a baseline.

  1. What are the features, and what is the class, of an item?
  2. Why are the items invented and drawn from a seeded generator?
  3. The training set has 8484 packets, 5757 letters and 3939 parcels. Which class does the baseline always answer?
  4. The validation set has 2727 packets out of 6060. Check the baseline’s validation error.
  5. The test set has 1919 packets out of 6060. Check the baseline’s test error. Why does it differ from the validation error?

Part II — k-NN without scaling.

  1. From the unscaled column, what is the smallest validation error, and for which kk?
  2. How many validation items does a 20 %20\,\% error stand for?
  3. Why does the unscaled error grow with kk? Think of which feature decides the neighbours.
  4. Is the unscaled method still much better than the baseline?

Part III — Scaling.

  1. From the scaled column, which values of kk give the smallest validation error?
  2. The program keeps the first kk reaching the smallest error. Which kk is chosen?
  3. Why are the bounds of the scaling taken from the training set only?
  4. The scaled error for k=1k = 1 is 10 %10\,\%, for k=5k = 5 it is 5 %5\,\%. Explain the difference with the pictures of the decision regions.
  5. How many fewer validation errors does scaling make at k=5k = 5?

Part IV — The final test.

  1. What is the final test error, and how many test items does it stand for?
  2. With scaling, the test errors for k=1k = 1 to 1515 are 4,4,3,3,4,4,…4, 4, 3, 3, 4, 4, \dots: k=3k = 3 would have done better on the test set. Why must the office still keep k=5k = 5?
  3. The four test items in error are a parcel of 33.833.8 mm and 349349 g, a packet of 0.50.5 mm and 152152 g, a packet of 10.410.4 mm and 55 g, and a parcel of 20.920.9 mm and 573573 g. Why are they hard?
  4. Every prediction computes 180180 distances. How many for a day of 50005000 items?
  5. How could the office reduce the error further, without changing the method?
  6. State the result: the chosen kk, 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. 60−27=3360 - 27 = 33 wrong: 33/60=55 %33/60 = 55\,\%.

5. 60−19=4160 - 19 = 41 wrong: 41/60≈68.3 %41/60 \approx 68.3\,\%. The two sets are different random samples, with fewer packets in the test set.

6. 11.7 %11.7\,\%, for k=1k = 1, 22 and 44.

7. 0.2×60=120.2 \times 60 = 12 items.

8. Without scaling the mass decides almost alone. Packets and parcels overlap much more in mass than in thickness, so as kk grows, the neighbours by mass bring more items of the wrong class.

9. Yes: at worst 21.7 %21.7\,\%, against 55 %55\,\%.

10. k=5k = 5, 77, 88, 99 and 1111, at 5 %5\,\%.

11. k=5k = 5.

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 k=1k = 1, every isolated example of a class inside another class’s region makes an island, and new items near it are misclassified; with k=5k = 5 such an example is outvoted, and the frontier is smoother.

14. 15 %15\,\% is 99 errors, 5 %5\,\% is 33: six fewer.

15. 6.7 %6.7\,\%: 44 items out of 6060.

16. The test set must stay untouched by every choice: choosing kk by its error would make that error an optimistic estimate. A difference of one item out of 6060 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 55 g, a parcel among the packets. Their neighbours are mostly of the other class.

18. 5000×180=900 0005000 \times 180 = 900\,000 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 k=5k = 5, whose error on the untouched test set is 6.7 %6.7\,\% (44 items out of 6060), against 68.3 %68.3\,\% for the baseline that always answers “packet”.

本章定义的术语

在术语表中查看全部 1050 个术语