An n-gram is a contiguous sequence of items that are collected from a sequence of text or speech corpus. The n in n-grams specifies the number of tokens considered.
Sliding a window of size n along the text, 1 token at a time, produces every n-gram in it. A text of tokens gives n-grams, and neighbouring n-grams overlap because the window moves by 1 token rather than by n.

This model generate sentences in human language. It uses conditional probabilties where it requires the last words to generate the next word
Probability of a Sentence
N-grams are a probabilistic model that computes the probability of a sentence or a given sequence of words.
To compute this probability, we use the chain rule of probability:
With more variables this becomes:
- each new word is conditioned on every word before it, so the chain grows by 1 term per word
- as these sentences get longer, the computation for these probabilities becomes increasingly difficult
Markov Assumption
To simplify these probabilities, the Markov assumption is utilised:
Intuitively, this means the next word in a sentence can be predicted as a probability based on the n number of words that precedes it.
- the full history before the window is thrown away, so only a fixed number of preceding words is kept
- this is what makes the model computable, since a short history has far fewer combinations to count

Counting the Probabilities
Each probability is obtained by counting over the training corpus, and for the bigram case:
- is a count of how many times that sequence appears in the corpus
- the numerator counts the pair, and the denominator counts the first word on its own
<s>and</s>mark the start and end of a sentence, so the first word and the sentence ending can be predicted in the same way- there is no training loop here, since the model is built entirely by counting

Choosing n
| Size of n | Effect |
|---|---|
| small | fewer combinations to count, so the counts are reliable, and very little context is captured |
| large | more context is captured, and most sequences are never seen in the corpus, so their counts fall to 0 |
-
a sequence unseen in training gets a probability of 0, which is the same zero probability problem that smoothing fixes
-
the tokens counted here come from Tokenization, so the choice of tokenizer decides what an n-gram is made of
-
the fix for that zero probability is Smoothing