এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
University Computer Science — Year 2 · স্নাতক দ্বিতীয় বর্ষ
29Learning from Examples: Decision Trees and Clustering
The library would like to know, when a book goes out, whether it will come back late. Nobody has written down the rule, if there is one; there are only past loans, each with a few facts and the answer. A program can look for the rule in them:
if __name__ == "__main__":
train, test = loans(700, seed=1), loans(300, seed=2)
tree = id3(train)
show(tree)
print(f"depth {depth(tree)}; test accuracy {accuracy(tree, test):.3f}")
$ python id3.py
prior <= 1.5
-> on time (on time 448, late 0)
prior > 1.5
distance <= 2490
-> on time (on time 95, late 0)
distance > 2490
-> late (on time 0, late 157)
depth 2; test accuracy 1.000
The program was given five facts per loan: the days lent, the book’s pages, the member’s age, how many books the member has already returned late, and how far from the library the member lives. It kept two of them and found a rule of two questions: a member with at least two late returns who lives more than about 2.5 km away brings the book back late. The loans were generated, and that is exactly the rule that was planted in them, so the program can be checked. Real data are not so kind: labels are noisy, and a program that fits its examples too closely learns the noise. This chapter builds the vocabulary and the tools to measure that, then turns to examples with no answer at all, where the task is to find groups.
You already know
The grade 11 volume: the -nearest-neighbour classifier, distances between points, training and test examples. The Year 1 volume: trees and their traversals, Kruskal’s algorithm for the minimum spanning tree, with union–find. The mathematics books: probability of an event, mean, the logarithm in base 2. Chapter 27: seeded pseudo-random numbers.
29.1 Learning as an algorithmic problem
Definition 29.1 (Example, feature, class label, training set, test set)
An example is a vector of values, its features, possibly with a class label, the answer to be predicted, taken from a finite set. A training set is a set of labelled examples given to a learning algorithm; a test set is a set of labelled examples, drawn from the same source, that the algorithm never sees and that serves only to measure the result.
Definition 29.2 (Supervised and unsupervised learning, classifier)
In supervised learning, an algorithm receives labelled examples and returns a classifier, a function from feature vectors to class labels. In unsupervised learning, the examples have no labels and the algorithm looks for structure in them, such as groups.
A classifier is useful only on examples it has not seen: a table of the training examples would answer all of them correctly and say nothing about the next loan. Hence the test set, kept apart until the end.
Definition 29.3 (Confusion matrix, accuracy)
The confusion matrix of a classifier on a labelled set counts, for each pair of classes , the examples of true class that it labels . Its accuracy is the fraction of the examples on the diagonal, those labelled correctly.
train, test = loans(700, seed=1, noise=0.15), loans(300, seed=2, noise=0.15)
tree = id3(train, max_depth=2)
m = [[0, 0], [0, 0]] # m[true][predicted]
for x, y in test:
m[y][predict(tree, x)] += 1
print(" predicted on time predicted late")
print(f"on time {m[0][0]:17} {m[0][1]:15}")
print(f"late {m[1][0]:17} {m[1][1]:15}")
late = m[1][0] + m[1][1]
print(f"accuracy {(m[0][0] + m[1][1]) / len(test):.3f};",
f"always 'on time' would score {(len(test) - late) / len(test):.3f}")
print(f"late loans caught: {m[1][1]} of {late}; false alarms: {m[0][1]}")
$ python confusion.py
predicted on time predicted late
on time 224 9
late 32 35
accuracy 0.863; always 'on time' would score 0.777
late loans caught: 35 of 67; false alarms: 9
Accuracy alone can mislead when one class is rare: a classifier that always answers “on time” scores 0.777 here, without learning anything. The matrix shows that the tree catches about half the late loans and raises few false alarms. The late loans it misses are mostly noise: their label was flipped at random, and no rule can predict them.
29.2 Nearest neighbours and -d trees
Definition 29.4 (-nearest-neighbour classifier)
The -nearest-neighbour classifier labels a feature vector with the most frequent label among the training examples closest to in Euclidean distance, breaking ties by the label of the nearest of them.
The grade 11 volume met this classifier on two features; here it runs on five. A distance adds up differences of features measured in different units, days, pages and metres, so the features are first rescaled to by their range on the training set; without it, the distance in metres would decide alone (Exercise 29.2).
def scaler(train, features=FEATURES):
lo = {f: min(x[f] for x, _ in train) for f in features}
hi = {f: max(x[f] for x, _ in train) for f in features}
return lambda x: [(x[f] - lo[f]) / (hi[f] - lo[f]) for f in features]
def knn_classify(train_vectors, query, k):
"""The majority label among the k training vectors closest to query; a tie goes
to the label of the nearest of them. Cost: one distance per training example."""
def d2(vy):
return sum((a - b) ** 2 for a, b in zip(vy[0], query))
near = sorted(train_vectors, key=d2)[:k]
counts = Counter(y for _, y in near).most_common()
if len(counts) > 1 and counts[0][1] == counts[1][1]:
return near[0][1]
return counts[0][0]
def evaluate(train, test, k, features=FEATURES, scale=True):
s = scaler(train, features) if scale else (lambda x: [x[f] for f in features])
tv = [(s(x), y) for x, y in train]
return sum(knn_classify(tv, s(x), k) == y for x, y in test) / len(test)
$ python knn.py
k = 1: test accuracy 0.753 | prior and distance only: 0.760
k = 3: test accuracy 0.797 | prior and distance only: 0.837
k = 5: test accuracy 0.843 | prior and distance only: 0.860
k = 9: test accuracy 0.837 | prior and distance only: 0.863
k = 15: test accuracy 0.837 | prior and distance only: 0.853
k = 25: test accuracy 0.827 | prior and distance only: 0.863
each answer computed 700 distances in 5 dimensions
With the classifier copies the noise of the nearest example; a larger averages it out. The three features that play no part in the rule still enter every distance and blur it: dropping them helps. A decision tree, below, chooses its features itself.
Proposition 29.5 (Cost of -nearest neighbours)
With training examples of features, the classifier needs no training beyond storing them, in memory, and labelling one query by computing all distances costs time.
Proof. Each of the distances costs . The smallest of numbers are found by a pass that keeps a heap of the best so far, at per number; the vote then costs . (The listing sorts all , at .) ∎
Computing every distance is wasteful when the points live in a space of few dimensions: most are obviously far away.
Definition 29.6 (-d tree)
A -d tree of a set of points in is a binary tree with one point per node. A node at depth splits on coordinate : the points of its left subtree have that coordinate at most the node’s, those of its right subtree at least the node’s. Built by medians, it takes the point of median coordinate as the node, and so has depth .
def build(points, depth=0):
"""A node is (point, axis, left, right): the points of the left subtree have their
coordinate on the axis at most the node's, those of the right one at least."""
if not points:
return None
axis = depth % 2
points = sorted(points, key=lambda p: p[axis])
m = len(points) // 2
left, right = build(points[:m], depth + 1), build(points[m + 1:], depth + 1)
return (points[m], axis, left, right)
def dist2(p, q):
return (p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2
def nearest(node, q, best=None, visited=None):
"""(best point, its squared distance); visited[0] counts the nodes looked at."""
if node is None:
return best
if visited is not None:
visited[0] += 1
p, axis, left, right = node
if best is None or dist2(p, q) < best[1]:
best = (p, dist2(p, q))
near, far = (left, right) if q[axis] <= p[axis] else (right, left)
best = nearest(near, q, best, visited)
if (q[axis] - p[axis]) ** 2 < best[1]: # the circle crosses the splitting line
best = nearest(far, q, best, visited)
return best
figs.py from kdtree.py.Proposition 29.7 (Nearest-neighbour search in a -d tree)
The function nearest of Listing 29.4 returns a point of the tree nearest to .
Proof. It visits every node except the subtrees it skips, and keeps the closest point visited; it suffices that no skipped subtree holds a point strictly closer than the best at the time of the skip, since the best only improves. Let the node be , splitting on axis , and suppose : the skipped subtree is the right one, whose points have , so . The subtree is skipped only when is at least the best squared distance, so no point of it is strictly closer. The case is the same with the left subtree, whose points have . ∎
$ python kdtree.py
n mean nodes visited most visited brute force
100 10.8 21 100
1000 15.1 35 1000
10000 19.2 43 10000
100000 23.0 45 100000
On uniform random points in the plane, the search visits a few nodes per level of the tree: 23 out of 100,000 on average. That is an observation, not a bound: points arranged to be all at nearly the same distance from the query force the search to visit every node (Exercise 29.12), and in many dimensions the pruning test rarely succeeds, so -d trees pay off only when the dimension is small.
History
Jon Bentley published multidimensional binary search trees, the -d trees, in 1975.
29.3 Decision trees
Definition 29.8 (Decision tree)
A decision tree is a binary tree whose internal nodes carry a test on a feature with a threshold , and whose leaves carry a class label. It labels an example by following the branch of each test, left when the test holds, down to a leaf.
To choose the first question, a program needs to measure how mixed the labels are, and how much a question unmixes them.
Definition 29.9 (Entropy, information gain)
The entropy of a finite probability distribution is , with ; the entropy of a set of labelled examples is that of the frequencies of its labels. A split of a set into and has information gain
The entropy is for a set with a single label and , its largest value, for labels in equal numbers: one bit for a fair coin. The gain is how much the split lowers the entropy, on average over the two parts.
Proposition 29.10 (Information gain is never negative)
Every split has .
Proof. For two labels: write for the entropy of a set with a fraction of the first label. Its second derivative on is , so is concave on . If and have fractions and and , then has fraction , and concavity gives , which is . With more labels the same argument applies to the entropy as a function of the vector of frequencies, which is concave too; we admit that case. ∎
Method 29.11 (ID3 with binary splits)
To grow a tree on a set of labelled examples: if no split of of the form has positive gain, or the depth limit is reached, return a leaf with the majority label of . Otherwise take the split of largest gain, with halfway between two consecutive values of in , and grow the two subtrees on the two parts.
def entropy(counts):
"""The entropy in bits of a distribution given by counts, a Counter."""
n = sum(counts.values())
return -sum(c / n * math.log2(c / n) for c in counts.values() if c)
def best_split(data):
"""The (gain, feature, threshold) of largest information gain, or None."""
labels = Counter(y for _, y in data)
h, n, best = entropy(labels), len(data), None
for f in FEATURES:
pairs = sorted((x[f], y) for x, y in data)
left, right = Counter(), Counter(labels)
for i in range(n - 1):
v, y = pairs[i]
left[y] += 1
right[y] -= 1
if v == pairs[i + 1][0]:
continue # a threshold must separate distinct values
k = i + 1 # examples on the left
gain = h - k / n * entropy(left) - (n - k) / n * entropy(right)
if gain > 1e-12 and (best is None or gain > best[0] + 1e-12):
best = (gain, f, (v + pairs[i + 1][0]) / 2)
return best
def id3(data, max_depth=99):
"""A tree: ("leaf", label, counts) or ("split", feature, threshold, left, right),
the left branch for the values at most the threshold."""
counts = Counter(y for _, y in data)
split = best_split(data) if max_depth > 0 else None
if split is None: # pure, or no split gains anything, or the depth is reached
return ("leaf", int(counts[1] > counts[0]), (counts[0], counts[1]))
_, f, t = split
left = [(x, y) for x, y in data if x[f] <= t]
right = [(x, y) for x, y in data if x[f] > t]
return ("split", f, t, id3(left, max_depth - 1), id3(right, max_depth - 1))
Sorting the examples on each feature lets the sweep move one example at a time from right to left and update the label counts in constant time, so the best split of examples on features costs . A split on a set whose examples all carry the same label has no positive gain, so ID3 stops on pure sets; it also stops when no question helps, which a depth limit makes earlier.
Definition 29.12 (Overfitting)
A classifier overfits its training set when its accuracy there is much higher than on new examples from the same source, and a simpler classifier, built from the same training set, does better on the new examples.
On noiseless loans, the tree stopped by itself at depth 2. On loans whose labels are flipped with probability , every flipped label is an exception that a deeper tree can isolate with more questions:
train, test = loans(700, seed=1, noise=0.15), loans(300, seed=2, noise=0.15)
print("depth leaves train test")
for d in [0, 1, 2, 3, 4, 5, 6, 8, 10, 12, 16]:
tree = id3(train, max_depth=d)
leaves = str(tree).count("'leaf'")
print(f"{d:5} {leaves:7} {accuracy(tree, train):6.3f} {accuracy(tree, test):6.3f}")
$ python overfit.py
depth leaves train test
0 1 0.701 0.777
1 2 0.744 0.743
2 4 0.847 0.863
3 8 0.850 0.860
4 16 0.857 0.850
5 24 0.869 0.833
6 36 0.883 0.827
8 62 0.906 0.810
10 94 0.950 0.773
12 122 0.990 0.733
16 131 1.000 0.740
The depth limit is not learned from the training set, which always prefers the deepest tree. It is chosen on examples held out for that purpose, a validation set, or by cross-validation (Exercise 29.7); the test set is looked at once, at the end.
History
Ross Quinlan published ID3, decision trees grown by information gain, in 1986.
29.4 Clustering by -means
Definition 29.13 (Clustering, centroid, -means cost)
A clustering of a finite set of points into clusters is a partition of into parts, given by an assignment . The centroid of a non-empty finite set is the mean of its points. Given centres , the -means cost of an assignment is .
Lemma 29.14 (The centroid minimises the squared distances)
For a non-empty finite set with centroid and any point , . In particular is the unique point that minimises the sum.
Proof. Write and expand the square: the cross terms add up to , which is by the definition of . ∎
Method 29.15 (Lloyd’s algorithm)
Start from centres, for example points of drawn at random. Repeat: assign each point to its nearest centre (the lowest index on a tie); if the assignment has not changed, stop; otherwise move each centre to the centroid of its cluster, or leave it in place if its cluster is empty.
def assign(points, centres):
"""The index of the nearest centre of each point (the first one on a tie)."""
return [min(range(len(centres)), key=lambda j: d2(p, centres[j])) for p in points]
def cost(points, centres, a):
return sum(d2(p, centres[j]) for p, j in zip(points, a))
def lloyd(points, centres):
"""Alternate the two steps until the assignment no longer changes; return the
centres, the assignment and the cost after each assignment step."""
a, costs = None, []
while True:
new = assign(points, centres)
costs.append(cost(points, centres, new))
if new == a:
return centres, a, costs
a = new
centres = [centroid([p for p, j in zip(points, a) if j == i]) or centres[i]
for i in range(len(centres))] # an empty cluster keeps its centre
def centroid(group):
if not group:
return None
n = len(group)
return (sum(p[0] for p in group) / n, sum(p[1] for p in group) / n)
Theorem 29.16 (Lloyd’s algorithm stops)
The cost never increases from one assignment to the next, and the algorithm stops after finitely many iterations.
Proof. Exercise 29.8: the assignment step can only lower each point’s term, the centroid step can only lower each cluster’s sum by Lemma 29.14, and an assignment never comes back. ∎
It stops, but not necessarily at the best clustering: the result depends on the start.
$ python kmeans.py
seed 3, cost after each step: 899.3 628.2 625.8 625.7
20 random starts: 8 stop at cost 131.2, the others at
347.4 349.2 351.4 351.5 388.4 388.6 391.9 621.3 622.8 624.2 625.7 625.7
figs.py.Eight starts of twenty find the planted groups; the others stop at costs up to five times higher. The usual remedy is to run the algorithm from many starts and keep the best, and to start better. The -means++ seeding chooses the first centre at random and each next one among the points with probability proportional to its squared distance to the nearest centre chosen so far, so that far groups are likely to get a centre:
def seed_pp(points, k, rng):
"""The first centre uniformly; each next one a point drawn with probability
proportional to its squared distance to the nearest centre already chosen."""
centres = [rng.choice(points)]
while len(centres) < k:
w = [min(d2(p, c) for c in centres) for p in points]
centres.append(rng.choices(points, weights=w)[0])
return centres
$ python kmeanspp.py
uniform : best clustering 8 times of 20, mean final cost 336.9, worst 625.7, 5.5 steps
k-means++: best clustering 14 times of 20, mean final cost 218.4, worst 621.3, 3.5 steps
Better starts also need fewer steps. The seeding does not remove local minima, only makes them rarer: over 100 seeds, Exercise 29.11 counts them.
History
Stuart Lloyd proposed the algorithm in 1957, for the quantisation of signals; his work circulated widely but was published only in 1982.
29.5 Hierarchical clustering
-means asks for in advance. Hierarchical clustering builds every number of clusters at once.
Definition 29.17 (Hierarchical agglomerative clustering, linkage, dendrogram)
Hierarchical agglomerative clustering starts with each point in a cluster of its own and repeatedly merges the two clusters at the least linkage distance, until one cluster is left. The single, complete and average linkages of two clusters are the least, the largest and the mean distance between a point of one and a point of the other. The merges, drawn as a tree whose leaves are the points and whose internal nodes sit at the height of their merge, form the dendrogram; cutting it after merges gives clusters.
def hac(points, link):
"""The merges, in order, as (cluster, cluster, height); clusters are tuples."""
clusters = [(i,) for i in range(len(points))]
merges = []
while len(clusters) > 1:
def gap(pair, link=link):
a, b = pair
return link([math.dist(points[i], points[j]) for i in a for j in b])
a, b = min(combinations(clusters, 2), key=gap)
merges.append((a, b, gap((a, b))))
clusters = [c for c in clusters if c not in (a, b)] + [tuple(sorted(a + b))]
return merges
$ python hac.py
single : merge heights 1.26 1.58 1.70 1.71 1.75 1.77 2.11 2.25 2.26 2.41 4.03
three clusters: ABC DEFGH IJKL
complete: merge heights 1.26 1.58 1.77 1.92 2.21 2.25 3.20 3.48 3.65 8.00 9.84
three clusters: ABCD EFGH IJKL
average : merge heights 1.26 1.58 1.77 1.84 1.96 2.25 2.53 2.64 3.20 5.85 6.97
three clusters: ABCD EFGH IJKL
single linkage = spanning tree cut, for every k: True
figs.py from hac.py. Cutting between the heights 2.26 and 2.41 leaves three clusters: D joins E, F, G and H through its nearest neighbour, at 2.26, before A, B, C reach them at 2.41. Complete linkage puts D with A, B and C instead.Single linkage follows chains of close points, which finds groups of any shape but may join two groups through a few points between them; complete linkage prefers compact groups of small diameter. The brute-force listing recomputes every linkage at every merge: each of the merges looks at every pair of points in different clusters, distances in all, which is fine for a dozen points only. Single linkage needs no such work: it is already known from the Year 1 volume.
Theorem 29.18 (Single linkage and the minimum spanning tree)
Let the distances between points be distinct. For each , the clusters of single linkage are the connected components of the minimum spanning tree of the complete graph on the points, weighted by distance, once its heaviest edges are removed; equivalently, the components after Kruskal’s algorithm has accepted edges.
Proof. Exercise 29.10. The idea: the single linkage of two clusters is the shortest edge between them, and the shortest edge between two different clusters is exactly the next edge that Kruskal’s algorithm accepts. ∎
So single linkage costs a sort of the distances and a union–find, in all, and its clusters for every come out of one spanning tree.
29.6 Exercises
Exercise 29.1 ★
From the confusion matrix of Output 29.2, compute the accuracy, the fraction of late loans that are caught, and the fraction of “late” predictions that are right. Which of the three should the library watch if a false alarm costs a polite phone call and a missed late loan costs nothing?
Solution
Solution of Exercise 29.1.
Accuracy: . Late loans caught: . Right “late” predictions: . If only false alarms cost anything, the library should watch the last number, the fraction of alarms that are right, and could raise the bar for calling a loan late; accuracy mixes the two kinds of error with equal weight.
Exercise 29.2 ★
Run the -nearest-neighbour classifier on the raw features, without scaling, with exo_scaling.py. Which feature decides the distance, and why does accuracy drop?
Solution
Solution of Exercise 29.2.
$ python exo_scaling.py
k = 5: raw features 0.700, scaled 0.843
k = 9: raw features 0.723, scaled 0.837
ranges: days 7-28, pages 80-899, age 8-85, prior 0-6, distance 210-5990
The distance in metres ranges over almost 6,000 and the pages over about 800, while the late returns range over 6: in the raw distance, a difference of one late return weighs as much as one metre. The neighbours are then the members who live at about the same distance and borrow books of about the same length, whatever their late returns, and one of the two features of the rule is lost. Scaling every feature to gives each the same weight.
Exercise 29.3 ★
Write a search for all the points of a -d tree inside a rectangle, which skips the subtrees that cannot meet it. Compare the nodes visited with the points reported, using exo_range.py.
Solution
Solution of Exercise 29.3.
The function visits a node, reports its point if it lies in the rectangle, and goes down to the left only if the rectangle reaches coordinates at most the node’s on its axis (), to the right only if it reaches coordinates at least the node’s ().
$ python exo_range.py
rectangle (0.2, 0.2) to (0.3, 0.3): 88 points, 168 nodes visited
rectangle (0.0, 0.4) to (1.0, 0.45): 497 points, 793 nodes visited
rectangle (0.5, 0.5) to (0.5, 0.5): 0 points, 13 nodes visited
The nodes visited are the points reported plus the nodes whose region only crosses the rectangle’s border: about twice the answer for the square, and 13 for an empty point query, a path down the tree. A long thin strip crosses many regions, so it visits more nodes per point reported.
Exercise 29.4 ★
A set of 24 loans has 9 late ones. A split sends 8 loans to the left, 6 of them late, and 16 to the right, 3 of them late. Compute its information gain by hand, to three decimals.
Solution
Solution of Exercise 29.4.
The whole set has late, so bits. The left part has late, ; the right part , . The parts weigh and , so the gain is bits. On the entropy figure, the average of the parts is the point of the chord between them above , two thirds of the way from to , not its middle.
Exercise 29.5 ★★
Run one iteration of Lloyd’s algorithm by hand on the twelve points of Output 29.8, from the centres A, E and I: the assignment, the new centres and the two costs. Check with exo_lloyd_step.py.
Solution
Solution of Exercise 29.5.
$ python exo_lloyd_step.py
assignment: A1 B1 C1 D2 E2 F2 G2 H2 I3 J3 K3 L3 | cost 42.54
new centres: (1.50, 1.77) (7.28, 1.94) (4.65, 8.00) | cost 28.78
next assignment: A1 B1 C1 D2 E2 F2 G2 H2 I3 J3 K3 L3 | cost 28.78
From A, E and I, the points A, B, C go to A; D, E, F, G, H to E (D is from E and from A); I, J, K, L to I. The cost is . The centroids are , and , and the same assignment now costs . With these centres no point changes cluster, so the algorithm stops after one iteration, with D in the right-hand group.
Exercise 29.6 ★★
Some versions of ID3 split a feature with one branch per value. Add the loan’s number, different for each loan, as a feature, and compute the gain of such a split on it, on the days lent and on the late returns. What goes wrong? Is the gain ratio, the gain divided by the entropy of the branch sizes, enough to fix it here? Use exo_identifier.py.
Solution
Solution of Exercise 29.6.
$ python exo_identifier.py
days : 4 branches, gain 0.002 bits, split information 1.996, gain ratio 0.001
prior : 7 branches, gain 0.145 bits, split information 2.272, gain ratio 0.064
number : 700 branches, gain 0.880 bits, split information 9.451, gain ratio 0.093
entropy of the labels: 0.880 bits; log2 700 = 9.451
A split with one branch per loan leaves a single loan in each branch, so every branch has entropy and the gain is the whole entropy of the labels, the largest possible. The tree would ask “which loan is it?” and learn nothing that applies to a new loan, whose number is new. The gain ratio divides by the entropy of the branch sizes, bits for the number, and lowers its score to , but that is still above the of the late returns: here it is not enough. Identifiers must be left out of the features; binary splits limit the damage, since one threshold on the number gains almost nothing.
Exercise 29.7 ★★
In 5-fold cross-validation, the training set is cut into five parts; each part in turn serves as the validation set for a tree grown on the other four, and the five accuracies are averaged. Use it to choose the depth of the tree on the 700 noisy training loans, with exo_crossval.py. Compare with Output 29.5.
Solution
Solution of Exercise 29.7.
$ python exo_crossval.py
depth 0: mean 0.701, folds 0.714 0.700 0.707 0.750 0.636
depth 1: mean 0.744, folds 0.714 0.736 0.786 0.786 0.700
depth 2: mean 0.846, folds 0.850 0.814 0.857 0.879 0.829
depth 3: mean 0.839, folds 0.850 0.814 0.850 0.850 0.829
depth 4: mean 0.804, folds 0.814 0.771 0.836 0.814 0.786
depth 6: mean 0.797, folds 0.771 0.764 0.836 0.850 0.764
depth 8: mean 0.784, folds 0.779 0.750 0.814 0.814 0.764
depth 12: mean 0.757, folds 0.743 0.750 0.793 0.771 0.729
Cross-validation chooses depth 2, with a mean of , as the test set did in Output 29.5, without looking at it. The five folds differ by up to for the same depth ( at depth 2): one validation set of 140 is a noisy judge, and the mean of five is steadier.
Exercise 29.8 ★★
Prove Theorem 29.16.
Solution
Solution of Exercise 29.8.
Write for the -th assignment, for the centres from which it is computed, and for the -means cost. The assignment step gives each point its nearest centre, so . The centroid step replaces the centre of each non-empty cluster of by its centroid, which by Lemma 29.14 does not increase that cluster’s sum, and leaves empty clusters’ centres in place; so . Together, : the recorded cost never increases.
For termination, let be the cost of an assignment with each centre at the centroid of its cluster, empty clusters contributing nothing; then , since the centroid step computes from . The two steps and the lemma give . If , the last inequality is an equality, and by the uniqueness in the lemma each centre of with a non-empty cluster in is already its centroid; the others stay in place. So the next centres are again, the next assignment is again, and the algorithm stops. Hence, as long as it runs, strictly decreases, so no assignment comes back; there are at most assignments, so the algorithm stops.
Exercise 29.9 ★★
Run complete linkage by hand on the twelve points for the first five merges, then compare the full list of merges with exo_complete.py. Why does D end with A, B and C, while single linkage put it with E, F, G and H?
Solution
Solution of Exercise 29.9.
$ python exo_complete.py
A + B at 1.26
F + G at 1.58
J + K at 1.77
C + AB at 1.92
E + FG at 2.21
I + L at 2.25
H + EFG at 3.20
JK + IL at 3.48
D + ABC at 3.65
EFGH + ABCD at 8.00
IJKL + ABCDEFGH at 9.84
The first five merges are A with B (), F with G (), J with K (), C with AB (: its farthest point in AB is A) and E with FG (). Complete linkage measures a cluster by its farthest point: D is from A, the farthest of A, B, C, but from G, the farthest of E, F, G, H, so it joins A, B, C. Single linkage measures by the nearest point: D is from E but from B, so it joins E’s group.
Exercise 29.10 ★★★
Prove Theorem 29.18.
Solution
Solution of Exercise 29.10.
Run Kruskal’s algorithm on the complete graph: it examines the edges by increasing length and accepts an edge when its ends lie in different components. We show by induction on that after merges, the clusters of single linkage are the components after accepted edges. At both are the singletons.
Suppose it holds after merges. An edge whose ends are now in different components was never examined: when it was, its ends were in different components, since components only grow, and it would have been accepted, putting them in the same component. So the next edge Kruskal accepts is the shortest edge between two different components. The next merge of single linkage joins the two clusters at the least single linkage, the least distance between a point of one and a point of the other: it is the shortest edge between two different clusters. Since the distances are distinct, it is the same edge, and both join the same two sets.
After merges there are clusters, the components after accepted edges. With distinct weights the minimum spanning tree is unique and is Kruskal’s, made of its accepted edges in increasing order; the components after the first are those of the tree without the last , its heaviest edges.
Exercise 29.11 ★★★
Compare uniform and -means++ seeding over 100 seeds each with exo_kmeanspp.py: how often does each find the best clustering, and how many different local minima appear?
Solution
Solution of Exercise 29.11.
$ python exo_kmeanspp.py
uniform : 17 different final costs; runs ending at 131 in 53, 347 in 7, 348 in 1, ...
k-means++: 12 different final costs; runs ending at 131 in 80, 347 in 4, 348 in 2, ...
Uniform seeding finds the best clustering, cost 131, in 53 runs of 100, and stops at 17 different costs; -means++ finds it in 80 runs and stops at 12 different costs. With five groups, a uniform start leaves some group without a centre with fair probability; the -means++ start, by favouring points far from the centres chosen, rarely does. Neither avoids every local minimum, so keeping the best of several runs remains the practice.
Exercise 29.12 ★★★
Build a set of points and a query for which the nearest-neighbour search of Listing 29.4 visits every node, and explain why. Check with exo_kd_worst.py.
Solution
Solution of Exercise 29.12.
Put the points on a circle centred on the query, for example the 20 integer points with , and the query at the origin. Every point is at squared distance 625, so the best distance never improves after the first point, and a subtree is skipped only when . Every coordinate of every point lies in , so the test fails except at the points with a coordinate on the node’s axis, whose far side holds nothing on the circle.
$ python exo_kd_worst.py
20 points, query (0, 0): nearest (0, 25) at squared distance 625, 20 nodes visited
20 points, query (1, 0): nearest (25, 0) at squared distance 576, 19 nodes visited
The search visits all 20 nodes, the cost of the brute force plus the overhead of the tree. The pruning needs the best distance to be small compared with the distances to the splitting lines; points all at nearly the same distance from the query defeat it.
29.7 Problem: Which loans come back late?
Problem 29.1
Weekend problem — Which loans come back late?
The library has 1,000 past loans, with the same five features and a label that is wrong one time in ten. It wants a tree it can trust, and a first look at its members’ habits.
# Part I: the data, shuffled once and split 50 / 20 / 30.
data = loans(1000, seed=11, noise=0.10)
random.Random(0).shuffle(data)
train, valid, test = data[:500], data[500:700], data[700:]
for name, part in [("training", train), ("validation", valid), ("test", test)]:
late = sum(y for _, y in part)
print(f"{name:10} {len(part)} loans, {late} late ({late / len(part):.1%})")
# Parts II-III: the depth that does best on validation; then one look at the test set.
scores = {d: accuracy(id3(train, d), valid) for d in range(9)}
best = max(scores, key=lambda d: (scores[d], -d)) # the shallowest among the best
print("validation accuracy, depth 0 to 8:",
" ".join(f"{a:.3f}" for a in scores.values()))
tree = id3(train + valid, best)
show(tree)
majority = max(sum(y for _, y in test), sum(1 - y for _, y in test)) / len(test)
print(f"depth {best}: test accuracy {accuracy(tree, test):.3f}, majority baseline"
f" {majority:.3f}, agreement with the planted rule"
f" {accuracy(tree, [(x, rule(x)) for x, _ in test]):.3f}")
$ python loans_problem.py
training 500 loans, 151 late (30.2%)
validation 200 loans, 61 late (30.5%)
test 300 loans, 65 late (21.7%)
validation accuracy, depth 0 to 8: 0.695 0.755 0.885 0.880 0.880 0.860 0.845 0.850 0.835
prior <= 1.5
pages <= 375.5
-> on time (on time 142, late 34)
pages > 375.5
-> on time (on time 246, late 35)
prior > 1.5
distance <= 2495
-> on time (on time 88, late 5)
distance > 2495
-> late (on time 12, late 138)
depth 2: test accuracy 0.923, majority baseline 0.783, agreement with the planted rule 1.000
k = 1: cost 10796.6
k = 2: cost 2701.3
k = 3: cost 809.5; centres (4.5, 12.6), (11.7, 24.3), (30.7, 8.6)
k = 4: cost 638.3
k = 5: cost 516.8
k = 6: cost 468.8
Part I — The data and the split.
- Why are the loans shuffled before they are split?
- What is each of the three parts used for, and why must the test set be used only once?
- The test set has 21.7 % late loans, the training set 30.2 %. Is that a problem? What would a split that keeps the same proportion in every part do?
- With labels wrong one time in ten, what is the best accuracy any classifier can expect on the test set?
- What is the majority baseline on the test set, and why is it the first number to compare with?
- Which of the five features would you expect to matter, before looking at the tree?
Part II — A tree that finds the planted rule.
- Which depth does validation choose, and why the shallowest among the best?
- Read the tree: which loans does it call late?
- Compare it with the planted rule of
dataset.py. Why does its agreement with the rule reach 1.000? - The left branch splits on the pages, yet both its leaves say “on time”. Why did ID3 make that split, and what does it change?
- Compute the information gain of the root split from the counts in the leaves.
- State the problem’s result: test accuracy against the majority baseline.
Part III — Overfitting with noise.
- Validation accuracy falls past depth 2. Explain it with the noise.
- Why is the tree finally grown on the training and validation sets together?
- The test accuracy, 0.923, is above the 0.9 of question 4. Is that possible? What does it say about a single test set of 300?
- Would -nearest neighbours with all five features do as well? Use Output 29.3.
- How would the tree change if the noise were 30 %?
- Propose a check that the tree’s rule is stable: what would you rerun, and what would you compare?
Part IV — The members, clustered.
- Each member is a point (loans a year, mean days kept). Why is clustering here unsupervised?
- The cost drops from 10,797 to 2,701 to 810, then slowly. Which would you choose, and why?
- Describe the three groups from their centres.
- Why does the program keep the best of 10 starts for each ?
- Would the two features need scaling here? Compare their ranges.
- Which other method of the chapter could find the same groups without choosing first?
Solution
Solution of Problem 29.1.
1. The loans might come in an order that matters, by date for example; without shuffling, the test set could come from another period than the training set, and measure something else.
2. The training set grows the trees, the validation set chooses the depth, the test set measures the chosen tree. A test set used to choose anything becomes part of the training, and its score is then optimistic.
3. The two fractions come from the same source and differ by chance: on 300 loans the standard deviation of a fraction near the expected is about , and the test set’s is two of them below it. A stratified split, which keeps the same proportion of late loans in each part, removes that source of variation.
4. Even the planted rule is wrong on the flipped labels, one in ten on average, so about , give or take the chance of a single set.
5. Always answering “on time” scores . A classifier that does not beat it has learned nothing useful.
6. One would guess the late returns, and perhaps the distance or the days lent; nothing in the data says so in advance.
7. Depth 2, with on validation; depths 3 and 4 score , slightly less. Among nearly equal scores the shallowest tree is the simplest, and the least likely to have fitted noise.
8. A loan whose member has more than 1.5 late returns, that is at least 2, and lives more than 2,495 m away.
9. The planted rule is “at least 2 late returns and at least 2,500 m”. The distances are multiples of 10, so “more than 2,495” and “at least 2,500” agree on every possible loan, and the late returns are whole numbers: the tree computes exactly the rule, and agrees with it on every test loan.
10. On the noisy training loans, the left branch has 69 late labels out of 457, all of them noise, and they are not spread evenly: 34 of 176 among the short books, 35 of 281 among the long ones. Splitting there lowers the entropy a little, so the gain is positive, but both parts keep a majority on time and the predictions do not change. Pruning, which removes a split whose two leaves agree, would remove it.
11. The 700 loans have late, bits. The left part has late of , entropy about ; the right part of , about . The gain is bits.
12. The tree recovers the planted rule at depth 2: test accuracy , against a majority baseline of .
13. Below depth 2, the tree has not learned the rule; beyond, the only patterns left in the training labels are the flips, which are random, so each new split fits flips that new loans do not share.
14. Once the depth is chosen, the validation loans are only more data: the tree grown on 700 loans estimates the thresholds and the majorities better.
15. Yes. On 300 loans with labels wrong with probability , the number of wrong labels varies: its standard deviation is , so this test set had about 23 flips instead of 30. A single test set of 300 gives accuracy to within a few hundredths only.
16. On the loans with 15 % noise, -nearest neighbours reaches about with all five features against for the depth-2 tree, because the three useless features enter every distance; with the two right features it does about as well as the tree. It also keeps all the examples, where the tree keeps two questions.
17. The flips would hide the rule more: validation would choose a shallow tree, still the rule if the data are enough, with an accuracy of at most about ; with fewer loans it might choose depth 0 or 1.
18. Rerun the whole procedure on other shuffles of the data, or on samples drawn with replacement, and compare the features and thresholds chosen: a rule that keeps the same two questions with nearby thresholds is stable.
19. The members have no label: nobody has said which group each belongs to. The algorithm has only the points.
20. : the cost falls by a factor of four from 1 to 2 and more than three from 2 to 3, then by less than a quarter at each step. Past the bend, the extra clusters only split real groups.
21. About 31 loans a year kept 9 days: frequent readers of short books. About 12 a year kept 24 days: readers who keep their books long. About 4 or 5 a year kept 13 days: occasional borrowers.
22. Lloyd’s algorithm stops at a local minimum that depends on the start; the best of 10 starts is much more likely to be the best clustering, as in Output 29.7.
23. Both features range over a few tens, so scaling would change little; in general, as with -nearest neighbours, a feature with a larger range would decide the distances alone.
24. Hierarchical agglomerative clustering: its dendrogram shows every number of clusters at once, and a long vertical gap between two merge heights suggests where to cut.
এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ
- Clustering, centroid, k-means cost
- Confusion matrix, accuracy
- Decision tree
- Entropy, information gain
- Example, feature, class label, training set, test set
- Hierarchical agglomerative clustering, linkage, dendrogram
- k-d tree
- k-nearest-neighbour classifier
- Overfitting
- Supervised and unsupervised learning, classifier