A character-level model cannot process raw text directly. Its vocabulary, written Σ, assigns each distinct character a unique integer ID. If a character belongs to the vocabulary, write c ∈ Σ; |Σ| is the number of distinct characters. The IDs preserve character order in an integer tensor, ready for an embedding layer. section 4.2.1 section 4.2.2
Build the mapping before creating model inputs:
- Choose text preprocessing first. Converting a corpus to lowercase makes Σ smaller and the task easier, but prevents the model from learning capitalization. section 7.5.1
- Scan the corpus, assigning each previously unseen character the next integer: `vocab2indx[char] = len(vocab2indx)`. Reverse the pairs into `indx2vocab` to recover characters from IDs. section 7.5.1
- Convert each input chunk and its one-character-shifted target chunk with the same mapping. The model then receives IDs for the observed characters and labels for the next characters. section 7.5.1
Vocabulary size in a char-RNN
After lowercasing roughly 100,000 characters of Shakespeare text, the mapping contains 36 unique characters. Use `len(vocab2indx)` as the embedding’s number of entries and as the width of the next-character prediction layer. `nn.Embedding(|Σ|, d)` looks up a d-dimensional vector for each ID; it does not construct the string-to-ID mapping for you. section 7.5.1 section 4.2.2
vocab2indx = {} #1
for char in shakespear_100k:
if char not in vocab2indx: #2
vocab2indx[char] = len(vocab2indx) #3
indx2vocab = {} #4
for k, v in vocab2indx.items(): #5
indx2vocab[v] = k
print("Vocab Size: ", len(vocab2indx))
print("Total Characters:", len(shakespear_100k))
Vocab Size: 36
Total Characters: 99993
The character-to-index and index-to-character dictionaries show how a vocabulary of 36 entries is built from a much longer corpus. section 7.5.1
A vocabulary need not contain characters: a word-level translation model instead assigns IDs to distinct words and reserves IDs for padding, start-of-sentence, and end-of-sentence tokens. What counts as an item—and which special tokens are needed—depends on the task. section 11.2.1 section 4.2.2












