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
can you do it without default dict?
Assistant
User
raceback (most recent call last):
File "/Users//Desktop/CS 383/assignment-6-n-gram-complete-/main.py", line 28, in
main()
~~~~^^
File "/Users//Desktop/CS 383/assignment-6-n-gram-complete-/main.py", line 20, in main
next_char = predict_next_char(current_sequence[-n:], tables, vocabulary)
File "/Users//Desktop/CS 383/assignment-6-n-gram-complete-/NgramAutocomplete.py", line 99, in predict_next_char
prob = calculate_probability(sequence, char, tables)
File "/Users//Desktop/CS 383/assignment-6-n-gram-complete-/NgramAutocomplete.py", line 59, in calculate_probability
total_chars = sum(tables[min(n-1, sequence_length)].values())
TypeError: unsupported operand type(s) for +: 'int' and 'dict'
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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.
Sure! Here’s an implementation draft for the N-gram language model in Python based on the requirements you outlined. Below are the three main functions you'll need to complete in NgramAutocomplete.py.
NgramAutocomplete.py
python
from collections import defaultdict
def create_frequency_tables(document, n):
# Initialize a list of frequency tables
frequency_tables = [defaultdict(int) for _ in range(n)]
# Iterate through the document to populate frequency tables
for i in range(len(document)):
# Unigram (1-gram)
if i < len(document):
frequency_tables[0][document[i]] += 1
# Bigram (2-gram)
if i < len(document) - 1:
frequency_tables[1][(document[i], document[i + 1])] += 1
# Trigram (3-gram) and higher n-grams
for j in range(2, n):
if i < len(document) - j:
frequency_tables[j][tuple(document[i:i + j + 1])] += 1
return frequency_tables
def calculate_probability(sequence, char, tables):
n = len(tables)
sequence_length = len(sequence)
# Base case for unigram
if sequence_length == 0:
return tables[0][char] / sum(tables[0].values())
# For N-gram probability calculation
total_chars = sum(tables[min(n-1, sequence_length)].values())
# Depending on length of the sequence, we calculate the probabilities
if sequence_length >= n - 1:
relevant_sequence = tuple(sequence[-(n-1):]) + (char,)
else:
relevant_sequence = tuple(sequence) + (char,)
# Get the frequency of the relevant sequence
frequency_count = tables[min(n-1, sequence_length)].get(relevant_sequence, 0)
context_count = tables[min(n-1, sequence_length)].get(relevant_sequence[:-1], 0)
# Apply the formula for probability
if context_count == 0:
return 0 # To avoid division by zero
else:
return frequency_count / context_count
def predict_next_char(sequence, tables, vocabulary):
max_prob = -1
predicted_char = None
# Check probability for each character in vocabulary
for char in vocabulary:
prob = calculate_probability(sequence, char, tables)
# Find character with max probability
if prob > max_prob:
max_prob = prob
predicted_char = char
return predicted_char
Explanation:
create_frequency_tables(document, n):
This function initializes a list of frequency tables for each n from 1 to n.
It iterates over the input document, recording the frequencies of unigrams, bigrams, trigrams, etc.
calculate_probability(sequence, char, tables):
This function computes the probability of a specific character following a given sequence using the previously constructed frequency tables.
It checks the length of the sequence to decide which part of the frequency tables to use.
predict_next_char(sequence, tables, vocabulary):
This function iterates over the vocabulary and calculates the probability for each possible next character, using calculate_probability.
It keeps track of the character with the highest probability and returns that as the prediction.
Assumptions:
The input document should be a string containing characters to train the model.
The vocabulary is a set of possible characters; in this case, you may assume it consists of characters 'a', 'b', 'c', and 'd'.
Usage:
This code should be referenced in your main.py file to drive the autocomplete functionality interactively while using inputs from the user, and it will make predictions based on the training data processed through your language model.
Make sure to test thoroughly using a range of input sequences and validate the predictions against your expectations. Happy coding!
Certainly! We can implement the required functions while using regular dictionaries instead of defaultdict. In this case, we'll need to check if a key exists in the dictionary before accessing it, and if it doesn't exist, we'll provide a default value of zero. Below is the revised code:
NgramAutocomplete.py
python
def create_frequency_tables(document, n):
# Initialize a list of frequency tables
frequency_tables = [{} for _ in range(n)]
# Iterate through the document to populate frequency tables
for i in range(len(document)):
# Unigram (1-gram)
if i < len(document):
frequency_tables[0][document[i]] = frequency_tables[0].get(document[i], 0) + 1
# Bigram (2-gram)
if i < len(document) - 1:
bigram = (document[i], document[i + 1])
frequency_tables[1][bigram] = frequency_tables[1].get(bigram, 0) + 1
# Trigram (3-gram) and higher n-grams
for j in range(2, n):
if i < len(document) - j:
trigram = tuple(document[i:i + j + 1])
frequency_tables[j][trigram] = frequency_tables[j].get(trigram, 0) + 1
return frequency_tables
def calculate_probability(sequence, char, tables):
n = len(tables)
sequence_length = len(sequence)
# Base case for unigram
if sequence_length == 0:
return tables[0].get(char, 0) / sum(tables[0].values())
# For N-gram probability calculation
total_chars = sum(tables[min(n-1, sequence_length)].values())
# Depending on length of the sequence, we calculate the probabilities
if sequence_length >= n - 1:
relevant_sequence = tuple(sequence[-(n-1):]) + (char,)
else:
relevant_sequence = tuple(sequence) + (char,)
# Get the frequency of the relevant sequence
frequency_count = tables[min(n-1, sequence_length)].get(relevant_sequence, 0)
context_count = tables[min(n-1, sequence_length)].get(relevant_sequence[:-1], 0)
# Apply the formula for probability
if context_count == 0:
return 0 # To avoid division by zero
else:
return frequency_count / context_count
def predict_next_char(sequence, tables, vocabulary):
max_prob = -1
predicted_char = None
# Check probability for each character in vocabulary
for char in vocabulary:
prob = calculate_probability(sequence, char, tables)
# Find character with max probability
if prob > max_prob:
max_prob = prob
predicted_char = char
return predicted_char
Explanation of Changes:
Dictionaries:
The frequency tables are now standard dictionaries that require checking via the .get(key, default) method. If the key does not exist, it will return 0 (or whichever value default you specify).
Handling Frequency Counts:
Each time we want to update the count in the frequency tables, we check if the key exists in the dictionary. If it does, we increment the value; if it does not, we initialize it to zero and then increment.
Usage:
The revised code will function the same as before. You can integrate it into your main.py to obtain predictions based on training data. Ensure that you have tests in place to confirm that the model behaves as expected!
Feel free to ask if you need additional assistance or further modifications!
The error message you're seeing indicates that there's an issue when trying to sum the values of a dictionary in the line:
The sum function is expecting an iterable of numbers, but it appears that the dictionary values are not being interpreted as expected, perhaps due to the initialization of frequency tables or how they are populated.
Review and Fix
Let's ensure that the frequency tables are correctly initialized as dictionaries to contain integer values. Since you've been using the get method properly while updating the frequency counts, the problem likely originated in the calculation of total_chars.
We can remove the line total_chars = sum(tables[min(n-1, sequence_length)].values()) as it's unnecessary for the function we're implementing.
Updated Code for calculate_probability
Here's the refactored function along with the correction you need:
python
def calculate_probability(sequence, char, tables):
n = len(tables)
sequence_length = len(sequence)
# Base case for unigram
if sequence_length == 0:
return tables[0].get(char, 0) / sum(tables[0].values()) if sum(tables[0].values()) > 0 else 0
# Get the index for the appropriate n-gram table
index = min(n - 1, sequence_length)
# Depending on length of the sequence, we calculate the probabilities
relevant_sequence = tuple(sequence[-(index):]) + (char,)
# Get the frequency of the relevant sequence
frequency_count = tables[index].get(relevant_sequence, 0)
context_count = tables[index].get(relevant_sequence[:-1], 0)
# Apply the formula for probability
if context_count == 0:
return 0 # To avoid division by zero
else:
return frequency_count / context_count
Key Corrections Made:
Removed the total_chars Calculation: Since we don't need this in our probability calculation, it's been omitted.
Handled the Size of the Unigram Table: Added a check for the sum of the unigram frequencies, which prevents division by zero when calculating the probability for an empty document.
Generalized the Relevant Sequence: The use of index is now clarified so that it correctly accesses the intended level of n-gram depending on the length of sequence.
Summary
Make sure to update your NgramAutocomplete.py with the provided code. After doing so, check your implementation again in main.py. If any issues arise, please share the exact areas of concern or additional error messages for further diagnosis!