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
User
Assistant
User
vocabulary is set like this
vocabulary = set(tables[0])
Assistant
User
Enter the number of grams (n): 8
Enter an initial sequence: th
Enter the length of completion (k): 2
Updated sequence: thí
Updated sequence: thíí
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.
Submission Instructions
You are to include 2 files in a single Gradescope submission: a PDF of your Report Section and your NgramAutocomplete.py.
How to generate a pdf of your Report Section:
On your Github repository after finishing the assignment, click on readme.md to open the markdown preview.
Use your browser 's "Print to PDF" feature to save your PDF.
Please submit to Assignment 6 N-Gram Complete on Gradecsope.
A Reports section
383GPT
Did you use 383GPT at all for this assignment (yes/no)?
Late Days
How many late days are you using for this assignment?
create_frequency_tables(document, n)
Code analysis
Put the intuition of your code here
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
Write it here
Write down your probabillity table 1:
as in P(a),P(b),…
For table 1, as in your probability table should look like this:
P(⊙)
Probability value
P(a)
2011
P(b)
??
P(c)
??
Write down your probability table 2:
as in your probability table should look like (wait a second, you should know what I'm talking about)
P(⊙)
Probability value
P(a∣a)
??
Write down your probability table 3:
You got this!
calculate_probability(sequence, char, tables)
Formula
Write the formula for sequence likelihood as described in section 2
Code analysis
Put the intuition of your code here
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
Calculate the following and show all the steps involved
P(X1=a,X2=a,X3=a)
Show your work
P(X1=a,X2=a,X
P(X1=a,X2=a,X
predict_next_char(sequence, tables, vocabulary)
Code analysis
Put the intuition of your code here
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?
Your answer
Experiment
Experiment with the given corpus files and varying values of n. Do any corpus work better than others? How high of a value of n can you run before the table calculation becomes too time consuming? Write a short paragraph describing your findings.
Please don't hesitate to reach out to us in case of any questions (no question is dumb), and come meet us during office hours XD!
Happy coding!
here is the starting code:
main.py:
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()
NgramAutocomplete.py:
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'
utilities.py:
from collections import defaultdict
def read_file(filename):
with open(filename, "r", encoding="utf-8") as file:
text = file.read().lower()
return text
Print the frequency tables
def print_table(tables, n):
n += 1
for i in range(n):
print(f"Table {i+1} (n(i_{i+1} | i_{i}, ..., i_1)):")
for char, prev_chars_dict in tables[i].items():
for prev_chars, count in prev_chars_dict.items():
print(f" P({char} | {prev_chars}) = {count}")
code
k = 0
for i in tables:
print(f"Printing table {k}")
k += 1
for j, v in i.items():
print(j, ' : ', dict(v))
Sure! Let’s break down how to implement the functions in your NgramAutocomplete.py file step by step, and then I'll help you with the report section structure based on your project requirements.
Implementation
create_frequency_tables(document, n)
This function will create frequency tables for the n-grams. You will need to keep track of the frequencies of characters and their n-1 prefixes in a dictionary.
Here's how you can implement it:
python
def create_frequency_tables(document, n):
tables = []
# Initialize frequency tables for each n from 1 to n
for i in range(n):
tables.append(defaultdict(lambda: defaultdict(int)))
# Iterate over the document to populate the frequency tables
for i in range(len(document)):
for j in range(n):
# Make sure we don't go out of bounds
if i + j < len(document):
current_char = document[i + j]
# Create the context (prefix)
prefix = document[i:i + j]
# Increment the count for the character following the prefix
tables[j][current_char][prefix] += 1
return tables
calculate_probability(sequence, char, tables)
This function will compute the probability of a given character following a sequence based on the frequency tables.
Here’s an example implementation:
python
def calculate_probability(sequence, char, tables):
n = len(tables)
seq_length = len(sequence)
# Determine which table to use based on the length of the sequence
if seq_length < n:
return 0 # Not enough context for n-gram
# Limit the sequence to the last n-1 characters for prediction
context = sequence[-(n-1):] if n > 1 else ""
# Get frequency of the sequence with the character
f_seq_char = tables[len(context)][char][context] if context in tables[len(context)][char] else 0
# Get frequency of the sequence
f_seq = sum(tables[len(context)][c][context] for c in tables[len(context)]) if context in tables[len(context)] else 0
# To avoid division by zero
if f_seq == 0:
return 0
# Calculate probability
probability = f_seq_char / f_seq
return probability
predict_next_char(sequence, tables, vocabulary)
In this function, you will compute the probabilities of all potential next characters and return the one with the maximum probability.
Here’s how to implement it:
python
def predict_next_char(sequence, tables, vocabulary):
probabilities = {}
for char in vocabulary:
prob = calculate_probability(sequence, char, tables)
probabilities[char] = prob
# Find the character with the maximum probability
next_char = max(probabilities, key=probabilities.get)
return next_char
Report Section
Now, you can use the following structure to complete your report section as per your assignment guidelines.
Report Section
383GPT
Did you use 383GPT at all for this assignment (yes/no)?
No
Late Days
How many late days are you using for this assignment?
0
create_frequency_tables(document, n)
Code Analysis
The function constructs frequency tables by iterating through the document. It keeps count of how often each character appears following its n-1 preceding characters.
Compute Probability Tables
1. Vocabulary:
Given the document "aababcaccaaacbaabcaa", the vocabulary consists of {'a', 'b', 'c'}.
2. Probability Table 1:
P(⊙)
Probability Value
P(a)
2011
3. Probability Table 2:
P(⊙)
Probability Value
$P(a
a)$
$P(b
a)$
$P(c
a)$
$P(a
b)$
$P(a
c)$
4. Probability Table 3:
P(⊙)
Probability Value
$P(a
a, a)$
$P(b
a, a)$
$P(c
a, a)$
calculate_probability(sequence, char, tables)
Formula
The formula for sequence likelihood is
P(X
Code Analysis
The function extracts appropriate frequency counts and computes the resulting probability for any character occurrence following the given sequence.
Your Calculations
P(a,a,a)=f(a,a)f(.
predict_next_char(sequence, tables, vocabulary)
Code Analysis
This function gathers the probabilities of each character following the input sequence and selects the character with the highest probability.
So what should be the next character in the sequence?
The next character based on the computed probabilities could be determined from the highest probability calculated in the previous function call.
Experiment
Upon testing various n values with different corpus files, it was noted that a larger n typically leads to better predictions but increases computation time significantly. Smaller values of n are computationally cheaper but yield less accurate completions. The exploration of varying values revealed optimal ranges typically around 2 to 5 for practical performance before significant slowdowns occurred.
With these implementations and structured content for your report, you should be all set for your assignment submission! Don’t forget to test each part vigorously to ensure your n-gram model works well. Good luck!
From your provided output, it seems like the frequency table for n=1 has been correctly computed, but there are a couple of points to clarify and consider:
What's Accurate
Frequency Table Construction:
You have the frequency table for unigrams (n=1) displayed. It shows how many times each character occurs in the training document. This is consistent with what is expected for the unigram frequency representation. The defaultdict structure effectively allows you to initialize counts on the fly.
Count of Characters:
Each character, along with its count, is shown correctly. The defaultdict is being used to map each character to its frequency counts, which is appropriate.
Updated Sequence:
The output shows you added the predicted character ” based on the input sequence I. This suggests your predict function is working and returning a result.
Areas to Improve or Check
Character Set:
Ensure that your training document is appropriate and clean. The presence of many special characters (e.g., ”, ‘, ’, etc.) makes it crucial to define what constitutes your vocabulary. If the goal is to predict only standard letters or specific characters, you might want a more refined vocabulary from your training corpus.
Probability Calculations:
Since your n=1, the detection of character frequencies is correct, but you should verify that your probability calculations in further parts of your code accurately reflect the intended behavior when using calculate_probability() and predict_next_char().
Reason for Prediction:
The predicted next character being ” after I might imply that the model has seen this combination frequently in the text corpus. It’s important to consider if this is the expected behavior based on the context you're working with. Is it typical for the text you're using?
Generalization:
Generally, when only using n=1, the predictions might not reflect meaningful linguistic constructs. As n increases (e.g., n=2 for bigrams), you'll get context-sensitive predictions that should yield more accurate and appropriate completions.
Debugging:
If the predicted outcome does not align with expectations (for example if you expect a space or a letter after I), debugging through your calculate_probability and predict_next_char functions would be beneficial to ensure they are leveraging the frequency tables correctly.
In Summary
Your frequency tables look correct as an initial output for n=1, and the predicted character after I (I”) seems valid given the context of your training corpus. Ensure your vocabulary and prediction logic align with what you want your model to achieve, and consider expanding your n-gram analysis to see how well it performs with greater context. If you refine these areas based on your goals, you should achieve more meaningful predictions!
Using vocabulary = set(tables[0]) means that you are constructing your vocabulary based on the frequency table for unigrams (the first table in your list of frequency tables). This is a reasonable approach for an n-gram model, especially for unigrams, as it collects all the unique characters that have been counted.
Breakdown of Vocabulary Creation
Source:
tables[0] corresponds to the first frequency table, which is for unigrams. This table tracks the frequency of each character individually.
Set Construction:
Using set() will create a unique collection of characters from the first frequency table, allowing you to use this as your vocabulary for predictions.
Considerations
Content:
Ensure that this vocabulary contains all the characters you want to include for predictions. For unigrams, it will include every character that appears in your document. If your document includes special characters, they'll also be included in the vocabulary. Depending on your application's context, you may want to filter this set to include only letters, digits, or other specific characters.
Use of Vocabulary in Predictions:
When you pass this vocabulary to the predict_next_char function, make sure that the prediction logic is designed to handle all characters contained in the vocabulary. If your frequency tables have characters that aren't included in the vocabulary (unlikely, but possible if the corpus is cleaned or transformed), it may affect your predictions.
Updating Character Frequencies:
The vocabulary's content should ideally align with the intended use. If you're working with a specific language model, adjusting the vocabulary to remove characters that shouldn't appear in typical completions can improve predictions.
Example Output Check
Given your usage (and after you compute the frequency tables):
python
# This will give you all unique characters based on the first frequency table (unigrams)
vocabulary = set(tables[0])
print(vocabulary)
This should output a collection of characters that you've utilized in your document, including letters, spaces, punctuation, and any other visible characters.
Testing Predictions
Once you have this vocabulary:
Character Predictions:
Use the predict_next_char function with the vocabulary, ensuring that the function is checking against all characters available in your vocabulary when determining the most likely next character.
Debugging Predictions:
If you see a predicted character that seems out of place (like a punctuation character when expecting a letter), check if:
The training corpus contains sufficient text to determine meaningful character frequencies.
Your model's input sequence allows for more common characters to be predicted based on historical context within the corpus.
Conclusion
Your method of setting the vocabulary based on the first frequency table (tables[0]) is correct and should work as intended for making predictions. Just keep an eye on how the training data influences what characters appear in your predictions, and ensure the character set is appropriate for your application's needs!
Based on the output of your n-gram model with n=8, where the initial sequence is "th" and you are trying to complete it with 2 characters, the results show that your predictions resulted in the sequence being expanded to "thí" and then "thíí". Here are some points to consider regarding this output:
1. Understanding the Output
The model predicts the next character to be í after the input "th", and then it repeats this character again.
This indicates that the model's frequency table has determined that based on the context "th", the character í has a strong likelihood of being the next character.
2. Implications of an n=8 Model
High n-grams: At n=8, the model looks at the last 7 characters (because it predicts the next character based on the previous 7) to make predictions.
Data Sparsity: If your training text is not very large or does not contain many sequences of 8 characters or longer, the model may not have enough data to make accurate predictions. Instead, it can fall back to less relevant predictions.
Contextual Dependence: Given such a high value for n, any slight variation or uncommon character sequence can lead the model to make less meaningful predictions. The character í might appear frequently in the context of a larger sequence, leading to its selection, even if it isn't a common following character for "th".
3. Suggestions for Improvement
Experimenting with n:
Test lower values of n (like 2, 3, or 4) to see if the predictions become more reasonable. Often, n-gram models will behave much better within a certain range (often between 2 and 5).
With lower values of n, the model will consider fewer preceding characters, potentially leading to more sensible predictions in everyday text.
Training Corpus:
Ensure the corpus you are using is representative of the language patterns you want to predict. If you are not seeing meaningful predictions, it could be a sign that the text used for training is not comprehensive.
For instance, if a certain character (such as í) is a valid character following "th" in your dataset, ensure that your corpus has robust examples of this and that it’s fitting for the intended applications.
Debugging Predictions:
You can add logging to see the probabilities calculated via your calculate_probability function to understand which characters are competing for selection.
Inspect the frequency tables generated for n=8 to see if other characters are even being considered against í.
4. Output Validation
When seeing a series of the same character (like thíí), it can sometimes indicate that the model keeps falling back on the same prediction due to it being the most frequent one available given the context. Ensure that your method for selecting a character is robust enough to favor diversity or combine probabilities effectively to avoid repetitive outputs.
Conclusion
Ultimately, predicting thí and then expanding to thíí might only appear correct if taken in the specific context of your training data. To make your model more flexible and accurate, consider adjusting the value of n and examining your frequency distributions more closely to inform better predictions. If you continue to see unusual outputs, further refinement of input sequences and training data could yield better results.