liveBook · Manning

Bigram model

As explained in Deep Learning with PyTorch, Second Edition

A sequence model that predicts the next symbol from the immediately preceding symbol using pairwise transition probabilities.

A bigram model predicts the next character from the character immediately before it. It learns pairwise transition probabilities by counting adjacent characters in a collection of names, making statistical text generation concrete before introducing more sophisticated neural models. section 9.2

# In[]:
names = []
with open('../data/p2ch9/names_2022.txt', 'r') as file:
    for line in file:
        name, _, _= line.lower().strip().split(',')
        names.append("$" + name + "$")
len(names)

# Out[]:
31915

The dataset setup wraps each lowercase name with boundary markers, producing 31,915 training examples for character-pair counting. section 9.2

A simple implementation follows three steps:

  • Represent the transitions as a 27 × 27 matrix: each row identifies the preceding character, and each column identifies a possible next character. section 9.2
  • Count every consecutive character pair across the names, then normalize the matrix so its entries represent probabilities. section 9.2
  • Generate a name by sampling from the row associated with the latest character, appending the sampled character, and stopping at the boundary marker. section 9.2

Sampling generated names

Starting from "$", repeatedly sample the next character from its learned probability row. Outputs such as “liahuli,” “deiannnis,” “cl,” “de,” and “neynee” demonstrate both recognizable fragments and crude results. section 9.2

The model captures only one-character context, so it crudely estimates sequences compared with models using embeddings, linear layers, attention, or transformer architectures. A useful extension asks how name frequency would change the model. section 9.11 section 9.12

How Deep Learning with PyTorch, Second Edition covers it

How deep it goes
Explains counting, matrix normalization, and sampling, but stops at one-character context before neural and transformer models.
Examples
Uses 2022 baby names, a character-transition matrix, and sampled outputs including “liahuli” and “neynee.”
What you can do after
Builds a character-level generator by counting transitions and sampling from normalized PyTorch probabilities.
How it connects
Connects statistical generation with tokens, embeddings, linear layers, attention, and transformer architectures.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with PyTorch, Second Edition. The section links point to the parts of the book it draws on.