---
title: "Classifying by Neighbours: the k-NN Algorithm"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 19
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/19-classifying-by-neighbours-the-k-nn-algorithm
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 19 — Classifying 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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-k-nearest-neighbours/img-63492f1ad368.jpg)

*Sorting by hand: each item is weighed and measured, then put in the crate of its [class](#def-g11-k-nearest-neighbours-example).*

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](https://one-course.com/books/computer-science/2/en/chapter/4-floating-point-numbers#def-g10-floating-point-float) are approximations (chapter [4](https://one-course.com/books/computer-science/2/en/chapter/4-floating-point-numbers#ch-g10-floating-point)). `sorted(t, key=f)` sorts by a key (chapter [7](https://one-course.com/books/computer-science/2/en/chapter/7-processing-data-tables#ch-g10-data-tables)); the cost of an algorithm counts its [elementary operations](https://one-course.com/books/computer-science/2/en/chapter/17-the-cost-of-an-algorithm#def-g11-cost-of-an-algorithm-elementary) (chapter [17](https://one-course.com/books/computer-science/2/en/chapter/17-the-cost-of-an-algorithm#ch-g11-cost-of-an-algorithm)).

## 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.

```python
"""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](#def-g11-k-nearest-neighbours-example) a method learns from. A *test set* is a set of [labelled examples](#def-g11-k-nearest-neighbours-example) kept aside, never used for learning, on which the method’s answers are compared with the known classes.

The office keeps $180$ items to learn from, $60$ to make choices with, and $60$ that nobody looks at until the very end.

```python
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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-k-nearest-neighbours/fig-9d0d7e8af361.svg)

*The $180$ items of the [training set](#def-g11-k-nearest-neighbours-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](#def-g11-k-nearest-neighbours-example) 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.

```python
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 $25$ mm, the letter and the packet by $17$ mm; yet the distances say the opposite of what the eye sees on the thicknesses, because they are almost only differences of mass: $250$ g counts as $250$, a millimetre counts as $1$. The unit chosen for each [feature](#def-g11-k-nearest-neighbours-example) decides how much it weighs.

**Definition 19.3 (Scaling).**

*Scaling* the [features](#def-g11-k-nearest-neighbours-example) 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 $v$ of a [feature](#def-g11-k-nearest-neighbours-example) by $(v - \mathit{lo}) / (\mathit{hi} -
\mathit{lo})$, where $\mathit{lo}$ and $\mathit{hi}$ are the smallest and largest values of that [feature](#def-g11-k-nearest-neighbours-example) in the [training set](#def-g11-k-nearest-neighbours-training-set); the results lie between $0$ and $1$ on the [training set](#def-g11-k-nearest-neighbours-training-set).

```python
"""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](#def-g11-k-nearest-neighbours-scaling), computed on the [training set](#def-g11-k-nearest-neighbours-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](#def-g11-k-nearest-neighbours-scaling), the seven nearest items to $12$ mm, $150$ g.*

The bounds come from the [training set](#def-g11-k-nearest-neighbours-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](https://one-course.com/books/computer-science/2/en/chapter/4-floating-point-numbers#def-g10-floating-point-float); 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](#def-g11-k-nearest-neighbours-example) of a new item $x$ from a [training set](#def-g11-k-nearest-neighbours-training-set), with a whole number $k \ge 1$:

1. compute the distance from $x$ to every example of the [training set](#def-g11-k-nearest-neighbours-training-set) ;
2. keep the $k$ examples with the smallest distances, the $k$ nearest neighbours;
3. answer the [class](#def-g11-k-nearest-neighbours-example) that is most common among them; on a tie, a fixed rule decides, here the [class](#def-g11-k-nearest-neighbours-example) of the nearest of the tied ones.

```python
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 $k$ 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](#def-g11-k-nearest-neighbours-scaling): the seven nearest to $12$ mm, $150$ g, and the votes for $k = 1$, $3$, $7$.*

![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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-k-nearest-neighbours/fig-d72ca837f7f3.svg)

*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](#def-g11-k-nearest-neighbours-example) of the squares.*

With $k = 1$ the answer follows the single nearest example, however unusual it is; a larger $k$ smooths the answer by asking more examples. The two pictures below colour every point of the plane by the [class](#def-g11-k-nearest-neighbours-example) 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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-k-nearest-neighbours/fig-1823915798f0.svg)

*The [class](#def-g11-k-nearest-neighbours-example) predicted at each point of a grid, with scaled [features](#def-g11-k-nearest-neighbours-example): 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.*

## 19.4 Measuring the error

**Definition 19.5 (Error rate).**

The *error rate* of a method on a set of [labelled examples](#def-g11-k-nearest-neighbours-example) is the number of examples whose predicted [class](#def-g11-k-nearest-neighbours-example) differs from the known [class](#def-g11-k-nearest-neighbours-example), divided by the number of examples.

On which examples? On the [training set](#def-g11-k-nearest-neighbours-training-set) itself, $k = 1$ never errs: each example’s nearest neighbour is itself, at distance $0$. That says nothing about new items. The error must be measured on examples the method has not seen.

```python
"""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](#def-g11-k-nearest-neighbours-error-rate) for each $k$, on the [training set](#def-g11-k-nearest-neighbours-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 $0$ for $k = 1$ and $2$; the validation error tells more.*

Choosing $k$ is itself a kind of learning: the $60$ validation items serve to choose, and the $60$ test items, never used for any choice, give the honest final error. If $k$ were chosen on the test items, their error would flatter the method.

```python
"""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 $k$ 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 $k$ 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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-k-nearest-neighbours/fig-c4a786b6d110.svg)

*The validation error against $k$. [Scaling](#def-g11-k-nearest-neighbours-scaling) lowers it for every $k$: with scaled [features](#def-g11-k-nearest-neighbours-example) it stays between $5$ and $10\,\%$, while without [scaling](#def-g11-k-nearest-neighbours-scaling) it climbs towards $20\,\%$ as $k$ grows.*

## 19.5 What the method cannot do, and its cost

The method learns nothing in advance: it keeps the whole [training set](#def-g11-k-nearest-neighbours-training-set) and does all its work at each prediction. With $n$ examples, each prediction computes $n$ distances, then sorts them.

```python
"""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.** $180$ distances per prediction, whatever $k$.*

For $m$ predictions, $m \times n$ distances, each taking a few operations per [feature](#def-g11-k-nearest-neighbours-example): a cost that grows like $m \times n \times d$ with $d$ [features](#def-g11-k-nearest-neighbours-example), plus the sorts. A post office handling a million items a day with a million examples would compute $10^{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](#def-g11-k-nearest-neighbours-example), 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 = 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~\text{mm}, 30~\text{g})$ and $(5~\text{mm}, 34~\text{g})$, without [scaling](#def-g11-k-nearest-neighbours-scaling).

**Solution of Exercise 19.1.**

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

**Exercise 19.2 ★.**

A tiny [training set](#def-g11-k-nearest-neighbours-training-set): A at $(1, 1)$, A at $(2, 1)$, B at $(4, 3)$, B at $(5, 4)$, A at $(3, 2)$. Which [class](#def-g11-k-nearest-neighbours-example) does the method predict for $(4, 4)$ with $k = 3$?

**Solution of Exercise 19.2.**

Distances from $(4, 4)$: B $(4, 3)$ and B $(5, 4)$ at $1$, A $(3, 2)$ at $\sqrt{5} \approx 2.24$, A $(2, 1)$ at $\sqrt{13}$, A $(1, 1)$ at $\sqrt{18}$. The three nearest are B, B, A: [class](#def-g11-k-nearest-neighbours-example) B.

**Exercise 19.3 ★.**

With the same [training set](#def-g11-k-nearest-neighbours-training-set), list the five examples from the nearest to the farthest from $(3.5, 3)$.

**Solution of Exercise 19.3.**

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

**Exercise 19.4 ★.**

A confusion table counts, for each true [class](#def-g11-k-nearest-neighbours-example) (row), the predicted classes (columns). Compute the [error rate](#def-g11-k-nearest-neighbours-error-rate).

| true \ predicted | letter | packet | parcel |
| --- | --- | --- | --- |
| letter | $25$ | $1$ | $0$ |
| packet | $1$ | $17$ | $1$ |
| parcel | $0$ | $1$ | $14$ |

**Solution of Exercise 19.4.**

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

**Exercise 19.5 ★.**

Write `distance(a, b)` for items with any number of [features](#def-g11-k-nearest-neighbours-example), the label being the last element of each tuple.

**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](#def-g11-k-nearest-neighbours-example) in order.

**Exercise 19.6 ★★.**

To estimate the error without a validation set, a student predicts each item of the [training set](#def-g11-k-nearest-neighbours-training-set) with `predict(items, x, 1)` of the chapter, and finds an error of $0$ for every data set. Find the fault and correct it.

**Solution of Exercise 19.6.**

Each item is among the examples it is predicted from: its nearest neighbour is itself, at distance $0$, and votes for its own [class](#def-g11-k-nearest-neighbours-example). The item must be left out: predict `x = items[i]` from `items[:i] + items[i + 1:]`, as in exercise [19.13](#exo-g11-k-nearest-neighbours-13).

**Exercise 19.7 ★★.**

Write `knn_predict(train, x, k)`, with ties broken by the [class](#def-g11-k-nearest-neighbours-example) of the nearest of the tied ones.

**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 $100$ random sets.

**Exercise 19.8 ★★.**

In the [training set](#def-g11-k-nearest-neighbours-training-set), thickness runs from $0.5$ to $84.7$ mm and mass from $5$ to $1231$ g. Compute, with and without [scaling](#def-g11-k-nearest-neighbours-scaling), the distances from the new item $(12, 150)$ to $(5.3, 159)$ and to $(13.9, 133)$. Which is nearer in each case?

**Solution of Exercise 19.8.**

Without [scaling](#def-g11-k-nearest-neighbours-scaling): to $(5.3, 159)$, $\sqrt{6.7^2 + 9^2} \approx 11.2$; to $(13.9, 133)$, $\sqrt{1.9^2 + 17^2} \approx
17.1$: the first is nearer. With [scaling](#def-g11-k-nearest-neighbours-scaling), the differences are divided by $84.2$ and $1226$: to $(5.3, 159)$, $\sqrt{0.0796^2 + 0.0073^2} \approx 0.080$; to $(13.9, 133)$, $\sqrt{0.0226^2 + 0.0139^2} \approx 0.026$: the second is nearer, as the output of `scale.py` shows. Without [scaling](#def-g11-k-nearest-neighbours-scaling), $9$ g weigh more than $6.7$ mm; with it, $6.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 $k$ neighbours’ classes. On some items the program answers differently from one run to the next. Why?

**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](#def-g11-k-nearest-neighbours-example) of the nearest tied neighbour, removes the problem.

**Exercise 19.10 ★★.**

In the output of `error_rate.py`, the training error is $0$ for $k = 1$. Explain why. Can it be different from $0$ for some data?

**Solution of Exercise 19.10.**

Each training example is its own nearest neighbour, at distance $0$, and its [class](#def-g11-k-nearest-neighbours-example) is its own answer. It can differ from $0$ if two examples have the same [features](#def-g11-k-nearest-neighbours-example) and different classes: the sort may put the other one first. (With $k = 2$ the output also shows $0$: the second neighbour can only tie, and the tie goes to the nearest.)

**Exercise 19.11 ★★.**

Write `minmax(train)`, which returns a function [scaling](#def-g11-k-nearest-neighbours-scaling) an item with bounds taken from `train`, for any number of [features](#def-g11-k-nearest-neighbours-example).

**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](#def-g11-k-nearest-neighbours-example) with the same value everywhere would divide by $0$; it can simply be dropped, since it never separates two examples.

**Exercise 19.12 ★★★.**

Give the cost of predicting $m$ items with $n$ examples and $d$ [features](#def-g11-k-nearest-neighbours-example), counting the operations on [features](#def-g11-k-nearest-neighbours-example) for the distances and the comparisons for the sorts. What changes if the $k$ nearest are found by $k$ scans for the smallest remaining distance instead of a sort?

**Solution of Exercise 19.12.**

Each of the $m$ predictions computes $n$ distances of about $3d$ operations each (a subtraction, a square and an addition per [feature](#def-g11-k-nearest-neighbours-example)): $3mnd$, which grows like $m \times n \times d$. Each prediction then sorts $n$ distances, about $n \cdot h(n)$ comparisons with a good sort, where $h(n)$ is the [number of halvings](https://one-course.com/books/computer-science/2/en/chapter/17-the-cost-of-an-algorithm#def-g11-cost-of-an-algorithm-halvings) of $n$: in all about $m(3nd + n \cdot h(n))$. With $k$ scans for the smallest remaining distance, each scan makes about $n$ comparisons: $kn$ per prediction instead of $n \cdot h(n)$, better when $k$ is smaller than $h(n)$, as it is for $k = 5$ and $n = 180$ ($h(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](#def-g11-k-nearest-neighbours-error-rate) is computed over all the items.

**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 $1$ in a sum. On the scaled [training set](#def-g11-k-nearest-neighbours-training-set) it gives, for $k = 1$ to $15$, from $14$ to $20$ errors out of $180$, between $8$ and $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 $k$ equals the number $n$ of training examples? What [error rate](#def-g11-k-nearest-neighbours-error-rate) does it then have on the validation set of the chapter?

**Solution of Exercise 19.14.**

All $n$ examples are neighbours, whatever $x$: the vote always gives the most common [class](#def-g11-k-nearest-neighbours-example) of the [training set](#def-g11-k-nearest-neighbours-training-set). The method becomes the baseline, here always “packet”, with a validation error of $33/60 = 55\,\%$.

**Exercise 19.15 ★★★.**

Write `weighted_predict(train, x, k)`, in which each of the $k$ neighbours votes with a weight $1/\text{distance}$. On the scaled validation set it makes $5$ errors with $k = 5$, where the plain vote makes $3$, but $3$ errors for every $k$ from $6$ to $12$. What do the two votes do differently?

**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 $0$ when $x$ is an example. The weighted vote lets a very near neighbour outvote several far ones: it behaves more like a small $k$ when one neighbour is very close, and the far neighbours added by a larger $k$ change it less. Hence it makes fewer errors over a wide range of large $k$, but not at every $k$: on $60$ 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](#def-g11-k-nearest-neighbours-example) of the [training set](#def-g11-k-nearest-neighbours-training-set), then chooses $k$ and the [scaling](#def-g11-k-nearest-neighbours-scaling) on the validation set, and finally measures the error once, on the [test set](#def-g11-k-nearest-neighbours-training-set).

```python
"""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 $k$ 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](#def-g11-k-nearest-neighbours-scaling), and the final error.*

**Part I — The data and a baseline.**

1. What are the [features](#def-g11-k-nearest-neighbours-example) , and what is the [class](#def-g11-k-nearest-neighbours-example) , of an item?
2. Why are the items invented and drawn from a seeded generator?
3. The [training set](#def-g11-k-nearest-neighbours-training-set) has $84$ packets, $57$ letters and $39$ parcels. Which [class](#def-g11-k-nearest-neighbours-example) does the baseline always answer?
4. The validation set has $27$ packets out of $60$ . Check the baseline’s validation error.
5. The [test set](#def-g11-k-nearest-neighbours-training-set) has $19$ packets out of $60$ . Check the baseline’s test error. Why does it differ from the validation error?

**Part II — k-NN without scaling.**

6. From the unscaled column, what is the smallest validation error, and for which $k$ ?
7. How many validation items does a $20\,\%$ error stand for?
8. Why does the unscaled error grow with $k$ ? Think of which [feature](#def-g11-k-nearest-neighbours-example) decides the neighbours.
9. Is the unscaled method still much better than the baseline?

**Part III — Scaling.**

10. From the scaled column, which values of $k$ give the smallest validation error?
11. The program keeps the first $k$ reaching the smallest error. Which $k$ is chosen?
12. Why are the bounds of the [scaling](#def-g11-k-nearest-neighbours-scaling) taken from the [training set](#def-g11-k-nearest-neighbours-training-set) only?
13. The scaled error for $k = 1$ is $10\,\%$ , for $k = 5$ it is $5\,\%$ . Explain the difference with the pictures of the decision regions.
14. How many fewer validation errors does [scaling](#def-g11-k-nearest-neighbours-scaling) make at $k = 5$ ?

**Part IV — The final test.**

15. What is the final test error, and how many test items does it stand for?
16. With [scaling](#def-g11-k-nearest-neighbours-scaling) , the test errors for $k = 1$ to $15$ are $4, 4, 3, 3, 4, 4, \dots$ : $k = 3$ would have done better on the [test set](#def-g11-k-nearest-neighbours-training-set) . Why must the office still keep $k = 5$ ?
17. The four test items in error are a parcel of $33.8$ mm and $349$ g, a packet of $0.5$ mm and $152$ g, a packet of $10.4$ mm and $5$ g, and a parcel of $20.9$ mm and $573$ g. Why are they hard?
18. Every prediction computes $180$ distances. How many for a day of $5000$ items?
19. How could the office reduce the error further, without changing the method?
20. State the result: the chosen $k$ , its test error, and the baseline’s test error.

**Solution of Problem 19.1.**

**1.** The [features](#def-g11-k-nearest-neighbours-example) are the thickness in millimetres and the mass in grams; the [class](#def-g11-k-nearest-neighbours-example) 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 = 33$ wrong: $33/60 = 55\,\%$.

**5.** $60 - 19 = 41$ wrong: $41/60 \approx 68.3\,\%$. The two sets are different random samples, with fewer packets in the [test set](#def-g11-k-nearest-neighbours-training-set).

**6.** $11.7\,\%$, for $k = 1$, $2$ and $4$.

**7.** $0.2 \times 60 = 12$ items.

**8.** Without [scaling](#def-g11-k-nearest-neighbours-scaling) the mass decides almost alone. Packets and parcels overlap much more in mass than in thickness, so as $k$ grows, the neighbours by mass bring more items of the wrong [class](#def-g11-k-nearest-neighbours-example).

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

**10.** $k = 5$, $7$, $8$, $9$ and $11$, at $5\,\%$.

**11.** $k = 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 = 1$, every isolated example of a [class](#def-g11-k-nearest-neighbours-example) inside another [class](#def-g11-k-nearest-neighbours-example)’s region makes an island, and new items near it are misclassified; with $k = 5$ such an example is outvoted, and the frontier is smoother.

**14.** $15\,\%$ is $9$ errors, $5\,\%$ is $3$: six fewer.

**15.** $6.7\,\%$: $4$ items out of $60$.

**16.** The [test set](#def-g11-k-nearest-neighbours-training-set) must stay untouched by every choice: choosing $k$ by its error would make that error an optimistic estimate. A difference of one item out of $60$ is also within what chance alone produces.

**17.** Each lies in the region of another [class](#def-g11-k-nearest-neighbours-example): a parcel as thin and light as a packet, a packet as thin as a letter, a packet of only $5$ g, a parcel among the packets. Their neighbours are mostly of the other [class](#def-g11-k-nearest-neighbours-example).

**18.** $5000 \times 180 = 900\,000$ distances.

**19.** With more [labelled examples](#def-g11-k-nearest-neighbours-example), or with one more [feature](#def-g11-k-nearest-neighbours-example) that separates the classes, such as the length or width of the item.

**20.** With [scaling](#def-g11-k-nearest-neighbours-scaling), the office **chooses $k = 5$, whose error on the untouched [test set](#def-g11-k-nearest-neighbours-training-set) is $6.7\,\%$** ($4$ items out of $60$), **against $68.3\,\%$ for the baseline** that always answers “packet”.
