Bitpath

Lesson 1 · Unit 02

Nearest neighbours

Predict by a vote of the closest rows

12 exercisesabout 3 min

What you practise

  • Classify by the k closest points, distance needs scaled features, small k overfits and large k blurs, why distance stops meaning much in many dimensions

Try a question from this lesson

Pick one

A new animal is compared with five known ones, listed nearest first. You let the 3 nearest vote. What is the prediction?

neighbour  distance  label
A          1.0       cat
B          1.4       dog
C          2.0       dog
D          3.5       cat
E          4.0       cat
Hint

Take only the first three rows and count their labels.

The idea

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Store, measure, vote

k-nearest neighbours (kNN) has no training step. It stores the labelled rows.

To classify a new point: measure its distance to every stored row, take the k closest, and let their labels vote. argsort returns row numbers ordered from nearest to farthest.

Python
X = np.array([[1, 1], [2, 1],
              [8, 8], [9, 7]])
y = np.array([0, 0, 1, 1])
q = np.array([7, 7])
d = np.linalg.norm(X - q, axis=1)
near = np.argsort(d)[:3]
print(near)      # [2 3 1]
print(y[near])   # [1 1 0]

10 more exercises in the app

  • 3× type the answer
  • 1× fill the blanks
  • 4× multiple choice
  • 1× order the lines
  • 1× true or false

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy