Bayes Complete: Sentence Autocomplete using N-Gram Language Models
Assignment Objectives
Understand the mathematical principles behind N-gram language models
Implement an n-gram language model from scratch
Apply the model to sentence autocomplete functionality.
Analyze the performance of the model in this context.
Pre-Requisites
Python Basics: Familiarity with Python syntax, data structures (lists, dictionaries), and file handling.
Probability: Basic understanding of probability fundamentals (particularly joint distributions and random variables).
Bayes: Theoretical knowledge of how n-gram language models work.
Overview
In this assignment, you'll be stepping into the shoes of a language model developer. Your mission: to build a sentence autocomplete feature using the power of language models.
Imagine you're working on a messaging app where users want quick and accurate sentence completion suggestions. Your model will analyze the context of the sentence and predict the most likely next letter (repeatedly, thus completing the sentence), helping users express themselves faster and more efficiently.
You'll train your model on a large text corpus, teaching it the patterns and probabilities of letter sequences. Then, you'll put your model to the test, seeing how well it can predict the next letter and complete sentences.
This project will implement an autocomplete model using n-gram language models to predict the next character in a sequence. The model takes a training document, builds frequency tables for n-grams (with up to n conditionals), and calculates the probability of the next character given the previous n characters.
Get ready to dive into the world of language modeling and build an autocomplete feature that's both smart and helpful!
Project Components
1. Frequency Table Creation
The model reads a document and constructs frequency tables based on character sequences. These tables store the frequency of occurrence of a given character, conditioned on the previous characters ( grams).
Assistant
n
n
For an n gram model, we will have to store n tables.
Table 1 contains the frequencies of each individual character.
Table 2 contains the frequencies of two character sequences.
Table 3 contains the frequencies of three character sequences.
And so on, up to Table N.
Consider that our vocabulary just consists of 4 letters, {a,b,c,d}, for simplicity.
Table 1: Unigram Frequencies
Unigram
Frequency
f(a)
f(b)
f(c)
f(d)
Table 2: Bigram Frequencies
Bigram
Frequency
f(a, a)
f(a, b)
f(a, c)
f(a, d)
f(b, a)
f(b, b)
f(b, c)
f(b, d)
...
Table 3: Trigram Frequencies
Trigram
Frequency
f(a, a, a)
f(a, a, b)
f(a, a, c)
f(a, a, d)
f(a, b, a)
f(a, b, b)
...
And so on with increasing sizes of n.
2. Computing Joint Probabilities for a Language Model
In general, Bayesian Networks are used to visually represent the dependencies (edges) between distinct random varaibles (nodes) in a large joint distribution.
In the case of a language model, each node in the network corresponds to a character in the sequence, and edges represent the conditional dependencies between them.
For a character sequence of length 4 a bayesian network for our the full joint distribution of 4 letter sequences would look as follows.
Where X1 is a random variable that maps to the character found at position 1 in a character sequence, X2 maps to the character at position 2, and so on.
This makes clear how the chain rule can be applied to expand the full joint form of a probability distribution.
In our case we are interested in computing the next character (the character at position 4) given the characters at the previous positions (characters at position 1, 2, and 3). Applying the definition of conditional distributions we can see this is
If we wanted to predict the most likely next character, we could compute the probability of every possible completion given each character in our vocabularly. This will give us a probability distribution over the next character prediction P(X4=x4∣X1=t,X2=h,X3=u). Taking the character with the max probability value in this distribution gives us an autocomplete model.
General Case:
Given a sequence x1,x2,…,xt, the probability of the next character xt+1 is calculated as:
P(xt+1∣x1,x2,…,xt)=P(x1,x2,…,xt)P
This can be generalized for different values of t, using the corresponding frequency tables.
N-gram models:
For short sequences, we can compute our joint probabilities in their entirity. However, as the sequences grows longer, our tables become exponentially larger and this problem quickly grows intractable. Enter n-gram models. An n-gram model is the same model we described above except only n-1 characters are considered as context for the prediction.
That is for a bigram model n=2 we estimate the joint probability as
Putting this network in terms of computations via our frequency tables is now slightly different as we now have to consider the ratio for each term
P(X1=x1,X2=x
Where size(C) is the total number of characters in the corpus. Consider how this generalizes to an arbitrary n-gram model for any n, this will be the core of your implementation. Write this formula in your report.
Starter Code Overview
The project starter code is structured across three main Python files:
NgramAutocomplete.py: This is where the main logic of the autocomplete model is implemented. You are expected to complete three functions in this file: create_frequency_tables(), calculate_probability(), and predict_next_char().
main.py: This file provides the user interface and controls the flow of the program. It initializes the model, takes user inputs, and runs the character prediction process iteratively. You may modify this file to test their code, but no modifications are required to complete the project.
utilities.py: This file includes helper functions that facilitate the program, such as reading and preprocessing the training document. No modifications are needed in this file.
TODOs
NgramAutocomplete.py is the core file where you will change in this project. Each function here builds upon each other to create a probabilistic model for predicting the next character in a sequence.
1. create_frequency_tables(document, n)
This function constructs a list of n frequency tables for an n-gram model, each table capturing character frequencies with increasing conditional dependencies.
Parameters:
document: The text document used to train the model.
n: The number of value of n for the n-gram model.
Returns:
Returns a list of n frequency tables.
2. calculate_probability(sequence, char, tables)
Calculates the probability of observing a given sequence of characters using the frequency tables.
Parameters:
sequence: The sequence of characters whose probability we want to compute.
tables: The list of frequency tables created by create_frequency_tables(), this will be of size n.
char: The character whose probability of occurrence after the sequence is to be calculated.
Predicts the most likely next character based on the given sequence.
Parameters:
sequence: The sequence used as input to predict the next character.
tables: The list of frequency tables.
vocabulary: The set of possible characters.
Functionality:
Calculates the probability of each possible next character in the vocabulary, using calculate_probability().
Returns:
Returns the character with the maximum probability as the predicted next character.
A Reports section
383GPT
Did you use 383GPT at all for this assignment? Yes
create_frequency_tables(document, n)
Code analysis
The create_frequency_tables function processes a text document to build frequency tables for an n-gram language model, capturing patterns from single characters (unigrams) up to sequences of length n (bigrams, trigrams, etc.).
It initializes a list of frequency tables: the first table counts individual characters, while each subsequent table tracks n-gram frequencies based on the preceding n-1 characters (the context). As the function iterates through the document, it increments counts in the unigram table and, for each higher-order n-gram, checks if there are enough remaining characters to form the sequence. For valid n-grams, it extracts the context and counts how often each character follows it.
The function returns these tables as the foundation for probabilistic modeling, enabling the prediction of character sequences based on observed patterns.
Compute Probability Tables
Note:Probability tables are different from frequency tables**
Assume that your training document is (for simplicity) "aababcaccaaacbaabcaa", and the sequence given to you is "aa". Given n = 3, do the following:
What is your vocabulary in this case
Vocabulary: {a, b, c}
Write down your probabillity table 1:
P(⊙)
Probability value
P(a)
2011
P(b)
204
P(c)
205
Write down your probability table 2:
P(⊙)
Probability value
P(a∣a)
10
Write down your probability table 3:
P(⊙)
Probability value
P(a∣a,a)
calculate_probability(sequence, char, tables)
Formula
To calculate the likelihood of the next character xt+1 given a sequence x1,x2,…,xt, the following conditional probability is used:
P(xt+1∣x1,x2,…,xt)=f(x1,x2,…,xt)f
This probability is estimated by dividing the frequency of the full sequence x1,x2,…,xt,xt+1 by the frequency of the context x1,x2,…,xt.
In an n-gram model, we simplify by considering only the preceding n-1 characters as context.
Code analysis
The calculate_probability function computes the conditional probability of a character following a given sequence, leveraging the precomputed frequency tables from create_frequency_tables. It first determines the context length based on the available n-gram level (up to n-1 characters).
Unigram Probability: If there is no context (i.e., for a single character or n=1), it calculates the probability as the count of the character divided by the total characters in the document.
Bigram and Higher N-gram Probability: For sequences with context, it extracts the last n-1 characters as the context and uses this to look up the frequency of the target character following the context. It then divides this by the total occurrences of the context to get the conditional probability.
The function returns this calculated probability, representing the likelihood of the character occurring next given the specific context in the document.
Your Calculations
Now using your probability tables above, it is time to calculate the probability distribution of all the next possible characters from the vocabulary.
Calculations for Next Charater Probabilities
P(X1=a,X2=a,X3=a)
Using Table 3 for the trigram probabilities:
P(a∣a,a)=f(a,a)
Therefore:
P(X1=a,X2=a,
P(X1=a,X2=a,X
P(X1=a,X2=a,X
predict_next_char(sequence, tables, vocabulary)
Code analysis
The predict_next_char function identifies the most likely next character following a given sequence by calculating probabilities for each character in the vocabulary.
It initializes max_prob to track the highest probability and predicted_char to store the corresponding character. For each character, it uses calculate_probability to determine the likelihood of that character appearing after the sequence.
If this probability exceeds max_prob, the function updates max_prob and sets predicted_char to that character. Finally, it returns the predicted next character based on observed patterns in the document.
So what should be the next character in the sequence?
Based on the probability distribution obtained above for all the next possible characters, which character would be next in the sequence?
Based on the probability distribution obtained above, the next character would be b, as it has the highest probability:
P(X3=b∣X1=a,X2=a)=0.5
Experiment
Through experimentation, I found that model performed significantly better on the Alice's Adventures in Wonderland corpus, consistently producing coherent sequences. Through further experimentation, I found the optimal range for n-gram values to be between 5 and 8. These values provide enough context for the model to generate logical sequences while avoiding excessive repetition of common phrases. Below is one of the better outputs, using n=8, initial sequence: Wonderland, and k=100.
Updated sequence: Wonderland updated equipment many small again and more she had not gone much frightened up and was going to al
Your report on using N-gram language models for sentence autocomplete looks very thorough and well-structured. However, I’ve identified a few areas for improvement, including grammatical issues, mathematical notation, and stylistic suggestions. Here are the recommended adjustments:
General Corrections
Spelling Errors: Correct the following spelling mistakes:
"probabillity" should be "probability"
"varaibles" should be "variables"
"entirity" should be "entirety"
"probabillity table" should be "probability table"
Inconsistent Use of Variables: Throughout the report, ensure the consistent use of variables and notation. For example, sometimes you use X variables, other times lowercase variables like x. Consistency improves readability.
Mathematical Notation Consistency: Make sure all formulas are formatted uniformly. Specifically:
Ensure that all symbols denote probability (e.g., use ( P(X) ) vs ( P(x) )) consistently throughout the document.
Section Specific Corrections
Overview Section:
The sentence "helping users express themselves faster and more efficiently" could be improved by removing "and more" for clearer parallel structure: "helping users express themselves faster and more efficiently."
Frequency Table Creation Section:
In the frequency table description, ensure you specify that the tables for bigrams, trigrams, etc., should be filled with actual frequencies when you present those tables.
Probability Tables
Labeling: Indicate clearly that the last "2" in the headings of the tables (Table 2 and 3) refer to bigram and trigram probabilities clearly to maintain clarity in presentation.
Formula Section:
The formula when stating:
P(X4=x4∣X1=x
should be clarified—state that it follows from the definition of conditional probability.
Experiment Section:
The phrase "model performed significantly better on the Alice's Adventures in Wonderland corpus" could be made more precise. For example: "The model performed significantly better when trained on the 'Alice's Adventures in Wonderland' corpus."
Stylistic Recommendations
Bullet Points for Clarity: In sections with lists (like the objectives), consider the use of bullet points rather than numbered lists unless a specific order is intended.
Clarify Technical Jargon: For readers who may not be familiar with terms like "n-gram," provide a brief definition or context where first mentioned.
Further Experimentation: Consider adding a brief section where you summarize insights gained from experimentation—what worked and what didn't, as well as specific examples of how the output changed with different configurations.
Conclusion
Your report overall captures the essence of implementing N-gram language models for sentence auto-completion with nice detail in methodology and calculations. The corrections and suggestions above should refine your report, making it clearer and more consistent. Once you've made these adjustments, your report should be in excellent shape for submission.