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
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 n previous characters (n grams).
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.
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.
image1
Where
X
1
is a random variable that maps to the character found at position 1 in a character sequence,
X
2
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.
P
(
X
1
x
1
,
X
2
x
2
,
X
3
x
3
,
X
4
x
4
)
P
(
x
1
)
⋅
P
(
x
2
∣
x
1
)
⋅
P
(
x
3
∣
x
1
,
x
2
)
⋅
P
(
x
4
∣
x
1
,
x
2
,
x
3
)
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
P
(
X
4
x
4
∣
X
1
x
1
,
X
2
x
2
,
X
3
x
3
)
P
(
X
1
x
1
,
X
2
x
2
,
X
3
x
3
,
X
4
x
4
)
P
(
X
1
x
1
,
X
2
x
2
,
X
3
x
3
)
Which can be estimated using the frequencies of each sequence in a our corpus
P
(
X
4
x
4
∣
X
1
x
1
,
X
2
x
2
,
X
3
x
3
)
f
(
x
1
,
x
2
,
x
3
,
x
4
)
f
(
x
1
,
x
2
,
x
3
)
To make this concrete, consider an input sequence "thu", where we want to predict the probability the next character is "s".
P
(
X
4
s
∣
X
1
t
,
X
2
h
,
X
3
u
)
P
(
X
1
t
,
X
2
h
,
X
3
u
,
X
4
s
)
P
(
X
1
t
,
X
2
h
,
X
3
u
)
f
(
t
,
h
,
u
,
s
)
f
(
t
,
h
,
u
)
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
(
X
4
x
4
∣
X
1
t
,
X
2
h
,
X
3
u
)
. Taking the character with the max probability value in this distribution gives us an autocomplete model.
General Case:
Given a sequence
x
1
,
x
2
,
…
,
x
t
, the probability of the next character
x
t
+
1
is calculated as:
P
(
x
t
+
1
∣
x
1
,
x
2
,
…
,
x
t
)
P
(
x
1
,
x
2
,
…
,
x
t
,
x
t
+
1
)
P
(
x
1
,
x
2
,
…
,
x
t
)
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
P
(
X
1
x
1
,
X
2
x
2
,
X
3
x
3
,
X
4
x
4
)
P
(
x
1
)
⋅
P
(
x
2
∣
x
1
)
⋅
P
(
x
3
∣
x
2
)
⋅
P
(
x
4
∣
x
3
)
Which can be visually represented with the following Bayesian Network
image2
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
(
X
1
x
1
,
X
2
x
2
,
X
3
x
3
,
X
4
x
4
)
P
(
x
1
)
⋅
P
(
x
2
∣
x
1
)
⋅
P
(
x
3
∣
x
2
)
⋅
P
(
x
4
∣
x
3
)
f
(
x
1
)
s
i
z
e
(
C
)
⋅
f
(
x
1
,
x
2
)
f
(
x
1
)
⋅
f
(
x
2
,
x
3
)
f
(
x
2
)
⋅
f
(
x
3
,
x
4
)
f
(
x
3
)
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.
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.
def 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.
code
- **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.
"""
return []
def calculate_probability(sequence, char, tables):
"""
Calculates the probability of observing a given sequence of characters using the frequency tables.
code
- **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.
- **Returns**:
- Returns a probability value for the sequence.
"""
return 0
def predict_next_char(sequence, tables, vocabulary):
"""
Predicts the most likely next character based on the given sequence.
code
- **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.
"""
return 'a'
Implement the first function.
Here is the main function: from utilities import read_file, print_table
from NgramAutocomplete import create_frequency_tables, calculate_probability, predict_next_char
def main():
document = read_file('warandpeace.txt')
n = int(input("Enter the number of grams (n): "))
initial_sequence = input(f"Enter an initial sequence: ")
k = int(input("Enter the length of completion (k): "))
code
tables = create_frequency_tables(document, n)
vocabulary = set(tables[0])
current_sequence = initial_sequence
for _ in range(k):
# Predict the most likely next character
next_char = predict_next_char(current_sequence[-n:], tables, vocabulary)
current_sequence += next_char
print(f"Updated sequence: {current_sequence}")
if name == "main":
main()
Assistant
To implement the create_frequency_tables() function in the NgramAutocomplete.py file, we need to construct frequency tables for unigrams, bigrams, trigrams, and so on, up to n-grams. Each table should correspond to the frequency of occurrences of character sequences of a certain length, conditioned on the previous characters.
Here's how we can approach the implementation of create_frequency_tables():
Initialize Frequency Tables: We will create a list of dictionaries, where each dictionary corresponds to a frequency table for a specific n-gram length. The keys will be the character sequences and the values will be their respective frequencies.
Iterate Through the Document: Loop through the characters in the document and build n-grams from the characters. For each n-gram generated, update the corresponding frequency table.
Handle Edge Cases: Ensure that the model can handle cases where the document is shorter than n characters and also take care to initialize frequencies correctly.
Here's the code for create_frequency_tables():
python
def 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.
"""
# Initialize a list to hold the frequency tables
frequency_tables = [{} for _ in range(n)]
# Preprocess the document to remove any unwanted characters and to ensure it is suitable for the model
document = document.replace('\n', '').replace('\r', '') # Clean newlines from document
length = len(document)
for i in range(length):
for order in range(1, n + 1): # Go up to n
if i + order <= length: # Ensure we do not go out of bounds
# Extract the n-gram
ngram = document[i:i + order]
# Update the frequency table for this order
if order == 1: # Unigram
frequency_tables[order - 1][ngram] = frequency_tables[order - 1].get(ngram, 0) + 1
else: # N-grams for order > 1
context = ngram[:-1] # All but the last character
char = ngram[-1] # Last character
if context not in frequency_tables[order - 1]:
frequency_tables[order - 1][context] = {}
frequency_tables[order - 1][context][char] = frequency_tables[order - 1][context].get(char, 0) + 1
return frequency_tables
User
what if we use default dict
Assistant
Using defaultdict from the collections module can simplify the management of frequency counts in our create_frequency_tables() function. It automatically initializes any new keys with a default value (in our case, we can use int which defaults to 0). This means we don't have to check whether a key exists before incrementing its value, reducing code complexity.
Here's how you'd implement the create_frequency_tables() function using defaultdict:
python
from collections import defaultdict
def 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.
"""
# Initialize a list to hold the frequency tables
frequency_tables = [defaultdict(int) for _ in range(n)] # Use default dict for counts
# Preprocess the document to remove any unwanted characters
document = document.replace('\n', '').replace('\r', '') # Clean newlines from document
length = len(document)
for i in range(length):
for order in range(1, n + 1): # Go up to n
if i + order <= length: # Ensure we do not go out of bounds
# Extract the n-gram
ngram = document[i:i + order]
if order == 1: # Unigram
frequency_tables[order - 1][ngram] += 1 # Increment the count
else: # N-grams for order > 1
context = ngram[:-1] # All but the last character
char = ngram[-1] # Last character
# Use defaultdict for nested dictionary
if context not in frequency_tables[order - 1]:
frequency_tables[order - 1][context] = defaultdict(int)
frequency_tables[order - 1][context][char] += 1 # Increment the count
return frequency_tables
User
def calculate_probability(sequence, char, tables):
"""
Calculates the probability of observing a given sequence of characters using the frequency tables.
code
- **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.
- **Returns**:
- Returns a probability value for the sequence.
"""
return 0
Implement this function
Assistant
To implement the calculate_probability() function, we need to compute the probability of observing a given character (char) immediately following a specified sequence of characters (sequence) using the provided frequency tables. The calculation will be based on the n-gram model defined in your assignment.
Steps to Implement calculate_probability()
Determine the Order: The order of the sequence will inform which frequency table to use (e.g., if the sequence has a length of k, we will use the frequency table for k-grams).
Access the Correct Frequency Table: Based on the length of the sequence, retrieve the corresponding frequency table from the tables.
Calculate the Probability:
If the order is 1 (unigrams), the probability is simply the frequency of char divided by the total occurrences of the character in the document.
For higher orders (bigrams and beyond), calculate the probability using the context (the preceding characters of the sequence) available in the frequency table.
Handle Missing Frequencies: If there are no occurrences of the preceding sequence or the character following it, the probability will be zero.
Here's the implementation:
python
User
I wanna use the default dict approach for function 1. help me implement this
Assistant
Certainly! Using defaultdict is a great way to handle frequency counts neatly in the create_frequency_tables() function.
Here's the implementation of create_frequency_tables() using defaultdict:
python
from collections import defaultdict
def 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.
"""
# Initialize a list to hold the frequency tables
frequency_tables = [defaultdict(int) for _ in range(n)] # Use default dict for counts
# Preprocess the document to remove any unwanted characters
document = document.replace('\n', '').replace('\r', '') # Clean newlines from document
length = len(document)
for i in range(length):
for order in range(1, n + 1): # Go up to n
if i + order <= length: # Ensure we do not go out of bounds
# Extract the n-gram
ngram = document[i:i + order]
if order == 1: # Unigram
frequency_tables[order - 1][ngram] += 1 # Increment the count
else: # N-grams for order > 1
context = ngram[:-1] # All but the last character
char = ngram[-1] # Last character
# Use defaultdict for nested dictionary
if context not in frequency_tables[order - 1]:
frequency_tables[order - 1][context] = defaultdict(int)
frequency_tables[order - 1][context][char] += 1 # Increment the count
return frequency_tables
User
for i in range(1, n + 1):
table = defaultdict(int)
for j in range(len(document) - i + 1):
ngram = document[j:j+i] # string of length i
table[ngram] += 1
tables.append(dict(table)) # convert to regular dict for consistency
code
return tables
does this work
Assistant
The code snippet you've provided is an alternative way to implement the n-gram frequency table creation using defaultdict. It looks close to being correct, but it has a few modifications necessary to ensure that it captures the n-gram structure correctly and manages contexts properly for bigrams and higher n-grams.
Corrections and Improvements:
Context Handling: For bigrams and higher n-grams, you need to separate the context and the next character (similar to previous examples).
Appending Tables: Make sure you're appending the constructed frequency tables correctly. You need to maintain a list of dictionaries for each order (1 to n) as the frequency tables.
Here’s a revised version of your code that does this correctly:
python
from collections import defaultdict
def 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.
"""
tables = [] # Initialize the list to hold frequency tables
for i in range(1, n + 1): # For each order from 1 to n
if i == 1: # Unigrams
table = defaultdict(int) # Frequency table for unigrams
for j in range(len(document)):
table[document[j]] += 1 # Count each character
tables.append(dict(table)) # Convert to regular dict for consistency
else: # Bigrams and beyond
table = defaultdict(lambda: defaultdict(int)) # Nested defaultdict for higher-order n-grams
for j in range(len(document) - i + 1): # Ensure we don't go out of bounds
ngram = document[j:j+i] # Extract the n-gram
context = ngram[:-1] # The context is all but the last character
char = ngram[-1] # The last character is what we want to predict
table[context][char] += 1 # Increment the count for that character given the context
tables.append(dict(table)) # Convert to regular dict for consistency
return tables
User
what is context? do we need it
Assistant
In the context of n-gram language models, context refers to the preceding characters (or tokens) that provide information about a prediction for the next character (or token). Essentially, the context is what comes before the specific point of interest in a sequence where we want to predict the next character.
Understanding Context in N-Gram Models:
N-Gram Definition: An n-gram is defined as a contiguous sequence of n items (in this case, characters or words).
Unigram (n=1): Each character is considered independently.
Bigram (n=2): The probability of a character depends on the single preceding character.
Trigram (n=3): The probability of a character depends on the two preceding characters.
Context Usage:
In a bigram model, the context is the single preceding character. E.g., if you're trying to predict the character following "t" in "the cat", the context is "t".
In a trigram model, the context could be the two preceding characters. For example, to predict the next character after "th", we would use "th" as the context.
Why Context is Important: The inclusion of context allows the language model to make better predictions based on the patterns observed in the training data. For example, the character "s" is much more likely to follow "th" (as in "this") than it is to follow "a" (as in "a").
Do We Need Context?
Yes, Context is Essential: If you want your n-gram model to be meaningful and predictive, you need to include context when making predictions. By utilizing previous characters, you can significantly improve the accuracy of your predictions.
Example without Context: If you only rely on unigrams (individual characters), your model will ignore the relationships between characters, leading to poor predictions.
Example with Context: By using a bigram or trigram model, the model becomes sensitive to the structure of the language, capturing dependencies and improving prediction.
Implementation Implications
The use of context in your create_frequency_tables function is crucial for higher-order n-grams:
For bigrams, each entry in your frequency table tracks how often a certain character follows a given character.
For trigrams, you track how often a character follows a specific two-character sequence, and so forth.
Dataset releases
Not yet included in a published release.
Explanation of the Implementation:
We create a list of frequency tables (frequency_tables), where each table is represented as a dictionary.
We iterate through each character in the document and form n-grams for each possible sequence length from 1 to n.
For unigrams, we directly update the frequency. For higher-order n-grams, we separate the last character and use it as what we want to predict, while the rest is treated as context.
Each time we form an n-gram, we check if the sequence already exists in the table and update the counts accordingly.
Next Steps:
After implementing this function, you'd proceed to implement calculate_probability() and predict_next_char() to complete the n-gram autocomplete model as described in the provided assignment overview.
Feel free to let me know if you need help with those functions or anything else!
Key Changes and Benefits:
Simpler Count Increments: The code uses += 1 for incrementing counts without needing to check if the key exists first. This reduces the amount of boilerplate code we need to write.
Nested defaultdicts: For bigrams and higher n-grams, we create a nested defaultdict. This allows us to easily initialize counts for characters that follow a context without having to check if the context key exists.
Clearer Code: Overall, using defaultdict leads to cleaner and more readable code since the logic for counting becomes more straightforward.
Next Steps:
After implementing create_frequency_tables() with defaultdict, you can continue to the next functions (calculate_probability and predict_next_char) similarly, making use of the stored frequency tables to drive the probability calculations. Let me know if you would like to continue with those implementations or if you have any questions!
def 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.
- **Returns**:
- Returns a probability value for the sequence.
"""
order = len(sequence) # Length of the sequence determines the order
if order > len(tables): # If the order is greater than n, return 0 since we have no data
return 0
# Get the corresponding frequency table for this order
frequency_table = tables[order - 1]
# For unigrams (order 1)
if order == 1:
total_count = sum(frequency_table.values()) # The total number of unigrams
return frequency_table[char] / total_count if total_count > 0 else 0
# For higher orders (bigrams and beyond)
context = sequence # Use the full sequence as context
if context not in frequency_table:
return 0 # If there's no record for this context, return 0
context_count = sum(frequency_table[context].values()) # Total number of instances for this context
return frequency_table[context][char] / context_count if context_count > 0 else 0
Explanation:
Determining the Order: We find the length of the sequence to identify which frequency table we need to access.
Checking Frequency Table:
For unigrams, we sum up all counts to get the total number of characters and compute the probability of char.
For higher orders, we check if the context (the sequence) exists in the frequency table. If it doesn't, we return 0.
Calculating Probabilities: We use the frequency counts to compute the probabilities:
For unigrams: P(char) = f(char) / N, where N is the total number of unigrams.
For context-based probabilities: P(char | context) = f(context, char) / f(context), where f(context) is the total number of occurrences of the context.
Next Steps:
You can now proceed to implement the predict_next_char() function, which will use the calculate_probability() function to determine the most likely next character based on the input sequence. Let me know if you need help with that or if you have any questions!
Explanation of the Code:
Initialization:
We use a list comprehension to create a list of defaultdict(int) for each n-gram table. This allows counts to automatically initialize to 0 when a new key is accessed, simplifying increment operations.
Preprocessing:
The document is cleaned by removing newlines to ensure each character is appropriately counted.
Building Frequency Tables:
We loop through each character of the document and form n-grams of lengths from 1 to n.
For unigrams, we directly increment the count associated with the ngram.
For higher-order n-grams, we identify the context (all characters except the last one) and the character following that context. We then increment the count of the character given the context.
For nested n-grams, we use a defaultdict(int) to automatically handle counts of characters following a specific context.
Next Steps:
This implementation can directly be integrated into your NgramAutocomplete.py file. After this, you can proceed to implement other functions like calculate_probability() and predict_next_char(). If you need assistance with those or have any other questions, feel free to ask!
Key Enhancements:
Table Initialization for Higher Orders: A nested defaultdict(int) is used for higher-order n-grams to represent the counts of characters conditioned on their contexts.
Context Extraction: Inside the loop for bigrams and higher n-grams, we separate the ngram into its context (all characters except the last) and the character being predicted.
Appending Tables: After finishing the n-gram counting, we convert the defaultdict to a regular dictionary before appending it to tables to ensure consistency.
Testing:
You can test this function with a sample document and see if it correctly counts the frequency of characters and character sequences as expected:
python
if __name__ == "__main__":
document = "abcdabc"
n = 3 # For trigram
frequency_tables = create_frequency_tables(document, n)
for i, table in enumerate(frequency_tables):
print(f"Table {i + 1}: {table}")
This setup will help you validate that the frequency tables are being built correctly. Let me know if you need further assistance!
This context is critical for calculating probabilities in the subsequent steps of your autocomplete model (e.g., in calculate_probability()).
Conclusion
In summary, yes, we definitely need context when building n-gram language models, especially when dealing with bigrams and higher orders. The context helps capture the syntactical and semantic relationships between characters in the sequence, allowing the autocomplete feature to function effectively. If you need integration or further explanations on how to use context specifically in your implementation, feel free to ask!