Build a vocabulary with special tokens, a minimum frequency and UNK

Why it matters Every word-level model, from classic RNN classifiers to fastText-style baselines, builds its vocabulary this way.

Word-level models need a fixed vocabulary. Words seen fewer than min_freq times are dropped, the vocabulary is capped in size, and any word outside it maps to an UNK id at encode time.

Write build_vocab(docs, min_freq, max_size). docs is a list of token lists. The vocabulary (a list itos, index = id) starts with '<pad>' (id 0) and '<unk>' (id 1), followed by every word with count >= min_freq over all docs, sorted by count descending then word ascending, and cut so len(itos) <= max_size (max_size >= 2).

Return (itos, encoded) where encoded is docs with each word replaced by its id, or 1 if it is not in itos.

Signaturedef build_vocab(docs, min_freq, max_size)

Example

build_vocab([['a', 'b', 'a'], ['c', 'a', 'b']], 2, 10) gives itos ['<pad>', '<unk>', 'a', 'b'] and encoded [[2, 3, 2], [1, 2, 3]].

Understand the idea

A vocabulary maps words to integer ids. Special tokens come first: <pad> for padding and <unk> for anything unknown. Rare words are dropped because the model cannot learn much from them, and a size cap keeps the embedding table small.

Worked example: docs [a, b, a] and [c, a, b]. Counts: a = 3, b = 2, c = 1. With min_freq 2, keep a and b. Sorted by count: a, b. itos = [<pad>, <unk>, a, b], so a = 2 and b = 3. Encoding the second doc: c is unknown, so 1; then a = 2, b = 3, giving [1, 2, 3].

Rule: keep words with count >= min_freq, sort by (-count, word), take the first max_size - 2, prepend specials, and encode unknown words as the <unk> id.

Word-level text classifiers, seq2seq baselines and embedding training scripts build vocabularies exactly like this.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplebuild_vocab([['a', 'b', 'a'], ['c', 'a', 'b']], 2, 10)
  • Sample 2: size cap with tiesbuild_vocab([['x', 'y', 'z', 'x'], ['y', 'z', 'w', 'x']], 1, 4)
  • Test 3: min_freq one keeps allbuild_vocab([['hi', 'there']], 1, 10)
  • Test 4: nothing frequent enoughbuild_vocab([['p', 'q']], 3, 5)