AI foundations · Lesson 2 of 3
AI foundations · Lesson 2 of 3
A prediction uses past examples to guess an unknown value. One of the simplest methods is the nearest neighbour: find the past example most similar to the new case, and reuse its answer.
Say a moving company records each job as (rooms, hours): [(1, 3), (3, 7), (5, 11)]. For a new 4-room job, the nearest examples are 3 and 5 rooms. If two are equally close, a rule must decide; here we keep the first one found.
This method has no formula to learn: the examples are the model. It works surprisingly well when there are many good examples, and badly when the new case looks like nothing seen before.
Write nearest(examples, x): examples is a list of (x, y) pairs. Return the y of the example whose x is closest to the given x. On a tie, return the first one in the list.
All checks pass. Well done.
Next lesson: Is the model any good?An AI tutor that gives hints, not answers. It sees your code, its output and this lesson. It can be wrong.