Paul's Python CoursePPC

Project 9 of 14, for Caitlin

Text Generator

A character-level text generator that writes shipping forecasts: a vocabulary, a model that counts which character follows which, and the same model learnt by gradient descent through embeddings.

About an hour and a half, in 15 steps.

Sign up free to open itLog in

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

The brief

  • CaitlinMy sailing game's got a radio that reads the shipping forecast for the game's sea areas.
  • CaitlinI wrote thirty forecasts and kept five back, and I want the game to make up its own.
  • YahyaIt'll be writing the forecast by Friday.
  • PaulIt'll be writing something by Friday.

In words.py, turn the forecasts into numbers and build a model that guesses each next character by counting.

  1. build_vocab(text): every character in the text once, sorted.
  2. encode(text, vocab): a list of ids, each character's place in vocab; decode(ids, vocab) turns them back into text.
  3. count_pairs(ids, size): a size by size array, where counts[a, b] is how often id b comes straight after id a.
  4. probabilities(counts, smoothing=0.1): add smoothing to every count, then divide each row by its total.
  5. average_nll(probs, ids): the average of minus the log of the chance of each real next character. perplexity(probs, ids) is e to that.
  6. sample(probs, start, length, rng): length ids, each drawn with rng.choice(len(probs), p=probs[current]) from the row of the id before, starting after start.
  7. Run as a program, it scores the held-back forecasts and makes up three of its own.
  8. In learn.py, the same model learnt by gradient descent, with an embedding for every character.
What it prints
Vocabulary: 39 characters
Perplexity on forecasts it never saw: 7.05
Guessing evenly would be 39
-we rngor. fy d. od. 4 5.
thes. qsherr. gout ooubesinoord.kk. am d. or windwes. eveck3nars.
6 hesaiomo mon sherly omorigherough-weshea9-3 goorably norstester. e. orsththor.

What you learn

What's in it

  1. Text into numbers
  2. Every character once
  3. Counting what comes next
  4. How surprised is it?
  5. Writing, a character at a time
  6. How Paul would do it
  7. Fix Caitlin's version
  8. Counting the forecasts
  9. A row of numbers per token
  10. A row of the table
  11. Which rows point alike
  12. Learning what counting knew
  13. Downhill to the same place
  14. Ship it