Study Vault Search notes, aliases and full text
Graph
ConceptDBISAI-written · not yet proofread

N-Gram Model

Also N-gram Model · Unigram Model · Bigram Model · Trigram Model

An n-gram model is a count-based language model that gives, for each sequence of n − 1 previous tokens, a probability distribution over the next token, estimated by counting n-grams in a training text and normalizing.

Know these firstLanguage Model

Formula#

Learning from a text (counting). Let #s\#s be the number of occurrences of the token sequence ss in the training text. Then

Pr⁡(v)=#v∣text∣,Pr⁡(v∣v1…vn−1)=#v1…vn−1v∑u∈V#v1…vn−1u.\Pr(v) = \frac{\#v}{|\text{text}|}, \qquad \Pr(v \mid v_1 \dots v_{n-1}) = \frac{\#v_1 \dots v_{n-1} v}{\sum_{u \in V} \#v_1 \dots v_{n-1} u}.

Generating text (sampling via cumulative counts). Let V=(v1,…,vm)V = (v_1, \dots, v_m) with counts #v1,…,#vm\#v_1, \dots, \#v_m (for n≥2n \ge 2: the counts of the current context, i.e. the last n−1n - 1 generated tokens).

  1. Compute the cumulative counts cj=∑i≤j#vic_j = \sum_{i \le j} \#v_i, j=1,…,mj = 1, \dots, m.
  2. Pick a random integer r∈{1,…,cm}r \in \{1, \dots, c_m\}.
  3. Find the smallest jj with r≤cjr \le c_j.
  4. Output vjv_j.

Exactly #vj\#v_j values of rr map to vjv_j, so vjv_j is generated with probability #vj/cm\#v_j / c_m. A unigram model picks each token independently of the previous ones.

def make_counts_cumulative(counts: list[int]):
    for i in range(1, len(counts)):
        counts[i] += counts[i - 1]

def random_char(cumulative_counts: list[int]) -> str:
    r = random.randint(1, cumulative_counts[-1])
    for i, ci in enumerate(cumulative_counts):
        if r <= cumulative_counts[i]:
            return chr(i + ord(" "))

(Lecture code: character tokens, vocabulary = printable ASCII from " " to "~", trained on the ES11 movie plots.)

Properties#

ModelnnConditions onProbability# distributions# possible n-grams (∣V∣=100\lvert V \rvert = 100)
Unigram1nothingPr⁡(v)\Pr(v)11100100
Bigram2previous token v1v_1Pr⁡(v∣v1)\Pr(v \mid v_1)∣V∣\lvert V \rvert10 00010\,000
Trigram3previous two tokens v1v2v_1 v_2Pr⁡(v∣v1v2)\Pr(v \mid v_1 v_2)∣V∣2\lvert V \rvert^210610^6
  • Size: there are ∣V∣n|V|^n possible n-grams (∣V∣n−1|V|^{n-1} contexts), exponential in nn, so large nn is infeasible. Solution: neural language models.
  • Unseen contexts and smoothing: many (n−1)(n-1)-token contexts never occur in the training text, so the model has no distribution for them. Remedy: pick the next token at random (uniformly). This is called smoothing, because it changes the probability distribution.
  • Tokens: the lecture’s n-gram models use characters as tokens; modern language models use subwords.

Example#

Sources#

Search

Type In
↑ ↓ move ↵ open ⇥ next section Ctrl↵ results page Prefix # to search text only