Level 4 · ExplorerLesson 4.2 40 min read 10 question quiz 13 marks of written practice

Classification, Trees, Neighbours and Clusters

Classification and decision boundaries

A classifier sorts inputs into categories. Picture each example as a point, with one axis per feature, coloured by its class. A classifier carves this space into regions, one per class, and the edges between regions are decision boundaries.

Three kinds of decision boundaryThree square panels show the same 26 points of two classes, pink circles mostly towards the top right and blue squares towards the bottom left, with some mixing in the middle. The background of each panel is shaded pink or blue by the class each model would predict there. Logistic regression divides the square with one straight diagonal boundary. k-nearest neighbours with k equal to 3 draws a wiggly boundary that bends around individual points. A decision tree of depth 3 divides the square into rectangles with edges parallel to the axes.Same data, three classifiers, three kinds of boundaryLogistic regressiona straight boundaryk-nearest neighbours, k = 3follows the data closelyDecision tree, depth 3boxes with straight sidesclass Aclass Bshading: the region each class gets
Each algorithm's assumptions decide what shape of boundary it can learn.

Different algorithms draw different kinds of boundary:

AlgorithmBoundary shapeStrengthWeakness
Logistic regressionA straight line (a hyperplane)Fast, gives probabilities, easy to explainCannot bend
k-nearest neighboursAny shape, following the dataNo training at allSlow to predict, needs scaled features
Decision treeBoxes with edges parallel to the axesReadable as a list of rulesOverfits if grown deep

k-nearest neighbours

k-nearest neighbours (kNN) is the simplest classifier there is, and a surprisingly good one.

  1. Store all the training examples. That is the whole of training.
  2. For a new point, measure its distance to every stored example.
  3. Take the k closest, its nearest neighbours.
  4. Predict the class most of them belong to.
k-nearest neighbours votingA scatter of blue squares on the left and pink circles on the right, with a new point, a star, near the middle. A small dashed circle encloses its 3 nearest neighbours: 1 pink and 2 blue, so with k equal to 3 the prediction is blue square. A larger dashed circle encloses its 7 nearest neighbours: 5 pink and 2 blue, so with k equal to 7 the prediction is pink circle.Who are my neighbours? The answer depends on kk = 7k = 3new pointk = 3 nearest neighbours1 pink circle, 2 blue squaresprediction: blue squarek = 7 nearest neighbours5 pink circles, 2 blue squaresprediction: pink circleSame point, different k, different answer.
k is a setting you choose, a hyperparameter, and it changes the model's answers.

The choice of k matters. With k = 1 the model copies its single nearest neighbour, so one mislabelled example creates a little island of wrong answers: overfitting. A very large k smooths everything towards the most common class: underfitting. An odd k avoids ties between two classes.

Scale first

kNN depends entirely on distance, so a feature measured in thousands drowns out one measured in single digits. Always scale features before using it (Level 3).

Logistic regression: probabilities from a line

Despite its name, logistic regression classifies. It computes a linear score exactly like regression, then squashes the score into a probability between 0 and 1 using the sigmoid function.

Logistic regression

z = w₁x₁ + w₂x₂ + … + b, then probability = σ(z) = 1 ÷ (1 + e-z)

The sigmoid functionA graph of the sigmoid function for scores z from minus 6 to 6. The curve is S-shaped, rising from almost 0 on the left through exactly 0.5 at z equal to 0 to almost 1 on the right. Marked points: z equal to minus 2 gives 0.12, z equal to 0 gives 0.50 and z equal to 2 gives 0.88. A dashed threshold line at 0.5 divides the graph: the left half, shaded blue, predicts class 0, and the right half, shaded pink, predicts class 1. A side panel gives the formula sigma of z equals 1 divided by 1 plus e to the minus z.The sigmoid: any score in, a probability out00.250.50.751-6-4-20246score z = w·x + bprobabilitythreshold 0.5z = −2 → 0.12z = 0 → 0.50z = 2 → 0.88predict class 0predict class 1σ(z) =1 ÷ (1 + e−z)z = −60.0025z = 00.5z = +60.9975
Large positive scores mean nearly certain yes; large negative scores, nearly certain no.
  • A large positive z gives a probability near 1, a large negative z gives one near 0, and z = 0 gives exactly 0.5.
  • The model predicts the class when the probability passes a threshold, usually 0.5. The boundary where z = 0 is a straight line.
  • It is trained with log loss (cross-entropy), which punishes confident wrong answers severely. Level 5 explains why.

Look closely and you will see a weighted sum, a bias, and a squashing function. That is exactly an artificial neuron, which is Level 6.

Decision trees and forests

A decision tree asks a sequence of yes or no questions about the features, and each answer leads down a branch until a leaf gives the prediction.

A decision tree with Gini impurityA decision tree for 100 emails, 40 spam and 60 not, Gini impurity 0.48. The root asks: is the sender in your contacts? Yes leads to a leaf, not spam, with 2 spam and 43 not. No leads to 38 spam and 17 not, Gini 0.43, which asks: more than 3 links? Yes leads to a leaf, spam, with 28 spam and 2 not. No leads to 10 spam and 15 not, Gini 0.48, which asks: does it contain the word free? Yes gives a spam leaf with 8 spam and 1 not; no gives a not spam leaf with 2 spam and 13 not. Each node shows a bar of the spam and not spam proportions.A decision tree for spam, with Gini impurity at every nodeIs the sender in your contacts?40 spam, 60 not · Gini 0.48yesnonot spam2 spam, 43 notMore than 3 links?38 spam, 17 not · Gini 0.43yesnospam28 spam, 2 notContains the word 'free'?10 spam, 15 not · Gini 0.48yesnospam8 spam, 1 notnot spam2 spam, 13 notspamnot spamThe first question gives thebiggest drop in impurity.
Each question is the one that makes the groups below it as pure as possible.

How a tree chooses its questions

At each step the tree tries every feature and every threshold, and picks the question that splits the examples into the purest groups. Purity is measured with Gini impurity:

Gini impurity

Gini = 1 − (sum of the squares of the class proportions)

A group of all one class has Gini 0. A 50 : 50 mix of two classes has Gini 1 − (0.5² + 0.5²) = 0.5. The tree picks the split that lowers the average impurity the most, weighted by group size, then repeats inside each branch.

Forests

A single deep tree overfits. Two ensemble methods fix that:

  • A random forest trains hundreds of trees, each on a random sample of the data and features, and lets them vote. The errors of individual trees cancel out.
  • Gradient boosting builds trees one after another, each trained to correct the mistakes of those before. Libraries such as XGBoost and LightGBM are the standard tool for tabular data in industry.

Evaluating classifiers: the confusion matrix

For a yes or no classifier there are four possible outcomes:

Predicted yesPredicted no
Actually yesTrue positive (TP)False negative (FN)
Actually noFalse positive (FP)True negative (TN)

From these four counts:

MeasureFormulaQuestion it answers
Accuracy(TP + TN) ÷ allHow often is it right overall?
PrecisionTP ÷ (TP + FP)When it says yes, how often is it right?
RecallTP ÷ (TP + FN)Of all the real yeses, how many did it find?
F1 score2 × precision × recall ÷ (precision + recall)One number balancing the two

Raising the threshold makes the model more cautious: precision usually rises and recall falls. Which matters more depends on the cost of each mistake. Missing a cancer (a false negative) is far worse than an extra scan (a false positive), so a screening model favours recall. A spam filter that bins real emails is worse than one that lets a little spam through, so it favours precision.

Classifier scorer

Move the threshold and watch precision and recall trade against each other. This tool needs JavaScript, so turn it on to use it. Everything you need to answer the exam question is explained in the text above.

Clustering with k-means

With no labels at all, k-means finds k groups of similar points.

  1. Choose k, and place k centroids (cluster centres), for example at k random data points.
  2. Assign every point to its nearest centroid.
  3. Update: move each centroid to the mean of the points assigned to it.
  4. Repeat steps 2 and 3 until nothing changes.
k-means clustering step by stepA stepped animation of k-means with k equal to 4 on 24 unlabelled points that form four groups: bottom left, top right, top left and bottom right. The four starting centroids are badly placed, two in the bottom left group and two in the top right group. In each round every point is coloured by its nearest centroid, then each centroid moves to the mean of its points, shown by arrows. Over 4 rounds the centroids spread out until there is one in each group, and then nothing moves, so the algorithm stops.k-means with k = 4: assign, update, repeat1. Assign each point to thenearest centroid (the ×).2. Move each centroid to themean of its points.3. Repeat until nothing moves.Two centroids started in thesame cluster; watch one leave.
Press Play to watch the centroids find the four groups.

Each round can only reduce the total squared distance from points to their centroids, so the algorithm always settles down, usually within a handful of rounds.

k-means clustering lab

Drop centroids onto a scatter of points and run k-means one assign and update at a time. This tool needs JavaScript, so turn it on to use it. Everything you need to answer the exam question is explained in the text above.

Its limits

  • You must choose k. The elbow method plots the total distance for k = 1, 2, 3 and so on, and looks for the point where adding clusters stops helping much.
  • Different starting centroids can give different answers, so it is run several times and the best result kept.
  • It assumes clusters are roughly round and similar in size, and it will happily split random noise into k clusters.

Hands-on: classify and cluster from scratch

k-nearest neighbours

Python
import math

# (sweetness, crunchiness) of foods, labelled by type
data = [((9, 2), "fruit"), ((8, 3), "fruit"), ((7, 1), "fruit"), ((8, 1), "fruit"),
        ((2, 9), "vegetable"), ((3, 8), "vegetable"), ((1, 7), "vegetable"),
        ((2, 6), "vegetable"), ((6, 6), "nut"), ((5, 7), "nut"), ((5, 9), "nut")]

def knn(point, k):
    nearest = sorted(data, key=lambda item: math.dist(item[0], point))[:k]
    votes = {}
    for _, label in nearest:
        votes[label] = votes.get(label, 0) + 1
    return max(votes, key=votes.get), [label for _, label in nearest]

for food in [(7, 3), (3, 6), (6, 8)]:
    for k in (1, 3, 5):
        guess, neighbours = knn(food, k)
        print(f"{food} with k={k}: {guess:10} neighbours {neighbours}")

Choosing a split with Gini impurity

Python
def gini(labels):
    n = len(labels)
    return 1 - sum((labels.count(c) / n) ** 2 for c in set(labels))

# Hours of sleep and whether the student felt alert
sleep = [4, 5, 5, 6, 7, 7, 8, 8, 9, 10]
alert = ["no", "no", "no", "no", "yes", "no", "yes", "yes", "yes", "yes"]

best = None
for threshold in sorted(set(sleep)):
    left = [a for s, a in zip(sleep, alert) if s < threshold]
    right = [a for s, a in zip(sleep, alert) if s >= threshold]
    if not left or not right:
        continue
    score = (len(left) * gini(left) + len(right) * gini(right)) / len(alert)
    print(f"split at sleep < {threshold:2}: weighted Gini {score:.3f}")
    if best is None or score < best[0]:
        best = (score, threshold)
print("Best question: is sleep <", best[1], "hours?")

k-means

Python
import math

points = [(1, 1), (1.5, 2), (2, 1.2), (8, 8), (9, 8.5), (8.5, 9.5), (1, 8), (2, 9), (1.5, 9.5)]
centroids = [(1, 1), (2, 1.2), (8, 8)]          # deliberately poor starting places

for step in range(1, 10):
    clusters = [[] for _ in centroids]
    for p in points:
        nearest = min(range(len(centroids)), key=lambda i: math.dist(p, centroids[i]))
        clusters[nearest].append(p)
    new = [(sum(x for x, y in c) / len(c), sum(y for x, y in c) / len(c)) for c in clusters]
    print(f"round {step}:", [(round(x, 2), round(y, 2)) for x, y in new])
    if new == centroids:
        print("No change, so k-means has converged.")
        break
    centroids = new

Two starting centroids were placed inside the same group, yet within a few rounds one of them migrates to the empty group at the top left.

Activity: build a human decision tree

As a class, think of an animal. A volunteer may only ask yes or no questions about features, such as "does it have fur?". Record the questions on the board as a tree. Which first question splits the class's animals most evenly, and why is that the best first question?

Level check

  • Explain what a decision boundary is and sketch the boundaries of three algorithms
  • Describe the kNN algorithm and the effect of choosing k
  • Explain how logistic regression turns a linear score into a probability
  • Calculate Gini impurity and explain how a tree chooses a split
  • Calculate precision and recall from a confusion matrix and say when each matters more
  • Describe the k-means algorithm and two of its limitations

Key terms you must be able to define

Classifier
A model that predicts which category an input belongs to.
Decision boundary
The edge between the regions a classifier assigns to different classes.
k-nearest neighbours
Classifying a point by a vote of the k training examples closest to it.
Logistic regression
A classifier that passes a linear score through the sigmoid function to give a probability.
Sigmoid
The S-shaped function 1 ÷ (1 + e-z) that squashes any number into the range 0 to 1.
Decision tree
A model that predicts by asking a sequence of yes or no questions about the features.
Gini impurity
A measure of how mixed the classes in a group are; 0 means all one class.
Random forest
Many decision trees trained on random samples of the data, voting together.
Precision
Of the examples predicted positive, the fraction that really are positive.
Recall
Of the examples that really are positive, the fraction the model found.
k-means
A clustering algorithm that repeatedly assigns points to the nearest of k centroids and moves each centroid to the mean of its points.
Centroid
The centre of a cluster: the mean of the points in it.

Flashcards

DefineClassifier
AnswerA model that predicts which category an input belongs to.
DefineDecision boundary
AnswerThe edge between the regions a classifier assigns to different classes.
Definek-nearest neighbours
AnswerClassifying a point by a vote of the k training examples closest to it.
DefineLogistic regression
AnswerA classifier that passes a linear score through the sigmoid function to give a probability.
DefineSigmoid
AnswerThe S-shaped function 1 ÷ (1 + e-z) that squashes any number into the range 0 to 1.
DefineDecision tree
AnswerA model that predicts by asking a sequence of yes or no questions about the features.
DefineGini impurity
AnswerA measure of how mixed the classes in a group are; 0 means all one class.
DefineRandom forest
AnswerMany decision trees trained on random samples of the data, voting together.

Go further: notes for future AI engineers

Support vector machines

Before deep learning, the most celebrated classifier was the support vector machine (SVM, 1990s). Of all the straight lines that separate two classes, it chooses the one with the widest margin, the gap to the nearest points on either side, which tends to generalise well. The kernel trick lets an SVM draw curved boundaries by implicitly mapping the data into a higher-dimensional space where a flat boundary works.

Why trees still win on tables

On images, sound and text, deep learning dominates because those inputs have structure (neighbouring pixels, word order) that networks exploit. Spreadsheet-style data has no such structure, features are often on wildly different scales, and datasets are often small. Gradient boosted trees handle all of that with little tuning. A good engineer tries a boosted tree baseline on any table before reaching for a neural network.

Misconceptions to avoid

Avoid these
  • Thinking logistic regression is a regression model. It is a classifier that outputs probabilities.
  • Using kNN on features with very different scales, so one feature decides every distance.
  • Growing a decision tree until every leaf is pure. It will memorise the training data.
  • Judging a classifier by accuracy alone when false positives and false negatives have very different costs.
  • Believing k-means discovers the true number of groups. You choose k, and it will always produce k clusters.
Fun fact

Gradient boosted decision trees, an idea from around 2000, still win most machine learning competitions on spreadsheet-style data. On tables of numbers, deep learning often loses to a forest of small, well-tuned trees.

Knowledge check

0 of 10 answered
1What is a decision boundary?
2In kNN with k = 5, a new point's nearest neighbours are 3 cats and 2 dogs. What is predicted?
3What is the risk of using k = 1 in k-nearest neighbours?
4What does the sigmoid function do in logistic regression?
5A group contains 3 apples and 1 orange. What is its Gini impurity?
6How does a random forest reduce overfitting?
7A model finds 40 of the 50 real fraud cases and flags 10 genuine payments by mistake. What is its recall?
8For a cancer screening test, which mistake is usually worse, and so which measure is favoured?
9In k-means, what happens in the update step?
10Why is k-means usually run several times with different starting centroids?
Score 0 / 10

Check you could explain this

13 marks
1Describe how the k-nearest neighbours algorithm classifies a new example.4 marks
Describe

Mark scheme0 / 4
  • LCalculate the distance from the new example to every training example
  • LSelect the k closest examples
  • LCount the classes of those neighbours / vote
  • LPredict the most common class among them
Model answer

The algorithm calculates the distance, usually the straight-line distance, from the new example to every example in the training data. It selects the k closest of these, its nearest neighbours. It then counts which class each neighbour belongs to, a vote, and predicts the class that is most common among the k neighbours.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

2A spam filter is tested on 1,000 emails. It correctly flags 90 of the 100 spam emails and wrongly flags 30 genuine emails. Calculate its precision and recall, and explain which matters more for a spam filter.5 marks
Calculate

Mark scheme0 / 5
  • LRecall = 90 ÷ 100 = 90%
  • LPrecision = 90 ÷ 120
  • LPrecision = 75%
  • LPrecision matters more
  • LBecause binning genuine emails is worse than letting some spam through
Model answer

Recall is TP ÷ (TP + FN) = 90 ÷ 100 = 90%. Precision is TP ÷ (TP + FP) = 90 ÷ (90 + 30) = 90 ÷ 120 = 75%. Precision matters more for a spam filter, because a genuine email sent to the spam folder may be important and never seen, whereas a spam email that gets through is only a mild annoyance. So the threshold should be raised to cut false positives.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

3Explain how a decision tree chooses which question to ask first.4 marks
Explain

Mark scheme0 / 4
  • LIt tries every feature and possible threshold
  • LIt measures how pure / mixed the resulting groups are
  • LUsing Gini impurity or entropy
  • LIt picks the split that lowers impurity the most, weighted by group size
Model answer

The tree considers every feature and every possible threshold for it. For each candidate question it splits the training examples into two groups and measures how mixed the classes in each group are, using Gini impurity or entropy. It chooses the question that reduces the impurity the most, averaged over the two groups and weighted by their sizes, so that the groups are as pure as possible.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

Machine mark 0 / 13