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
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!
summarize this
Bayes Complete: Sentence Autocomplete Using N-Gram Language Models - Summary
Assignment Objectives
Understand n-gram language models' mathematical principles.
Implement an n-gram language model from scratch.
Apply the model for sentence autocomplete functionality.
Analyze the model's performance.
Project Overview
You will build a sentence autocomplete feature that predicts the next character in a sequence based on an n-gram language model. The model will analyze a text corpus, construct frequency tables for character sequences, and predict likely continuations, enabling faster user expression in applications like messaging apps.
Key Components
Frequency Table Creation:
Construct character frequency tables for unigrams, bigrams, trigrams, etc., based on the corpus.
Computing Joint Probabilities:
Apply Bayesian principles to predict the next character based on existing context using frequency tables.
N-Gram Model Implementation:
The model only considers the last n-1 characters for predictions, allowing for tractable computations.
Starter Code
NgramAutocomplete.py: Implement key functions for frequency table creation, probability calculation, and character prediction.
main.py: User interface and control flow (modification not required).
utilities.py: Helper functions for document reading and preprocessing.
TODOs in NgramAutocomplete.py
create_frequency_tables(document, n): Create frequency tables for different n-gram models.
calculate_probability(sequence, char, tables): Compute the probability of a character following a given sequence.
predict_next_char(sequence, tables, vocabulary): Predict the next character using the calculated probabilities.
Submission Instructions
Submit the NgramAutocomplete.py and a PDF report generated from your README.md via your browser's print function.
Report Sections
Address specific aspects of the implementation, including:
Usage of tools (e.g., 383GPT).
Code analysis and intuition for each function.
Probability calculations using example sequences.
Conclusion
Experiment with various corpuses and n values to assess performance. Analyze the efficiency of n-gram models as n increases and determine the optimal n for predictions.
The assignment emphasizes hands-on understanding of language models, practical coding skills, and analytical evaluation of model performance.
For assistance, seek support during office hours or reach out for clarification on any doubts. Happy coding!