this is readme:
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.
Assistant
User
how to commit changes github codespace
Assistant
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.
image
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
1
∣
x
2
)
⋅
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
image
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
1
∣
x
2
)
⋅
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.
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.
Returns:
Returns a probability value for the sequence.
3. predict_next_char(sequence, tables, vocabulary)
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/no)?
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
)
11
20
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
(
X
1
a
,
X
2
a
,
X
3
a
)
Show your work
P
(
X
1
a
,
X
2
a
,
X
3
b
)
Show your work
P
(
X
1
a
,
X
2
a
,
X
3
c
)
Show your work
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!
this is the file:
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'
Sure! Let's break down how we can implement the functions mentioned in your file to create a simple N-gram language model that predicts the next character based on a given sequence. Below are detailed implementations for create_frequency_tables, calculate_probability, and predict_next_char along with explanations.
Step 1: Implementing create_frequency_tables
This function will read the document and compute frequency counts for the character sequences.
python
def create_frequency_tables(document, n):
"""
Constructs a list of `n` frequency tables for an n-gram model.
Each table captures character frequencies with increasing conditional dependencies.
Parameters:
document (str): The text document used to train the model.
n (int): The number of value of `n` for the n-gram model.
Returns:
list: A list of `n` frequency tables.
"""
from collections import defaultdict
tables = [defaultdict(int) for _ in range(n)]
length = len(document)
for i in range(length):
for j in range(1, n + 1):
if i + j <= length:
ngram = document[i:i + j]
tables[j - 1][ngram] += 1
return tables
Step 2: Implementing calculate_probability
This function will compute the conditional probability of a specific character following a given sequence, based on the previously computed frequency tables.
python
def calculate_probability(sequence, char, tables):
"""
Calculates the probability of observing a given sequence of characters using the frequency tables.
Parameters:
sequence (str): The sequence of characters whose probability we want to compute.
char (str): The character whose probability of occurrence after the sequence is to be calculated.
tables (list): The list of frequency tables created by `create_frequency_tables()`.
Returns:
float: The probability value for the sequence.
"""
n = len(tables)
sequence_length = len(sequence)
if sequence_length < 1 or sequence_length > n:
return 0 # Invalid input, can't calculate probability
# Get the frequency of the character that follows the sequence
ngram = sequence + char
sequence_ngram = sequence[-(sequence_length - 1):]
if sequence_length > 1:
freq = tables[sequence_length - 1][ngram]
total = tables[sequence_length - 1][sequence]
return (freq / total) if total > 0 else 0
else:
# For single character, treat it as a unigram
freq = tables[0][char]
total = sum(tables[0].values())
return (freq / total) if total > 0 else 0
Step 3: Implementing predict_next_char
This function will use the previously defined functions to predict the next character based on the highest calculated probability.
python
def predict_next_char(sequence, tables, vocabulary):
"""
Predicts the most likely next character based on the given sequence.
Parameters:
sequence (str): The sequence used as input to predict the next character.
tables (list): The list of frequency tables.
vocabulary (set): The set of possible characters.
Returns:
str: The character with the maximum probability as the predicted next character.
"""
probabilities = {}
for char in vocabulary:
probabilities[char] = calculate_probability(sequence, char, tables)
# Find the character with the max probability
predicted_char = max(probabilities, key=probabilities.get)
return predicted_char
Explanation of the Code:
create_frequency_tables: This function creates frequency tables for n-grams from the provided document. It uses a defaultdict to count occurrences of each n-gram. It iterates through the document, constructing n-grams of size from 1 to n and populating the respective tables.
calculate_probability: This function calculates the conditional probability of a character following a given sequence based on the frequency tables. It checks the last n-length of the sequence to define which n-gram table to use and computes the probability using the frequency counts.
predict_next_char: This function predicts the next character by computing the probabilities for all characters in the vocabulary and returning the character with the highest probability based on the preceding sequence.
Variables and Returns
Vocabulary: For demonstration with the sample document "aababcaccaaacbaabcaa", the vocabulary will be {'a', 'b', 'c', 'd'}.
Probability Tables:
For Unigrams (Table 1):
P(a) = Count(a) / Total Count
P(b) = Count(b) / Total Count
P(c) = Count(c) / Total Count
For Bigrams (Table 2):
P(a | a) = Count(aa) / Total Count of a's
P(b | a) = Count(ab) / Total Count of a's
Similar for others.
For Trigrams (Table 3): It follows a similar counting process.
Example Calculation
Using the document "aababcaccaaacbaabcaa":
Total counts might result in something like:
Table 1:
P(a) = 11/20
P(b) = 4/20
P(c) = 5/20
P(d) = 0/20
When asked for predictions given a sequence 'aa':
Calculate probabilities for each character in vocabulary as described above.
Finally, you can call these functions from the main.py to see how they work together for predictions based on user input.
Feel free to modify or expand upon this implementation according to your project needs! If you have any questions, don't hesitate to ask.
Committing changes in a GitHub Codespace is similar to committing changes in any Git repository. Here are the steps you need to follow to commit your changes in GitHub Codespaces:
Open Your Codespace: Start by launching your GitHub Codespace from the repository you want to work on.
Make Changes: Use the integrated editor to make your changes to the files in your project.
Open the Terminal (Optional): You can use the built-in terminal in Codespaces for Git commands, or you can use the Source Control panel in the GUI.
To open the terminal, you can go to the top menu and select Terminal > New Terminal or use the shortcut `Ctrl + `` (backtick).
Check Git Status: You can verify which files have been modified by running the following command in the terminal:
bash
git status
This command will show you the current status of your repository, including any modified, staged, or untracked files.
Stage Changes: If you want to commit all the changes, you can stage them with:
bash
git add .
If you want to stage specific files, replace . with the file names, like so:
bash
git add filename.py
Commit Changes: Now, commit your changes with a meaningful commit message that describes what you've done. Use the following command:
git commit -m "Implemented character prediction algorithm"
Push Changes: Once your changes are committed, you need to push them to the remote repository on GitHub with:
bash
git push
Check Your Repository on GitHub: After you push your changes, you can go to your GitHub repository in your web browser to confirm that your changes have been reflected.
Alternative: Using the GUI
If you prefer the graphical interface:
Source Control Panel: Click on the Source Control icon on the left sidebar (it looks like a branch).
Stage Changes: You will see all your changed files. Hover over the files and click the + icon to stage them, or you can click "Stage All Changes".
Commit Changes: Below the staged files, you will see a text box for your commit message. Enter your message and click on the checkmark icon or press Ctrl + Enter to commit.
Push Changes: After committing, you may find a button to push your changes right there in the same panel or you can use the terminal to use the git push command.
That's it! Your changes should now be committed and pushed to your GitHub repository. If you have more specific scenarios or issues, feel free to ask!