Skip to content
Exit presentation

Programming + AI Capstone

Write the classifier

You have written the nearest-example rule before. Now it works on a whole register, not just a few examples. A register is the list of judged kites. A walk goes through the list once, one example at a time. Met first means reached first when walking the list. One square away means one step on the board. Its squared distance is 1.

A new kite at 8 span, 5 tail. Two examples sit one square away.
Step 1 of 4
  1. A new kite at 8 span, 5 tail. Two examples sit one square away.
  2. T1, met first: squared distance 1. Best so far.
  3. T2, met next: squared distance 1 too. It is not strictly nearer. T1 stays best.
  4. The winner is T1. Its word, dancer, is the answer.

The rule

Measure every example and carry the nearest one so far. A new example wins only when it is strictly nearer. Ties keep the example met first.

  1. let best = 0;
  2. let least = distanceSquared(newKite, examples[0]);
  3. if (d < least) { least = d; best = i; }

The name best holds the position of the nearest example so far. The name least holds its squared distance. The name d holds the squared distance of the example being checked. The name i holds that example's position. The walk starts at position 1. Position 0 is the first best.

Use <, not <=. That single sign is the whole tie rule. A later example replaces the best only when strictly nearer. Equal is not enough.

Write classify with a best-so-far walk. Return the nearest example's word.

Loading lab…

The five printed words should match the board you have already seen.

Jump to lesson

This track

  1. 0 Start here
  2. 1 The plan, in plain words
  3. 2 Collect the day
  4. 3 The distance between two
  5. 4 See the board
  6. 5 Write the classifier
  7. 6 When the nearest is wrong
  8. 7 Assemble and report
  9. 8 Who it gets wrong
  10. 9 The big picture
  11. 10 Track quiz

Other tracks