Traceback (most recent call last):
File "/Users//Desktop/CS 383/assignment-6-n-gram-language-models-/main.py", line 40, in
main()
File "/Users//Desktop/CS 383/assignment-6-n-gram-language-models-/main.py", line 13, in main
tables = create_frequency_tables(document, n)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users//Desktop/CS 383/assignment-6-n-gram-language-models-/NgramAutocomplete.py", line 25, in create_frequency_tables
frequency_tables[ngram] = 0
~~~~~~~~~~~~~~~~^^^^^^^
TypeError: list indices must be integers or slices, not str
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.
"""
frequency_tables = [{} for _ in range(n)] # Initialize n frequency tables
# Loop through each level of n-gram (from 1 to n)
for i in range(len(document)):
for j in range(1, n + 1):
if i + j > len(document):
break
# Check if the current n-gram exists in the frequency table as a key
ngram = document[i:i + j]
if ngram not in frequency_tables[j - 1]:
frequency_tables[ngram] = 0
frequency_tables[ngram] += 1
return frequency_tables
Assistant
The error you are encountering indicates that you are trying to use a string as an index for a list, which is not allowed in Python. Let's analyze your code to identify the issue and correct it.
In your function create_frequency_tables, you have the following line:
python
frequency_tables[ngram] = 0
This line is attempting to use ngram (which is a string) as an index for frequency_tables, which is a list. Instead, you should be indexing into the individual dictionaries within the list.
Here’s the corrected version of your create_frequency_tables function:
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.
"""
frequency_tables = [{} for _ in range(n)] # Initialize n frequency tables
# Loop through each level of n-gram (from 1 to n)
for i in range(len(document)):
for j in range(1, n + 1):
if i + j > len(document):
break
# Extract the current n-gram
ngram = document[i:i + j]
# Use the correct index to access the dictionary in frequency_tables
if ngram not in frequency_tables[j - 1]:
frequency_tables[j - 1][ngram] = 0 # Corrected indexing here
frequency_tables[j - 1][ngram] += 1 # Increment the count for this n-gram
return frequency_tables
Changes made:
The line frequency_tables[ngram] = 0 was changed to frequency_tables[j - 1][ngram] = 0 to correctly access the dictionary at the position j - 1 in the frequency_tables list.
The line frequency_tables[ngram] += 1 was changed to frequency_tables[j - 1][ngram] += 1 for the same reason.
Explanation:
frequency_tables is a list containing n dictionaries (one for each n-gram level from 1 to n). Therefore, to access the correct dictionary for each n-gram level, you need to use frequency_tables[j - 1], where j ranges from 1 to n. The j - 1 gives you the appropriate index in the list.
Each dictionary is used to store the count of each n-gram as keys with their frequencies as values.
With these corrections, your function should work without throwing a TypeError.
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.
"""
if len(sequence) > len(tables):
return 0 # Beyond the available tables, return 0 probability
# get frequency of the sequence
base_freq = tables[len(sequence) - 1][sequence]
# get frequency of the combined sequence
combined_freq = tables[len(sequence)][sequence + char] if char in tables[len(sequence)] else 0
return combined_freq / base_freq if base_freq > 0 else 0
Assistant
Your calculate_probability function is intended to compute the probability of a character following a given sequence of characters based on the frequency tables you've constructed. However, there are some areas where you need to be cautious to ensure that the function works correctly.
Here are some notes and improvements for the function:
Indexing the Frequency Tables: When accessing the frequency tables, you should ensure that the index you are using is within bounds. If the length of the sequence is equal to n, you should not access tables[len(sequence)] since this would be out of bounds.
Handling Missing Keys: The way you've attempted to access the frequency for combined_freq needs to be revised. If char is not in the appropriate frequency table, you should explicitly use the dictionary's method to avoid a KeyError.
Return Type: It’s good practice to ensure that your function always returns a float, even if the result is 0.
Here’s the corrected version:
python
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.
"""
seq_length = len(sequence)
# Ensure we do not exceed the number of tables
if seq_length > len(tables):
return 0.0 # Return 0 probability as a float
# Get the base frequency of the sequence
base_freq = tables[seq_length - 1].get(sequence, 0) # Default to 0 if the sequence is not found
# Get frequency of the combined sequence (sequence + char)
combined_freq = tables[seq_length].get(sequence + char, 0) if seq_length < len(tables) else 0
# Compute and return the probability
return (combined_freq / base_freq) if base_freq > 0 else 0.0
User
{'a': 11, 'b': 4, 'c': 5}
Sum of table: 20
{'aa': 5, 'ab': 3, 'ba': 2, 'bc': 2, 'ca': 3, 'ac': 2, 'cc': 1, 'cb': 1}
Sum of table: 19
{'aab': 2, 'aba': 1, 'bab': 1, 'abc': 2, 'bca': 2, 'cac': 1, 'acc': 1, 'cca': 1, 'caa': 2, 'aaa': 1, 'aac': 1, 'acb': 1, 'cba': 1, 'baa': 1}
Sum of table: 18
Probability of observing 'a': 0.0
Probability of observing 'b': 0.0
Probability of observing 'c': 0.0
Probability of observing 'aa': 0.45454545454545453
Its not right for single letters
Assistant
The probability calculation for individual characters in your calculate_probability function seems to be resulting in zero, which indicates that the frequency of those characters following an empty sequence is not being calculated correctly. Let's analyze the problem and correct it.
Explanation of Issues:
Calculating Probabilities for Single Characters: The basic issue here lies in how you're setting up to compute the probability of observing a character (like 'a', 'b', or 'c') in sequence. Specifically, the logic for calculating the base frequency and combined frequency should correctly reflect the conditions under which these frequencies are calculated.
Understanding Frequencies:
For a single character probability, you might be trying to find the frequency of the character in the context of an empty sequence. In this case, you would want to look also at the total frequency of that character without requiring it to follow another character, which might not be captured by the n-gram table designed for sequences.
Adjustments Needed:
For calculating the probability of a single character, you can create a special case when sequence is an empty string. In this case, directly get the frequency of the character from the first frequency table (which should capture unigrams) and divide that by the total frequency of all characters.
Here’s a corrected version of your calculate_probability function addressing the single character probabilities:
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
To calculate the probabilities as requested, we will first summarize the methodology that will be applied. We'll be using the conditional probabilities provided in your probability tables. Then, we'll work through each of the requested calculations step by step.
Given Vocabulary and Frequency Tables
From your example, we have a simplified vocabulary of characters {a, b, c} based on the training document "aababcaccaaacbaabcaa" and the frequency tables constructed during your implementation. Here are the relevant parts of the frequency tables for single letters and pairs (unigrams and bigrams):
Frequency Tables
Unigram Frequencies (P(a), P(b), P(c)):
(f(a) = 11)
(f(b) = 4)
(f(c) = 5)
Total Frequency (N) = (20)
Probability Table 1:
(P(\odot))
Probability Value
(P(a))
(\frac{11}{20} = 0.55)
(P(b))
(\frac{4}{20} = 0.20)
(P(c))
(\frac{5}{20} = 0.25)
Bigram Frequencies:
For Conditional Probabilities, assume the following calculated values based on your earlier data:
(P(\odot))
Probability Value
(P(a \mid a))
(\frac{5}{11} \approx 0.4545)
(P(b \mid a))
(\frac{3}{11} \approx 0.2727)
(P(c \mid a))
(\frac{2}{11} \approx 0.1818)
(P(a \mid b))
(\frac{2}{4} = 0.5)
(P(b \mid b))
(0)
(P(c \mid b))
(\frac{2}{4} = 0.5)
(P(a \mid c))
(\frac{3}{5} = 0.6)
(P(b \mid c))
(\frac{1}{5} = 0.2)
(P(c \mid c))
(\frac{1}{5} = 0.2)
Trigram Frequencies: Similar logic applies, but since these are more complex, we will primarily use the bigrams for our calculations.
Calculations
Calculation of (P(X_1 = a, X_2 = a, X_3 = a))
[
P(X_1 = a, X_2 = a, X_3 = a) = P(X_1=a) \cdot P(X_2=a \mid X_1=a) \cdot P(X_3=a \mid X_1=a, X_2=a)
]
User
P(X1=a,X2=a,X3=b)
Put it in this form that works in github readme
Assistant
Certainly! When representing mathematical expressions in a GitHub README, you can use Markdown with LaTeX-style syntax for clear formatting. Below is how you would present the calculation for ( P(X_1 = a, X_2 = a, X_3 = b) ) in a Markdown-friendly format:
markdown
### Calculation of \( P(X_1 = a, X_2 = a, X_3 = b) \)
To compute \( P(X_1 = a, X_2 = a, X_3 = b) \), we can use the following formula:
\[
P(X_1 = a, X_2 = a, X_3 = b) = P(X_1 = a) \cdot P(X_2 = a \mid X_1 = a) \cdot P(X_3 = b \mid X_1 = a, X_2 = a)
\]
Substituting values from our frequency tables:
1. From the unigram table:
\[
P(X_1 = a) = P(a) = 0.55
\]
2. From the bigram table:
\[
P(X_2 = a \mid X_1 = a) = P(a \mid a) = \frac{5}{11} \approx 0.4545
\]
3. Now for the conditional probability of the bigram:
\[
P(X_3 = b \mid X_1 = a, X_2 = a) = P(b \mid a,a) = \frac{2}{5} = 0.4
\]
Now, we can compute the overall probability:
\[
P(X_1 = a, X_2 = a, X_3 = b) = 0.55 \cdot 0.4545 \cdot 0.4
\]
Calculating this:
\[
P(X_1 = a, X_2 = a, X_3 = b) \approx 0.55 \cdot 0.4545 \cdot 0.4 \approx 0.100
\]
### Conclusion
Thus, the probability \( P(X_1 = a, X_2 = a, X_3 = b) \) is approximately \( 0.100 \).
Important Points:
Use the backslashes (\) to escape any LaTeX-style commands and formatting.
Use double dollar signs ($$) for block math equations or single dollar signs ($) for inline math.
Make sure Markdown rendering is supported in your environment for the LaTeX to render correctly.
This will correctly display in a GitHub README, letting readers see both the formulas and calculations in a structured manner. If this format is not rendering properly as expected on GitHub, you may need to ensure that the Markdown viewer supports LaTeX rendering as per GitHub's standards.
Now for the conditional probability of the bigram:
P(X3=b∣X1
Now, we can compute the overall probability:
P(X1=a,X2=
Calculating this:
P(X1=a,X2=
Thus, the probability P(X1=a,X2=a,X is approximately .
Do the first and third in this format with the $
Assistant
Sure! Here’s how you would present the calculations for ( P(X_1 = a, X_2 = a, X_3 = a) ) and ( P(X_1 = a, X_2 = a, X_3 = c) ) using the same formatting as you provided, utilizing LaTeX syntax for clarity.
Calculation of ( P(X_1 = a, X_2 = a, X_3 = a) )
We start with the formula:
[
P(X_1 = a, X_2 = a, X_3 = a) = P(X_1 = a) \cdot P(X_2 = a \mid X_1 = a) \cdot P(X_3 = a \mid X_1 = a, X_2 = a)
]
Substituting values from our frequency tables:
From the unigram table:
[
P(X_1 = a) = P(a) = 0.55
]
From the bigram table:
[
P(X_2 = a \mid X_1 = a) = P(a \mid a) = \frac{5}{11} \approx 0.4545
]
For the conditional probability:
[
P(X_3 = a \mid X_1 = a, X_2 = a) = P(a \mid a,a) = \frac{1}{5} = 0.2
]
Now, we can compute the overall probability:
[
P(X_1 = a, X_2 = a, X_3 = a) = 0.55 \cdot 0.4545 \cdot 0.2
]
Calculating this:
[
P(X_1 = a, X_2 = a, X_3 = a) \approx 0.55 \cdot 0.4545 \cdot 0.2 \approx 0.050
]
Thus, the probability ( P(X_1 = a, X_2 = a, X_3 = a) ) is approximately ( 0.050 ).
Calculation of ( P(X_1 = a, X_2 = a, X_3 = c) )
We start with the formula:
[
P(X_1 = a, X_2 = a, X_3 = c) = P(X_1 = a) \cdot P(X_2 = a \mid X_1 = a) \cdot P(X_3 = c \mid X_1 = a, X_2 = a)
]
Substituting values from our frequency tables:
From the unigram table:
[
P(X_1 = a) = P(a) = 0.55
]
From the bigram table:
[
P(X_2 = a \mid X_1 = a) = P(a \mid a) = \frac{5}{11} \approx 0.4545
]
For the conditional probability:
[
P(X_3 = c \mid X_1 = a, X_2 = a) = P(c \mid a,a) = \frac{1}{5} = 0.2
]
Now, we can compute the overall probability:
[
P(X_1 = a, X_2 = a, X_3 = c) = 0.55 \cdot 0.4545 \cdot 0.2
]
Calculating this:
[
P(X_1 = a, X_2 = a, X_3 = c) \approx 0.55 \cdot 0.4545 \cdot 0.2 \approx 0.050
]
Thus, the probability ( P(X_1 = a, X_2 = a, X_3 = c) ) is approximately ( 0.050 ).
Feel free to adjust any parts or ask additional questions if you need further clarifications!
User
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?
Assistant
To determine the most likely next character in the sequence based on the previously calculated probabilities ( P(X_1 = a, X_2 = a, X_3 = a) ), ( P(X_1 = a, X_2 = a, X_3 = b) ), and ( P(X_1 = a, X_2 = a, X_3 = c) ), we will summarize the obtained probabilities and conclude which character has the highest probability.
Summary of Calculated Probabilities
( P(X_1 = a, X_2 = a, X_3 = a) \approx 0.050 )
( P(X_1 = a, X_2 = a, X_3 = b) \approx 0.100 )
( P(X_1 = a, X_2 = a, X_3 = c) \approx 0.050 )
Characteristics of the Probability Distribution
From the probabilities calculated:
The highest probability is for ( P(X_1 = a, X_2 = a, X_3 = b) ) which is approximately ( 0.100 ).
The probabilities for ( a ) and ( c ) are lower at ( 0.050 ) each.
Conclusion: Next Character Prediction
Given these probabilities, the next character predicted in the sequence ( "aa" ) is "b".
Thus, based on the calculated probabilities and the frequency distribution of the characters following the sequence ( "aa" ), the most likely next character is:
Character: "b"
If you have any further questions or need additional calculations or clarifications, feel free to ask!
User
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.
The corpus for Alice and wonderland works much better because it is a much shorter document so there is less of a document to process compared to the war and peace. Whenever we do an n > about 10/15 with the war and peace text, the program takes a good amount of time to run and the calculations become time-consuming. The shorter the corpus the more efficient the algorithm is. When I ran the war and peace for n=25 it took about 3 minutes to run completely, so as n gets larger the more time it takes will predictively get longer in correlation.
Assistant
Experiment Findings
In my experiments with the provided corpus files using varying values of ( n ), I observed that the corpus for Alice's Adventures in Wonderland performed significantly better than War and Peace. This can be attributed to the shorter length of Alice's Adventures in Wonderland, which results in a more manageable dataset that can be processed quickly. Conversely, the larger size of the War and Peace text caused the program to become increasingly time-consuming when ( n ) exceeded approximately 10 or 15. For instance, when I attempted to run the model with ( n = 25 ) on the War and Peace text, it took about 3 minutes to complete the calculations. This clearly indicates that, as ( n ) increases, the complexity and time required for n-gram table calculations grow significantly, leading to exponentially larger tables as well as longer processing times. Consequently, shorter corpora yield more efficient performance, allowing for quicker predictions and better usability of the model.
This experience reinforces the importance of balancing the choice of corpus and the value of ( n ) to maintain reasonable processing times while still achieving effective predictions.
User
My create frequency tables take in the document, and n then starts by creating empty objects for each n-gram table. Then we loop through the document for each char i, and from that char, we get each ngram of lengths 1 to n. If we don't already have it in our n-gram table, we create the object and make it zero, then after no matter what we add 1 because we've encountered it in the document. This will go through the document and for every i, get the grams up to length n, then move to the next position. Then it will return the frequency tables of objects with their counts.
Assistant
Your description of the create_frequency_tables function for generating n-gram frequency tables is mostly clear, but let me offer a slightly more structured and detailed breakdown. This will help in understanding the logic and ensure you're capturing the essential operations involved in the n-gram frequency table creation.
Overview of create_frequency_tables Function
The purpose of the create_frequency_tables function is to process a text document and construct frequency tables for n-grams (1-grams, 2-grams, ..., n-grams). Here's a detailed outline based on your description:
Initialization:
Create a list of empty dictionaries, where each dictionary corresponds to a frequency table for different n-gram lengths (from 1 to ( n )).
For example, frequency_tables[0] will store unigram frequencies, frequency_tables[1] will store bigram frequencies, and so on.
Loop Through Document:
For each character i in the document, iterate through possible n-gram lengths from 1 to ( n ).
For each n-length, extract the n-gram from the document starting at position i.
Update Frequency Tables:
Check if the extracted n-gram already exists in the corresponding frequency table (the dictionary at index j - 1 for an n-gram of length j):
If it does not exist, add it to the dictionary with an initial count of zero.
Increment the count of that n-gram by 1, indicating its occurrence in the document.
Return:
Finally, return the list of frequency tables containing the counts for all observed n-grams.
Pseudocode Example:
Here’s a concise pseudocode representation of the process:
Safe Dictionary Access: Used get method for safe access to the frequency dictionaries which returns 0 if the key does not exist.
Index Check: Added a condition to check whether seq_length < len(tables) when trying to access tables[seq_length], preventing index out of bounds.
Return Type Consistency: Ensured that the function always returns a float.
Function Logic:
If the length of the sequence exceeds the number of available n-gram tables, the function returns a probability of 0.
It calculates the base_freq for the input sequence and checks for the frequency of the combined_freq (which is the sequence followed by the character).
Finally, it computes the probability, ensuring that there’s no division by zero.
With these changes, the calculate_probability function should work correctly and robustly handle edge cases.
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.
"""
seq_length = len(sequence)
# Ensure we do not exceed the number of tables
if seq_length > len(tables):
return 0.0 # Return 0 probability as a float
# Handle the case for single character probabilities
if seq_length == 0:
total_frequency = sum(tables[0].values()) # Total frequency of all single characters
char_freq = tables[0].get(char, 0) # Frequency of the character
return char_freq / total_frequency if total_frequency > 0 else 0.0
# Get the base frequency of the sequence
base_freq = tables[seq_length - 1].get(sequence, 0) # Default to 0 if the sequence is not found
# Get frequency of the combined sequence (sequence + char)
combined_freq = tables[seq_length].get(sequence + char, 0) if seq_length < len(tables) else 0
# Compute and return the probability
return (combined_freq / base_freq) if base_freq > 0 else 0.0
Key Changes:
Special Case for Empty Sequence: When sequence is empty, the function calculates the total frequency of all single characters and the frequency of char, allowing you to compute the probability correctly.
We use sum(tables[0].values()) to calculate the total frequency of all single-character n-grams for normalization when computing the probability of char.
This revision will correctly compute the probability of single letters ('a', 'b', 'c', etc.) within your n-gram frequency tables instead of returning 0.0. Make sure your tables are constructed correctly and include the necessary unigrams for accurate results.
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.
2. Computing Joint Probabilities for a Language Model
In general, Bayesian Networks are used to visually represent the dependencies (edges) between distinct random varaibles (nodes) in a large joint distribution.
In the case of a language model, each node in the network corresponds to a character in the sequence, and edges represent the conditional dependencies between them.
For a character sequence of length 4 a bayesian network for our the full joint distribution of 4 letter sequences would look as follows.
Where X1 is a random variable that maps to the character found at position 1 in a character sequence, X2 maps to the character at position 2, and so on.
This makes clear how the chain rule can be applied to expand the full joint form of a probability distribution.
In our case we are interested in computing the next character (the character at position 4) given the characters at the previous positions (characters at position 1, 2, and 3). Applying the definition of conditional distributions we can see this is
If we wanted to predict the most likely next character, we could compute the probability of every possible completion given each character in our vocabularly. This will give us a probability distribution over the next character prediction P(X4=x4∣X1=t,X2=h,X3=u). Taking the character with the max probability value in this distribution gives us an autocomplete model.
General Case:
Given a sequence x1,x2,…,xt, the probability of the next character xt+1 is calculated as:
P(xt+1∣x1,x2,…,xt)=P(x1,x2,…,xt)P
This can be generalized for different values of t, using the corresponding frequency tables.
N-gram models:
For short sequences, we can compute our joint probabilities in their entirity. However, as the sequences grows longer, our tables become exponentially larger and this problem quickly grows intractable. Enter n-gram models. An n-gram model is the same model we described above except only n-1 characters are considered as context for the prediction.
That is for a bigram model n=2 we estimate the joint probability as
Putting this network in terms of computations via our frequency tables is now slightly different as we now have to consider the ratio for each term
P(X1=x1,X2=x
Where size(C) is the total number of characters in the corpus. Consider how this generalizes to an arbitrary n-gram model for any n, this will be the core of your implementation. Write this formula in your report.
Starter Code Overview
The project starter code is structured across three main Python files:
NgramAutocomplete.py: This is where the main logic of the autocomplete model is implemented. You are expected to complete three functions in this file: create_frequency_tables(), calculate_probability(), and predict_next_char().
main.py: This file provides the user interface and controls the flow of the program. It initializes the model, takes user inputs, and runs the character prediction process iteratively. You may modify this file to test their code, but no modifications are required to complete the project.
utilities.py: This file includes helper functions that facilitate the program, such as reading and preprocessing the training document. No modifications are needed in this file.
TODOs
NgramAutocomplete.py is the core file where you will change in this project. Each function here builds upon each other to create a probabilistic model for predicting the next character in a sequence.
1. create_frequency_tables(document, n)
This function constructs a list of n frequency tables for an n-gram model, each table capturing character frequencies with increasing conditional dependencies.
Parameters:
document: The text document used to train the model.
n: The number of value of n for the n-gram model.
Returns:
Returns a list of n frequency tables.
2. calculate_probability(sequence, char, tables)
Calculates the probability of observing a given sequence of characters using the frequency tables.
Parameters:
sequence: The sequence of characters whose probability we want to compute.
tables: The list of frequency tables created by create_frequency_tables(), this will be of size n.
char: The character whose probability of occurrence after the sequence is to be calculated.
Predicts the most likely next character based on the given sequence.
Parameters:
sequence: The sequence used as input to predict the next character.
tables: The list of frequency tables.
vocabulary: The set of possible characters.
Functionality:
Calculates the probability of each possible next character in the vocabulary, using calculate_probability().
Returns:
Returns the character with the maximum probability as the predicted next character.
A Reports section
383GPT
Did you use 383GPT at all for this assignment (yes/no)?
Yes
create_frequency_tables(document, n)
Code analysis
My create frequency tables take in the document, and n then starts by creating empty objects for each n-gram table. Then we loop through the document for each char i, and from that char, we get each ngram of lengths 1 to n. If we don't already have it in our n-gram table, we create the object and make it zero, then after no matter what we add 1 because we've encountered it in the document. This will go through the document and for every i, get the grams up to length n, then move to the next position. Then it will return the frequency tables of objects with their counts.
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
a, b, and c
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)
204
P(c)
205
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)
11
Write down your probability table 3:
P(⊙)
Probability value
P(a∣a,a)
calculate_probability(sequence, char, tables)
Formula
Write the formula for sequence likelihood as described in section 2P(xt+1∣x1,x2,…,xt)=P(x1,x2,…,xt)P
Code analysis
Put the intuition of your code here
The calculate probability function will take in the variables and then check if the sequence is greater than the length of our tables, meaning we don't have an n-gram table to calculate it, and if so returns 0. If the length is 0, it means that it's only a single character so we just have to divide the frequency of a character by the total count of all chars. If it is between 0 and len(sequence), then we simply get the frequency of the original sequence as our denominator, and then the sequence with the new char as our numerator and return it.
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)
P(X1=a)∗P(X
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!
Help me
Calculate the following and show all the steps involved
P(X1=a,X2=a,X3=a)
P(X1=a)∗P(X
P(X1=a,X2=a,X
P(X1=a,X2=a,X
Substituting from the tables:
[
P(X_1=a) = P(a) = 0.55
]
For (P(X_2 = a \mid X_1 = a)):
[
P(X_2=a \mid X_1=a) = P(a \mid a) = \frac{5}{11} \approx 0.4545
]
For (P(X_3 = a \mid X_1 = a, X_2 = a)):
We need the trigram (P(a \mid a,a)), which from earlier work is:
[
P(a \mid a,a) = \frac{1}{5} = 0.2
]
Thus:
[
P(X_1 = a, X_2 = a, X_3 = a) = 0.55 \cdot 0.4545 \cdot 0.2 \approx 0.050
]
Calculation of (P(X_1 = a, X_2 = a, X_3 = b))
[
P(X_1 = a, X_2 = a, X_3 = b) = P(X_1=a) \cdot P(X_2=a \mid X_1=a) \cdot P(X_3=b \mid X_1=a, X_2=a)
]
Substituting:
[
P(X_1 = a) = P(a) = 0.55 \
P(X_2 = a \mid X_1 = a) = P(a \mid a) = 0.4545
]
For (P(X_3 = b \mid X_1 = a, X_2 = a)):
We need to find (P(b \mid a,a)), which is (\frac{2}{5}):
[
P(b \mid a,a) = \frac{2}{5} = 0.4
]
Hence:
[
P(X_1 = a, X_2 = a, X_3 = b) = 0.55 \cdot 0.4545 \cdot 0.4 \approx 0.100
]
Calculation of (P(X_1 = a, X_2 = a, X_3 = c))
[
P(X_1 = a, X_2 = a, X_3 = c) = P(X_1=a) \cdot P(X_2=a \mid X_1=a) \cdot P(X_3=c \mid X_1=a, X_2=a)
]
Substituting:
[
P(X_1 = a) = P(a) = 0.55 \
P(X_2 = a \mid X_1 = a) = P(a \mid a) = 0.4545
]
[
P(X_1 = a, X_2 = a, X_3 = c) = 0.55 \cdot 0.4545 \cdot 0.2 \approx 0.050
]
Summary of Results
(P(X_1 = a, X_2 = a, X_3 = a) \approx 0.050)
(P(X_1 = a, X_2 = a, X_3 = b) \approx 0.100)
(P(X_1 = a, X_2 = a, X_3 = c) \approx 0.050)
If you need further assistance on this or any additional calculations, feel free to ask!
a)=
P(a∣
a)=
115≈
0.4545
=
a,X2=
a)=
P(b∣
a,a)=
52=
0.4
a
,
X3
=
b)=
0.55⋅
0.4545⋅
0.4
a
,
X3
=
b)≈
0.55⋅
0.4545⋅
0.4≈
0.100
3
=
b)
0.100
def create_frequency_tables(document, n):
# Step 1: Initialize frequency tables
frequency_tables = [{} for _ in range(n)]
# Step 2: Loop through each position in the document
for i in range(len(document)):
for j in range(1, n + 1): # j represents n-gram lengths
if i + j > len(document):
break # Prevent out-of-bounds
# Step 3: Extract the n-gram
ngram = document[i:i + j]
# Update the frequency table for n-grams of length j
if ngram not in frequency_tables[j - 1]:
frequency_tables[j - 1][ngram] = 0
frequency_tables[j - 1][ngram] += 1 # Increment count
# Step 4: Return the frequency tables
return frequency_tables
Explanation of the Steps:
Initialization: Using a list comprehension initializes the frequency tables.
Looping and Extracting: By nested loops, the algorithm iterates through sequences of characters of varying lengths and prepares the n-grams.
Updating Counts: The program uses dictionary functionalities to manage the counts efficiently, checking for existence and updating values.
Return Statement: Finally, the function returns the list that contains all the frequency tables constructed.
Conclusion
Your description accurately captures the essence of the algorithm, and the structured outline should provide a clear picture of how the function operates. Just remember that the efficiency of this method can be influenced by the size of the document and the chosen value of ( n ), especially for larger texts with high n-values, as discussed in your earlier findings. If you need any further details or examples related to n-gram models, feel free to ask!