An n-gram model is a type of probabilistic language model used for predicting the next item in a sequence of words. The n-gram model estimates the probability of a word given the previous n - 1 words, which is useful for tasks like text prediction, speech recognition, and machine translation.
To create probabilities for each word in an n-gram model, you need to calculate the conditional probabilities of a word given the previous n - 1 words. Let's use a bigram model (2-gram model) as an example to illustrate how you would do this.
For a bigram model, the probability of a word w_i given the previous word w_{i-1} can be calculated using the counts from your training data as follows:
P(w_i | w_{i-1}) = Count(w_{i-1}, w_i) / Count(w_{i-1})
Here's a step-by-step process:
-
Count the bigrams: You should have counts of how often each bigram (pair of consecutive words) occurs in your training data. For example, how many times does the bigram "the dog" occur?
-
Count the unigrams: You should also have the counts of how often each individual word occurs. For example, how many times does the word "the" occur?
-
Calculate the conditional probability: For each bigram, divide the count of the bigram by the count of its first word. This gives you the conditional probability of the second word given the first word.
Example:
If the bigram "the dog" occurs 50 times in your training data, and the word "the" occurs 1000 times, the conditional probability of the word "dog" following "the" is:
P("dog" | "the") = Count("the dog") / Count("the") = 50 / 1000 = 0.05
For an n-gram model with n > 2, you would use the same approach but with longer histories. For example, for a trigram (3-gram) model, you would calculate:
P(w_i | w_{i-2}, w_{i-1}) = Count(w_{i-2}, w_{i-1}, w_i) / Count(w_{i-2}, w_{i-1})
When working with n-grams, it is also important to handle cases where you might not have seen a particular n-gram in your training data (this is known as the sparsity problem). Techniques such as smoothing (e.g., Laplace smoothing) or backoff models can be used to assign non-zero probabilities to these unseen n-grams.
Additionally, for very large corpora or when dealing with higher-order n-grams, it's common to encounter memory constraints. Techniques such as pruning (removing low-frequency n-grams) or using probabilistic data structures (like count-min sketch) can help mitigate these issues.