Paul's Python CoursePPC

Project 6 of 12, for Caitlin

Q-Learning Crab

Caitlin's crab learns the League course by racing it, with Q-learning, and goes into the Arcade League. SARSA walks a clifftop.

About an hour and a half, in 13 steps.

Sign up free to open itLog in

Act 8 needs a free account, so your work is saved as you go. Act 1 is open to everyone.

The brief

  • CaitlinThis is the Arcade League. Every week everyone's crab gets the same course and the same rules.
  • YahyaIt's seven rows by nine columns, with two rock pools and a lot of rocks.
  • CaitlinNobody gets a map of the chances, you just race it until you know it.
  • AaeshaIt's like learning a new city on foot, where every turning ends up with a worth of its own.
  • PaulThen the crab learns the worth of every move as well as every tile.

The League course is in club-course.json, and Aaesha has copied the League's rules into course.py. The crab starts at S, top left, and races to F, bottom right. It slips sideways one move in ten on sand and 35 in a hundred in a rock pool. Into a rock or off the course, it stays put. A race stops at 100 moves, and the League's score is the average number of moves: lower is better.

Write crab.py:

  1. choose(Q, tile, epsilon, rng): epsilon-greedy over the four actions. Ties go to the first, as np.argmax does.
  2. q_update(Q, tile, action, reward, after, over, alpha=0.1, gamma=1.0): one Q-learning update, in place; returns the TD error.
  3. train(races, rng, alpha=0.1, gamma=1.0, epsilon=0.1): Q-learning. Practice races alternate: one from START, the next from random_start(rng). Returns the Q-table, a 7 by 9 by 4 array.
  4. greedy_policy(Q): the best action on every tile, as 7 lists of 9.
  5. save_entry(Q, path="league.json"): {"format": "ppc-league-1", "q": ...}, the League's entry format.

Run as a program, it trains for 3000 practice races, shows the policy, races it 50 times, and saves league.json.

What it prints
> > v v # < > v v
v # v v # v > v v
v # v > > v v v <
> > v # # v > v #
> > > > > v # v v
v > # > > v # v v
> > > ^ # > > > F
50 races: 15.72 moves on average, 50 finished
Saved league.json

What you learn

What's in it

  1. The worth of a move
  2. Q-learning
  3. One Q-learning update
  4. The Q-table as an array
  5. What it will actually do
  6. The same step, two ways
  7. The clifftop walk
  8. How Paul would do it
  9. Fix Yahya's version
  10. Make the crab a racer
  11. Where to practise
  12. Ship it