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.
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.
Assistant
To implement the autocomplete feature using an n-gram language model, we need to focus on building the three key functions in NgramAutocomplete.py. Let's go through the requirements and provide a potential implementation for each of these functions.
1. create_frequency_tables(document, n)
This function constructs frequency tables for n-grams from the given document. The frequency tables should be stored in a list, where each index corresponds to a frequency table (unigram, bigram, trigram, etc.).
python
from collections import defaultdict
def create_frequency_tables(document, n):
# Initialize a list of frequency tables
tables = [defaultdict(int) for _ in range(n)]
# Clean the document and extract characters
document = document.replace("\n", " ").replace("\r", "") # Basic cleaning
length = len(document)
# Loop through the document to gather frequencies
for i in range(length):
# Count unigrams
if i < length:
tables[0][document[i]] += 1
# Count bigrams
if i < length - 1:
tables[1][(document[i], document[i + 1])] += 1
# Count trigrams
if i < length - 2:
tables[2][(document[i], document[i + 1], document[i + 2])] += 1
# Extend for larger n values
for j in range(3, n):
if i < length - j + 1:
ngram = tuple(document[i:i + j])
tables[j][ngram] += 1
return tables
2. calculate_probability(sequence, char, tables)
This function computes the probability of the next character given the sequence and the frequency tables. We apply the n-gram model and utilize the count from the frequency tables.
python
User
is this correct based on all the requiremnets? 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.
"""
# Initialize a list of frequency tables
tables = [defaultdict(int) for _ in range(n)]
# Clean the document and extract characters
document = document.replace("\n", " ").replace("\r", "") # Basic cleaning
length = len(document)
# Loop through the document to gather frequencies
for i in range(length):
# Count unigrams
if i < length:
tables[0][document[i]] += 1
# Count bigrams
if i < length - 1:
tables[1][(document[i], document[i + 1])] += 1
# Count trigrams
if i < length - 2:
tables[2][(document[i], document[i + 1], document[i + 2])] += 1
# Extend for larger n values
for j in range(3, n):
if i < length - j + 1:
ngram = tuple(document[i:i + j])
tables[j][ngram] += 1
return tables
def calculate_probability(sequence, char, tables):
"""
Calculates the probability of observing a given sequence of characters using the frequency tables.
code
Assistant
Your implementation of the functions create_frequency_tables, calculate_probability, and predict_next_char appears to be quite good overall, but there are a few points worth addressing in order to ensure correctness and better adherence to the requirements. Let’s review each function step-by-step.
1. create_frequency_tables(document, n)
This function does a good job initializing frequency tables and counting the occurrences of unigrams, bigrams, and trigrams. Here are a few suggestions for improvements:
Handling longer n-grams: The current implementation has the right logic to iterate through lengths of 3 to n, but it would be beneficial to clarify how it captures sequences based on the value of n. Ensure that it correctly constructs frequency tables for all values from 1 to n.
Edge Cases: If the document is very short (e.g., fewer than n characters), the function should handle those scenarios gracefully.
Here’s the revised portion of the function that better captures these aspects:
python
def create_frequency_tables(document, n):
tables = [defaultdict(int) for _ in range(n)]
# Clean the document and extract characters
document = document.replace("\n", " ").replace("\r", "").strip() # Additional strip
length = len(document)
# Loop through the document to gather frequencies
for i in range(length):
# Count unigrams
tables[0][document[i]] += 1
if i < length - 1: # Count bigrams
tables[1][(document[i], document[i + 1])] += 1
if i < length - 2: # Count trigrams
tables[2][(document[i], document[i + 1], document[i + 2])] += 1
# Extend for larger n values
for j in range(3, n):
if i < length - j + 1:
ngram = tuple(document[i:i + j])
tables[j][ngram] += 1
return tables
User
what should the output of my program look like?
Assistant
The expected output of your autocomplete program will depend on how you structure the user interface in main.py (which you are allowed to modify for testing) and the input you provide. However, the general purpose of your program is to predict the next character(s) based on a given sequence of characters.
Here’s a typical flow along with expected outputs:
Initialization:
When the program starts, you might prompt the user to input a text document (to train the model) or initialize the model with a predefined training text.
Example Output:
code
Please enter the training document:
This is a sample training document for the autocomplete model.
Offering Input for Prediction:
After training, prompt for input sequences from the user for which they want predictions.
Example Output:
code
Enter a sequence to predict the next character (type 'exit' to quit):
thu
Getting Predictions:
Based on the input sequence, the program predicts the next character by leveraging the trained n-gram model.
Example Output:
code
The predicted next character for 'thu' is: 's'
Continuous Prediction:
You might loop this so the user can continuously input sequences until they wish to stop.
Example Output:
code
Enter a sequence to predict the next character (type 'exit' to quit):
The predicted next character for 'aut' is: 'o'
Enter a sequence to predict the next character (type 'exit' to quit):
Exit
Goodbye!
Handling Cases:
If a user inputs a sequence that hasn’t previously been encountered in the training document, your program should handle it gracefully, potentially returning a message indicating that it cannot predict the next character.
Example Output:
code
Enter a sequence to predict the next character (type 'exit' to quit):
xyz
The predicted next character for 'xyz' is: None (or 'unknown', or whatever default you choose)
Summary of Output Expectations
The output should clearly indicate what the user has input and the predicted next character or message.
Maintain a clean, friendly interface where users can easily understand the output.
Handle edge cases gracefully, such as unknown sequences or when predictions are not possible.
To implement this, ensure in main.py you include prompts and print statements that clearly show each step to the user. This helps demonstrate how effectively your n-gram model works and allows users to interact with it smoothly.
User
fix my code from collections import defaultdict
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.
"""
# Initialize a list of frequency tables
tables = [defaultdict(int) for _ in range(n)]
# Clean the document and extract characters
document = document.replace("\n", " ").replace("\r", "") # Basic cleaning
length = len(document)
# Loop through the document to gather frequencies
for i in range(length):
# Count unigrams
if i < length:
tables[0][document[i]] += 1
# Count bigrams
if i < length - 1:
tables[1][(document[i], document[i + 1])] += 1
# Count trigrams
if i < length - 2:
tables[2][(document[i], document[i + 1], document[i + 2])] += 1
# Extend for larger n values
for j in range(3, n):
if i < length - j + 1:
ngram = tuple(document[i:i + j])
tables[j][ngram] += 1
return tables
def calculate_probability(sequence, char, tables):
"""
Calculates the probability of observing a given sequence of characters using the frequency tables.
code
Assistant
Your code looks mostly functional, but there are a few adjustments and improvements that can be made to ensure robustness and clarity. Below, I'll address some changes and improvements, including:
Handling edge cases in the frequency calculations.
Using Laplace smoothing to avoid probability being zero if a character or context is unseen.
Simplifying any repetitive checks.
Correcting the predict_next_char to ensure it returns as required without print statements within the function.
Here’s your corrected and improved code:
python
User
Enter the number of grams (n): 3
Enter an initial sequence: the
Enter the length of completion (k): 5
Updated sequence: theó
Updated sequence: theóó
Updated sequence: theóóó
Updated sequence: theóóóó
Updated sequence: theóóóóó
Assistant
Based on your provided input and the output format, it seems like you are working on an autocomplete system that predicts and appends characters to an initial sequence. The output indicates that the program successfully takes an initial sequence ("the"), and subsequently adds more characters based on the prediction logic of your n-gram language model. The character appears to change to "ó," which is possibly an encoded character rather than one of your initial vocabulary characters ('a', 'b', 'c', 'd').
Expected Output
Given the sequence and process you described, here's a broader idea of how your program would function, focusing on predicting a sequence of characters based on the input.
Input Specifications:
Number of grams n: Defines how many previous characters will be considered for prediction (in this case, 3).
Initial sequence: the (the prefix for which predictions will be made).
Length of completion k: Defines how many characters should be predicted and appended to the initial sequence (in this case, 5).
Output:
The output shows the updated sequence after each appended predicted character. It seems that on each iteration, it predicts and appends characters based on the last three characters (since n is 3).
Example Flow
Assuming you have initialized your n-gram model successfully, and based on the input you provide, the function may look something like this:
python
def autocomplete(sequence, tables, vocabulary, length):
""" Generate the autocomplete sequence based on the existing sequence and tables. """
for _ in range(length): # Replace k with the desired completion length
next_char = predict_next_char(sequence, tables, vocabulary) # Predict the next character
sequence += next_char # Append the predicted character
print(f"Updated sequence: {sequence}") # Show updated sequence
Example Interaction
You could expect the interaction in your program to look like this:
code
User
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. from collections import defaultdict
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.
"""
# Initialize a list of frequency tables
tables = [defaultdict(int) for _ in range(n)]
# Clean the document and extract characters
document = document.replace("\n", " ").replace("\r", "").strip() # Basic cleaning
length = len(document)
# Loop through the document to gather frequencies
for i in range(length):
# Count unigrams
tables[0][document[i]] += 1
if i < length - 1: # Count bigrams
tables[1][(document[i], document[i + 1])] += 1
if i < length - 2: # Count trigrams
tables[2][(document[i], document[i + 1], document[i + 2])] += 1
# Extend for larger n values
for j in range(3, n):
if i < length - j + 1:
ngram = tuple(document[i:i + j])
tables[j][ngram] += 1
return tables
Assistant
Your code for the functions create_frequency_tables, calculate_probability, and predict_next_char in NgramAutocomplete.py looks solid and well-structured. I see that you've incorporated some improvements, especially the use of Laplace smoothing for probability calculations, which is essential for handling unseen events in n-gram models. Below, I provide a concise review and a few recommendations to ensure clarity and effectiveness in your implementation:
1. create_frequency_tables
Strengths:
The initialization of frequency tables using defaultdict(int) allows for easy frequency counting.
Cleaning the document before processing ensures that extraneous whitespace doesn't interfere with your counts.
Suggestions:
Your code correctly handles the creation of frequency tables for unigrams, bigrams, trigrams, and larger n-grams.
Consider adding a check at the beginning of the function to handle short documents (shorter than n characters) so that it doesn't attempt to access out-of-bounds indices.
2. calculate_probability
Strengths:
Nice incorporation of Laplace smoothing, which is essential for preventing zero probabilities in unseen events.
The checks for the context length and utilization of frequency tables seem logical.
Suggestions:
The section where you handle the case when the sequence is empty could be clarified. You might want to leave a comment explaining that if the sequence is empty, it defaults to calculating the probability of seeing char in an unigram context.
In your current implementation, if you get a zero frequency for the context, you directly return a small probability for the char. As it stands, the line you have does not handle the case of unseen events correctly in some scenarios. Ensure that the whole probability calculation flows logically, with the smoothing logic applied uniformly.
Here’s a refined version of that probability calculation that ensures clarity:
python
User
are these requiremnts followed ??? 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.
Assistant
Let's evaluate your implementation against the stated requirements to determine if they are followed correctly.
1. create_frequency_tables(document, n)
Requirements:
Functionality: Constructs a list of n frequency tables for an n-gram model.
Parameters:
document: Text document used for training.
n: Number indicating the size of the n-gram model.
Returns: A list of n frequency tables.
Evaluation:
Functionality:
The function builds frequency tables for unigrams, bigrams, trigrams, and potentially higher n-grams correctly.
Each table captures the character frequencies as required.
Parameters:
The function accepts document and n, which matches the requirements.
Returns:
It correctly returns a list of frequency tables.
Your implementation here follows the requirements satisfactorily.
2. calculate_probability(sequence, char, tables)
Requirements:
Functionality: Calculates the probability of observing a given sequence using the frequency tables.
Parameters:
sequence: The character sequence to compute the probability for.
tables: List of frequency tables created by create_frequency_tables().
char: The character for which to calculate the probability of occurrence after the sequence.
Returns: A probability value for the sequence.
Evaluation:
Functionality:
The logic for calculating the probability using frequency tables is implemented correctly.
The incorporation of Laplace smoothing is a useful enhancement that ensures robustness against unseen events, even though it's not explicitly required in the basic functionality.
Parameters:
Accepts sequence, char, and tables, in alignment with the specifications.
:
User
is this how its supposed to look? Enter the number of grams (n): 3
Enter an initial sequence: the
Enter the length of completion (k): 5
Updated sequence: the
Updated sequence: the
Updated sequence: the
Updated sequence: the
Updated sequence: the
Assistant
The output you provided seems to show a sequence of inputs and updates that occur in a character completion context, but it doesn't clearly indicate the intended functionality of the autocomplete model. Let’s break down what you might expect from a completed run of the autocomplete program based on what you've implemented and what a user would likely anticipate:
Expected Behavior of Autocomplete Program
Inputs:
The user inputs the number of grams (n): e.g., 3.
The user enters an initial sequence: e.g., the.
The user specifies the length of completion (k): e.g., 5.
Processing:
Based on the initial sequence the, and using the n-gram model, the program should predict the next characters based on the training data.
The model would update the sequence iteratively until it matches the specified length of completion.
Expected Output:
The output should reflect how the initial sequence extends as the model predicts additional characters.
Instead of just spaces being added, you would likely want to see the actual predictions for each step in the sequence.
Example Interaction Output
A more informative goal for your output could look like this:
code
Enter the number of grams (n): 3
Enter an initial sequence: the
Enter the length of completion (k): 5
Updated sequence: the q (where 'q' is predicted next character)
Updated sequence: the qu (where 'u' is predicted next character)
Updated sequence: the qui (where 'i' is predicted next character)
Updated sequence: the quic (where 'c' is predicted next character)
Updated sequence: the quick (where 'k' is predicted next character)
Key Points for Clarity
Correct Number of Characters Added: Ensure that at each step, your program is producing meaningful characters and not just spaces.
Progressive Updates: Each update of the sequence should reflect what the model predicts until the specified length of completion (k) is reached.
Meaningful Interaction: It’s important that the sequence gets updated meaningfully rather than just padding with spaces, which doesn't provide any insight or value to the user.
User
add that to the code
Assistant
Certainly! Below is an updated version of your main.py code that incorporates the interaction flow for the autocomplete functionality. This code assumes that you have already defined the functions create_frequency_tables, calculate_probability, and predict_next_char as previously discussed in NgramAutocomplete.py.
Updated main.py
You'll need to add this code to your main.py file. This code handles user input and demonstrates the functioning of the autocomplete feature:
python
from NgramAutocomplete import create_frequency_tables, calculate_probability, predict_next_char
def main():
# Assuming you have a function to read the training document.
document = "Your large corpus of text goes here for training." # Placeholder for actual text corpus
n = int(input("Enter the number of grams (n): "))
# Create frequency tables based on the training document
tables = create_frequency_tables(document, n)
initial_sequence = input("Enter an initial sequence: ")
k = int(input("Enter the length of completion (k): "))
current_sequence = initial_sequence
for _ in range(k):
next_char = predict_next_char(current_sequence, tables, {'a', 'b', 'c', 'd'}) # Adjust vocabulary as needed
current_sequence += next_char
print(f"Updated sequence: {current_sequence}")
# Ensure to call main() if this script is executed directly
if __name__ == "__main__":
main()
Explanation of Code Changes
Input Handling:
Prompts for the number of grams (n), initial sequence, and length of completion (k) from the user.
Frequency Table Creation:
Calls create_frequency_tables to generate frequency tables from the provided document (you may want to replace the placeholder with your actual text corpus).
User
dont add to main, add the .py
Assistant
Understood! Below is a complete implementation of the NgramAutocomplete.py file, which includes your previously defined functions along with the interactive sequence completion logic directly integrated into the script. This way, it is a standalone file that can be executed as a program.
Complete NgramAutocomplete.py
python
User
what did u add?
Assistant
I added the entire interactive functionality to the NgramAutocomplete.py file and provided a complete implementation of the script that includes the main logic for the n-gram model. Here's a detailed breakdown of the structure and the components I incorporated:
What Was Added
Main Functionality:
Main method: Included the main() function that serves as the entry point of the script. This function prompts the user for input and demonstrates the autocomplete functionality interactively.
User Interaction:
User Prompts: The script asks the user for three inputs:
The number of grams (n) for the n-gram model.
An initial character sequence to begin the predictions.
The desired length of the completion (k), which determines how many characters will be predicted.
Completion Loop:
Inside the main() function, a loop is added that:
Uses the predict_next_char function to predict the next character based on the current sequence.
Appends the predicted character to the current sequence.
Prints the updated sequence after each prediction.
Example Vocabulary:
The vocabulary provided in predict_next_char has been set to a placeholder {'a', 'b', 'c', 'd'} but can be adjusted to fit your actual application needs.
How It All Works Together
Initialization: When the script runs, it will initialize and create frequency tables from the provided document (a placeholder in this example).
Predictive Loop: Based on the initial user-provided sequence, the model will predict subsequent characters one by one, displaying the resulting sequence after each character is predicted.
Final Summary of Changes
With these adjustments, the NgramAutocomplete.py now not only includes the definitions of your n-gram functions but also a complete interactive feature for predicting characters based on user input. This allows users to test the model's functionality directly in the terminal and see the complete process of how the sequence gets extended dynamically.
You can replace the placeholder text in the document variable with your own corpus for meaningful predictions, and feel free to update the vocabulary to include characters relevant to your use case.
If there are any specific alterations, features, or additional functionalities you would like to add, let me know!
User
still looks like Enter the number of grams (n): 3
Enter an initial sequence: the
Enter the length of completion (k): 5
Updated sequence: the
Updated sequence: the
Updated sequence: the
Updated sequence: the
Updated sequence: the
Assistant
I see that the output you provided still shows the initial sequence followed by empty spaces instead of meaningful character predictions. This suggests that the predictive model is not functioning correctly, likely due to issues in the predict_next_char or calculate_probability functions, or possibly in the data passed through them.
Let's go through the process step-by-step and clarify both the expected functionality and any necessary changes to ensure that meaningful predictions occur.
Steps to Ensure Meaningful Predictions
Ensure a Full Vocabulary: The vocabulary provided should contain all the characters you expect to predict from. In the code, I provided a placeholder vocabulary ({'a', 'b', 'c', 'd'}), which isn't likely sufficient if you're trying to predict based on natural text. Use a vocabulary that matches the training corpus.
Implementing the Functions Properly: Let's ensure that your frequency tables are built correctly, and there is valid interaction between calculated probabilities and predictions.
Example Implementation with More Reasonable Vocabulary: Here’s an updated version of the code that includes a more realistic vocabulary and corrects any potential pitfalls. Replace the placeholder corpus with a proper character set.
Updated NgramAutocomplete.py Code
python
User
stop here is the .txt i have The Project Gutenberg eBook of Alice's Adventures in Wonderland
This ebook is for the use of anyone anywhere in the United States and
most other parts of the world at no cost and with almost no restrictions
whatsoever. You may copy it, give it away or re-use it under the terms
of the Project Gutenberg License included with this ebook or online
at www.gutenberg.org. If you are not located in the United States,
you will have to check the laws of the country where you are located
before using this eBook.
Title: Alice's Adventures in Wonderland
Author: Lewis Carroll
Illustrator: Gordon Robinson
Release date: August 12, 2006 [eBook #19033]
Language: English
Original publication: Sam'l Gabriel Sons & Company New York
Credits: Produced by Jason Isbell, Irma Spehar, and the Online
Distributed Proofreading Team at http://www.pgdp.net
*** START OF THE PROJECT GUTENBERG EBOOK ALICE'S ADVENTURES IN WONDERLAND ***
Produced by Jason Isbell, Irma Spehar, and the Online
Distributed Proofreading Team at http://www.pgdp.net
code
[Illustration: Alice in the Room of the Duchess.]
_THE "STORYLAND" SERIES_
ALICE'S ADVENTURES IN WONDERLAND
SAM'L GABRIEL SONS & COMPANY
NEW YORK
Copyright, 1916,
by SAM'L GABRIEL SONS & COMPANY
NEW YORK
ALICE'S ADVENTURES IN WONDERLAND
[Illustration]
I--DOWN THE RABBIT-HOLE
Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do. Once or twice she had peeped into the
book her sister was reading, but it had no pictures or conversations in
it, "and what is the use of a book," thought Alice, "without pictures or
conversations?"
So she was considering in her own mind (as well as she could, for the
day made her feel very sleepy and stupid), whether the pleasure of
making a daisy-chain would be worth the trouble of getting up and
picking the daisies, when suddenly a White Rabbit with pink eyes ran
close by her.
Assistant
Thank you for providing the text from "Alice's Adventures in Wonderland." You can use this text as your training corpus for the autocomplete model. Here’s how you can integrate this text into your existing NgramAutocomplete.py to ensure the model works as intended when predicting character sequences based on the text.
Steps to Integrate the Text
Save the Text as a File: First, save the provided text into a text file named alice_in_wonderland.txt.
Modify the Code: Adjust the main() function in your NgramAutocomplete.py to read from this text file instead of using the placeholder text.
Updated NgramAutocomplete.py Code
Here’s how your code should look after these changes. The key change is where the document is loaded from the alice_in_wonderland.txt file:
python
User
dont addd anythimng for main!!! remove main, thats a seperate one that cant be chnaged
Assistant
Understood! I apologize for the confusion. Let’s focus exclusively on the essential components of the NgramAutocomplete.py without touching the main() function or any input and output handling.
Here’s the updated NgramAutocomplete.py file, excluding the main() function. You can integrate it into your existing codebase:
NgramAutocomplete.py
python
from collections import defaultdict
def create_frequency_tables(document, n):
"""
Constructs a list of n frequency tables for an n-gram model.
Parameters:
- document: The text document used to train the model.
- n: The number of grams for the n-gram model.
Returns:
- A list of n frequency tables.
"""
tables = [defaultdict(int) for _ in range(n)]
document = document.replace("\n", " ").replace("\r", "").strip()
length = len(document)
for i in range(length):
# Count unigrams
tables[0][document[i]] += 1
if i < length - 1: # Count bigrams
tables[1][(document[i], document[i + 1])] += 1
if i < length - 2: # Count trigrams
tables[2][(document[i], document[i + 1], document[i + 2])] += 1
# Extend for larger n values
for j in range(3, n):
if i < length - j + 1:
ngram = tuple(document[i:i + j])
tables[j][ngram] += 1
return tables
def calculate_probability(sequence, char, tables):
"""
Calculates the probability of observing a given sequence using the frequency tables.
Parameters:
- sequence: The character sequence for which the probability is computed.
- tables: The frequency tables created by create_frequency_tables().
- char: The character whose probability follows the sequence.
Returns:
- The calculated probability.
"""
n = len(tables)
sequence_length = len(sequence)
if sequence_length == 0:
return tables[0][char] / sum(tables[0].values())
n_used = min(sequence_length, n) - 1
context = tuple(sequence[-n_used:])
context_freq = tables[n_used][context] if n_used > 0 else sum(tables[0].values())
next_char_freq = tables[n_used + 1][tuple(sequence[-n_used:] + (char,))] if n_used + 1 < n else tables[0][char]
return (next_char_freq + 1) / (context_freq + len(tables[0])) # Applying Laplace smoothing
def predict_next_char(sequence, tables, vocabulary):
"""
Predicts the most likely next character based on the given sequence.
Parameters:
- sequence: The sequence used for prediction.
- tables: The frequency tables.
- vocabulary: The set of possible characters.
Returns:
- The character with the highest probability.
"""
max_prob = float('-inf')
max_char = None
for char in vocabulary:
prob = calculate_probability(sequence, char, tables)
if prob > max_prob:
max_prob = prob
max_char = char
return max_char
User
my output Enter the number of grams (n): 3
Enter an initial sequence: the
Enter the length of completion (k): 5
Updated sequence: the
Updated sequence: the
Updated sequence: the
Updated sequence: the
Updated sequence: the
Assistant
If your output is showing the initial sequence followed by just spaces (like "the", then "the ", "the ", etc.) without meaningful character predictions, it indicates a few potential issues likely related to your n-gram model's setup.
Here’s a checklist to troubleshoot and ensure that the predictions are functioning correctly, specifically in terms of the implementation:
1. Check the Vocabulary
Make sure that the vocabulary you are using in the predict_next_char function accurately reflects the characters in the training document. If the vocabulary is too limited or contains unexpected characters, it could lead to poor predictions.
2. Verify Frequency Tables Creation
Ensure that your frequency tables are getting populated correctly. After calling create_frequency_tables, you can add some debugging print statements to check if the tables contain meaningful data.
3. Review Probability Calculations:
Make sure the probability calculations effectively return valid probabilities. Double-check that each conditional probability is calculated based on the correct n-gram context.
Debugging Steps
Print Frequency Tables: After each call to create_frequency_tables, print out the frequency tables to see if they contain the expected counts.
python
tables = create_frequency_tables(document, n)
for i, table in enumerate(tables):
print(f"Table {i+1} frequencies: {dict(table)}")
Print Vocabulary: Ensure that the vocabulary is correctly created:
python
vocabulary = set(document) # Make sure this is from a suitable document
print(f"Vocabulary: {vocabulary}")
Check probability outputs: Before returning the predicted character, print the calculated probabilities for the next character for debugging.
python
print(f"Character: {char}, Probability: {prob}")
Updated Predict Function Example
Here’s how you might adjust part of your predict_next_char function for debugging purposes:
python
Dataset releases
Not yet included in a published release.
def calculate_probability(sequence, char, tables):
n = len(tables)
sequence_length = len(sequence)
# If the sequence is empty, we fall back to unigram probability
if sequence_length == 0:
return tables[0][char] / sum(tables[0].values())
# Determine which n-gram table to use
n_used = min(sequence_length, n) - 1 # n-1 for the context
last_n_gram = tuple(sequence[-n_used:]) + (char,)
if n_used == 0: # If no context, unigram case
return tables[0][char] / sum(tables[0].values())
# Check the frequency of the preceding context
context = tuple(sequence[-n_used:])
if tables[n_used][context] == 0:
return 0 # No context found (or smoothed)
# Calculate the probability using the frequency tables
return tables[n_used + 1][last_n_gram] / tables[n_used][context]
This function predicts the most likely next character using the provided sequence and frequency tables. It calculates the probability for each character in the vocabulary and returns the character with the maximum probability.
python
def predict_next_char(sequence, tables, vocabulary):
max_char = None
max_prob = float('-inf')
for char in vocabulary: # Iterate through vocabulary
prob = calculate_probability(sequence, char, tables)
if prob > max_prob:
max_prob = prob
max_char = char
return max_char # Return the character with the maximum probability
Notes
Data Structures: defaultdict(int) is used for frequency tables to initialize counts to zero automatically.
Edge Cases: The functions handle edge cases like empty sequences by falling back to unigram probabilities or returning zeros when no counts are available.
Vocabulary: The vocabulary is expected to be a set of characters, in this case consisting of {'a', 'b', 'c', 'd'}.
Efficiency: The code may need optimizations depending on the corpus size, especially in calculate_probability for higher values of n.
With these functions implemented, you should have a simple yet functional n-gram autocomplete model. Ensure to test the model with various inputs to verify its accuracy and performance.
- **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.
"""
n = len(tables)
sequence_length = len(sequence)
# If the sequence is empty, we fall back to unigram probability
if sequence_length == 0:
return tables[0][char] / sum(tables[0].values())
# Determine which n-gram table to use
n_used = min(sequence_length, n) - 1 # n-1 for the context
last_n_gram = tuple(sequence[-n_used:]) + (char,)
if n_used == 0: # If no context, unigram case
return tables[0][char] / sum(tables[0].values())
# Check the frequency of the preceding context
context = tuple(sequence[-n_used:])
if tables[n_used][context] == 0:
return 0 # No context found (or smoothed)
# Calculate the probability using the frequency tables
return tables[n_used + 1][last_n_gram] / tables[n_used][context]
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.
"""
max_char = None
max_prob = float('-inf')
for char in vocabulary: # Iterate through vocabulary
prob = calculate_probability(sequence, char, tables)
if prob > max_prob:
max_prob = prob
max_char = char
return max_char # Return the character with the maximum probability
2. calculate_probability(sequence, char, tables)
This function is well-implemented, especially in terms of managing the context from the sequence. Here are a couple of minor tweaks:
Probability Calculation Without Found Frequencies: You correctly return 0 if the context doesn't exist. You might also enhance this by using a smoothing technique like Laplace smoothing to ensure that the probability doesn't become zero for unseen sequences:
Simplifying Unigram Logic: The check for n_used being 0 can probably be simplified, as you could just use the common logic for 1-grams without needing that specific branching since you can always map it to the right table.
Your final function efficiently calculates the most probable next character. A small formatting issue needs addressing:
Indentation: There is an indentation error at the beginning of your max_char and max_prob definitions. Ensure it aligns correctly with the function body.
Here’s an example of how it should look:
python
def predict_next_char(sequence, tables, vocabulary):
max_char = None
max_prob = float('-inf')
for char in vocabulary: # Iterate through vocabulary
prob = calculate_probability(sequence, char, tables)
if prob > max_prob:
max_prob = prob
max_char = char
return max_char # Return the character with the maximum probability
Summary of Changes
Improve the handling of edge cases in create_frequency_tables.
Consider using Laplace smoothing in calculate_probability.
Ensure correct indentation in predict_next_char.
Overall, your code is on the right track, and with these adjustments, it will be even better suited to meet the project requirements. Make sure to test the functions with various inputs and use cases to ensure robustness and correctness!
- **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.
"""
n = len(tables)
sequence_length = len(sequence)
# If the sequence is empty, we fall back to unigram probability
if sequence_length == 0:
return tables[0][char] / sum(tables[0].values())
# Determine which n-gram table to use
n_used = min(sequence_length, n) - 1 # n-1 for the context
last_n_gram = tuple(sequence[-n_used:]) + (char,)
if n_used == 0: # If no context, unigram case
return tables[0][char] / sum(tables[0].values())
# Check the frequency of the preceding context
context = tuple(sequence[-n_used:])
if tables[n_used][context] == 0:
return 0 # No context found (or smoothed)
# Calculate the probability using the frequency tables
return tables[n_used + 1][last_n_gram] / tables[n_used][context]
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.
"""
max_prob = 0
best_char = None
for char in vocabulary:
prob = calculate_probability(sequence, char, tables)
print(f"Char: {char}, Probability: {prob}")
if prob > max_prob:
max_prob = prob
best_char = char
print(f"Selected Char: {best_char}")
return best_char
from collections import defaultdict
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.
"""
# Initialize a list of frequency tables
tables = [defaultdict(int) for _ in range(n)]
# Clean the document and extract characters
document = document.replace("\n", " ").replace("\r", "").strip() # Basic cleaning
length = len(document)
# Loop through the document to gather frequencies
for i in range(length):
# Count unigrams
tables[0][document[i]] += 1
if i < length - 1: # Count bigrams
tables[1][(document[i], document[i + 1])] += 1
if i < length - 2: # Count trigrams
tables[2][(document[i], document[i + 1], document[i + 2])] += 1
# Extend for larger n values
for j in range(3, n):
if i < length - j + 1:
ngram = tuple(document[i:i + j])
tables[j][ngram] += 1
return tables
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.
"""
n = len(tables)
sequence_length = len(sequence)
# If the sequence is empty, we fall back to unigram probability
if sequence_length == 0:
return tables[0][char] / sum(tables[0].values()) # No need for a condition as this is just a fallback
# Determine which n-gram table to use
n_used = min(sequence_length, n) - 1 # n-1 for the context
last_n_gram = tuple(sequence[-n_used:]) + (char,)
# Check frequency of the preceding context
context = tuple(sequence[-n_used:])
# Handle the case of Laplace smoothing - adding 1 to frequency counts
if tables[n_used][context] == 0:
return 1 / (sum(tables[n_used].values()) + len(tables[n_used])) # Laplace smoothing
# Calculate the probability using the frequency tables
return (tables[n_used + 1][last_n_gram] + 1) / (tables[n_used][context] + len(tables[n_used])) # Laplace smoothing
def 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.
- **Returns**:
- Returns the character with the maximum probability as the predicted next character.
"""
max_prob = float('-inf') # Use negative infinity for comparison
best_char = None
for char in vocabulary:
prob = calculate_probability(sequence, char, tables)
# print(f"Char: {char}, Probability: {prob}") # Optional logging for diagnostics
if prob > max_prob:
max_prob = prob
best_char = char
return best_char
Key Changes and Features
Edge Case Handling: The code handles situations where the input sequence length is 0 directly.
Smoothing: Laplace smoothing is now included in the probability calculation, providing a non-zero probability for unseen characters. It prevents the probabilities from becoming zero when a character or context has not been observed.
Logging removed: The previous print statements within the predict_next_char function were removed to 'clean up' the function. You can add logging or debugging code as needed outside of this core functionality.
Inverted max_prob initialization: Using float('-inf') ensures that any valid probability will be greater.
With these changes, your code should function more robustly and effectively. Consider testing it with a variety of inputs to confirm it behaves as expected!
Enter the number of grams (n): 3
Enter an initial sequence: the
Enter the length of completion (k): 5
Updated sequence: theo
Updated sequence: theos
Updated sequence: theose
Updated sequence: theosel
Updated sequence: theosell
Issues and Improvements
Unexpected Characters: The character "ó" appearing in your output may indicate:
Input data not aligned with your set vocabulary.
Potential misconfiguration, or the presence of non-ASCII characters in your training data.
Be sure to check the corpus used for training the model or the defined vocabulary.
Input Validation: Consider adding validations to ensure that the input sequence and vocabulary are acceptable.
Flexibility and Usability: Enhancing user interaction to allow the user to stop early or provide new sequences can improve the usability of your program.
Summary
Ultimately, the expected output would depend on the trained n-gram model and its ability to predict based on the training data. If implemented correctly, your program should generate sequences realistically based on the vocabulary and prior input data without introducing unexpected characters. You might want to test with a clearly defined training set first to validate the system before deploying it with varied user inputs.
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.
"""
n = len(tables)
sequence_length = len(sequence)
# If the sequence is empty, we fall back to unigram probability
if sequence_length == 0:
return tables[0][char] / sum(tables[0].values()) # No need for a condition as this is just a fallback
# Determine which n-gram table to use
n_used = min(sequence_length, n) - 1 # n-1 for the context
last_n_gram = tuple(sequence[-n_used:]) + (char,)
# Check frequency of the preceding context
context = tuple(sequence[-n_used:])
# Handle the case of Laplace smoothing - adding 1 to frequency counts
if tables[n_used][context] == 0:
return 1 / (sum(tables[n_used].values()) + len(tables[n_used])) # Laplace smoothing
# Calculate the probability using the frequency tables
return (tables[n_used + 1][last_n_gram] + 1) / (tables[n_used][context] + len(tables[n_used])) # Laplace smoothing
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.
- **Returns**:
- Returns the character with the maximum probability as the predicted next character.
"""
max_prob = float('-inf') # Use negative infinity for comparison
best_char = None
for char in vocabulary:
prob = calculate_probability(sequence, char, tables)
# print(f"Char: {char}, Probability: {prob}") # Optional logging for diagnostics
if prob > max_prob:
max_prob = prob
best_char = char
return best_char
def calculate_probability(sequence, char, tables):
n = len(tables)
sequence_length = len(sequence)
# If the sequence is empty (fallback to unigram)
if sequence_length == 0:
return tables[0][char] / sum(tables[0].values())
n_used = min(sequence_length, n) - 1
context = tuple(sequence[-n_used:]) # Grabbing the last n_used characters
# Laplace smoothing applied during calculation
context_freq = tables[n_used][context] if n_used > 0 else sum(tables[0].values())
next_char_freq = tables[n_used + 1][tuple(sequence[-n_used:] + (char,))] if n_used + 1 < n else tables[0][char]
# Return the probability with Laplace smoothing
return (next_char_freq + 1) / (context_freq + len(tables[0])) # Use the size of the vocabulary for denominator
3. predict_next_char
Strengths:
Clear and efficient way to iterate through the vocabulary to find the maximum probability.
The printing statement for logging can be beneficial while debugging.
Suggestions:
Instead of using a variable called best_char, consider renaming it to max_char for consistency with max_prob, since both represent maximum values.
Final Version of the Code
Incorporating these suggestions and ensuring clarity and consistency, your final code should look something like:
python
from collections import defaultdict
def create_frequency_tables(document, n):
tables = [defaultdict(int) for _ in range(n)]
document = document.replace("\n", " ").replace("\r", "").strip()
length = len(document)
for i in range(length):
tables[0][document[i]] += 1
if i < length - 1:
tables[1][(document[i], document[i + 1])] += 1
if i < length - 2:
tables[2][(document[i], document[i + 1], document[i + 2])] += 1
for j in range(3, n):
if i < length - j + 1:
ngram = tuple(document[i:i + j])
tables[j][ngram] += 1
return tables
def calculate_probability(sequence, char, tables):
n = len(tables)
sequence_length = len(sequence)
if sequence_length == 0:
return tables[0][char] / sum(tables[0].values())
n_used = min(sequence_length, n) - 1
context = tuple(sequence[-n_used:])
context_freq = tables[n_used][context] if n_used > 0 else sum(tables[0].values())
next_char_freq = tables[n_used + 1][tuple(sequence[-n_used:] + (char,))] if n_used + 1 < n else tables[0][char]
return (next_char_freq + 1) / (context_freq + len(tables[0])) # Applying Laplace smoothing
def predict_next_char(sequence, tables, vocabulary):
max_prob = float('-inf')
max_char = None
for char in vocabulary:
prob = calculate_probability(sequence, char, tables)
if prob > max_prob:
max_prob = prob
max_char = char
return max_char
Summary
Your implementation is quite strong, and with these adjustments and clarifications, it will enhance both performance and maintainability. Be sure to test thoroughly with various inputs to validate the behavior and functionality of your n-gram autocomplete model. Good luck!
Returns
It indeed returns a probability value based on the criteria defined.
This implementation also meets the stated requirements effectively.
Functionality: Predicts the most likely next character based on the given sequence.
Parameters:
sequence: The input sequence used for prediction.
tables: List of frequency tables.
vocabulary: The set of potential characters for prediction.
Functionality:
Calculates the probability for each character in the vocabulary using calculate_probability().
Returns: The character with the maximum probability.
Evaluation:
Functionality:
The function loops through the vocabulary, calculating the probability for each character and identifying the one with the maximum probability correctly.
Parameters:
It appropriately takes sequence, tables, and vocabulary.
Returns:
Returns the character that has the maximum calculated probability.
Your implementation here also successfully follows the requirements.
Summary
Based on the provided requirements for the NgramAutocomplete.py file:
All three functions (create_frequency_tables, calculate_probability, predict_next_char) have been implemented according to the specifications given in your project.
Parameters are correctly defined and used as required.
Returns are aligned with the expected outcomes.
Recommendations for Further Improvement:
Documentation: Each function has docstrings, but for clarity, consider including examples in usage.
Error Handling: You might want to add error handling for unexpected input formats or types to make the functions more robust (e.g., empty documents or vocabulary).
Efficiency: Ensure to measure performance, especially for larger documents, to see if any optimizations are warranted.
Overall, your code appears to meet the requirements correctly. Great job!
Implementing Improvements
In order to achieve the desired behavior in your implementation, ensure that:
When updating the sequence, you call predict_next_char() for each and use the output to actually append to your current sequence correctly.
Finally, consider displaying how the entire completion process is modeled in your output for clarity.
Example Code Snippet for Interaction
Here’s a conceptual example of how your flow might look in the main loop:
python
# Given inputs n, initial_sequence, k
current_sequence = initial_sequence
for _ in range(k):
next_char = predict_next_char(current_sequence, tables, vocabulary)
current_sequence += next_char
print(f"Updated sequence: {current_sequence}")
This approach ensures that each iteration effectively builds on the predicted character, enhancing the interactive experience for the user and demonstrating the autocomplete functionality more clearly.
Completion Process:
Initializes current_sequence with the initial_sequence.
For each iteration up to k, it predicts the next character using predict_next_char, appends this character to current_sequence, and prints the updated sequence.
Vocabulary:
The vocabulary is hardcoded here as {'a', 'b', 'c', 'd'}. Adjust this as necessary to fit your actual language model's vocabulary.
How It Works
When executed, this script will prompt for user input.
It will display how the initial sequence gets extended iteratively based on predictions from the n-gram language model until the specified length has been reached.
Testing
Replace the placeholder text in the document variable with a realistic sample text or corpus that you've prepared for training your model.
After implementing and running this code, you should see a series of updated sequences reflecting the autocomplete functionality based on the provided initial sequence. Make sure to test it thoroughly to ensure accuracy and performance!
from collections import defaultdict
def create_frequency_tables(document, n):
"""
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.
"""
tables = [defaultdict(int) for _ in range(n)]
document = document.replace("\n", " ").replace("\r", "").strip()
length = len(document)
for i in range(length):
tables[0][document[i]] += 1
if i < length - 1:
tables[1][(document[i], document[i + 1])] += 1
if i < length - 2:
tables[2][(document[i], document[i + 1], document[i + 2])] += 1
for j in range(3, n):
if i < length - j + 1:
ngram = tuple(document[i:i + j])
tables[j][ngram] += 1
return tables
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.
"""
n = len(tables)
sequence_length = len(sequence)
if sequence_length == 0:
return tables[0][char] / sum(tables[0].values())
n_used = min(sequence_length, n) - 1
context = tuple(sequence[-n_used:])
context_freq = tables[n_used][context] if n_used > 0 else sum(tables[0].values())
next_char_freq = tables[n_used + 1][tuple(sequence[-n_used:] + (char,))] if n_used + 1 < n else tables[0][char]
return (next_char_freq + 1) / (context_freq + len(tables[0])) # Laplace smoothing
def 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.
Returns:
- Returns the character with the maximum probability as the predicted next character.
"""
max_prob = float('-inf')
max_char = None
for char in vocabulary:
prob = calculate_probability(sequence, char, tables)
if prob > max_prob:
max_prob = prob
max_char = char
return max_char
def main():
document = "Your large corpus of text goes here for training." # Replace with the actual text
n = int(input("Enter the number of grams (n): "))
# Create frequency tables based on the training document
tables = create_frequency_tables(document, n)
initial_sequence = input("Enter an initial sequence: ")
k = int(input("Enter the length of completion (k): "))
current_sequence = initial_sequence
for _ in range(k):
next_char = predict_next_char(current_sequence, tables, {'a', 'b', 'c', 'd'}) # Adjust vocabulary as needed
current_sequence += next_char
print(f"Updated sequence: {current_sequence}")
# Ensure to call main() if this script is executed directly
if __name__ == "__main__":
main()
Explanation of the Code Structure
create_frequency_tables: This function constructs n frequency tables from the input document and handles unigrams, bigrams, and higher n-grams.
calculate_probability: This function computes the probability of the next character based on the current sequence using the frequency tables.
predict_next_char: This function iterates through the vocabulary and returns the character that has the highest calculated probability given the sequence.
main() function:
Prompts the user for the number of grams (n), the initial sequence, and the desired completion length (k).
Builds frequency tables from the given document.
Iteratively predicts and appends the next character to the current sequence, displaying the updated sequence each time.
Execution Check: The if __name__ == "__main__": construct ensures that main() is executed when the script is run directly, making it suitable for command-line use.
Usage
Fill in the document variable with your own text corpus before running the script.
Save this code in a file named NgramAutocomplete.py and execute it to see how the autocomplete feature works based on your trained data.
from collections import defaultdict
def create_frequency_tables(document, n):
"""
Constructs a list of n frequency tables for an n-gram model.
Parameters:
- document: The text document used to train the model.
- n: The number of grams for the n-gram model.
Returns:
- A list of n frequency tables.
"""
tables = [defaultdict(int) for _ in range(n)]
document = document.replace("\n", " ").replace("\r", "").strip()
length = len(document)
for i in range(length):
tables[0][document[i]] += 1
if i < length - 1:
tables[1][(document[i], document[i + 1])] += 1
if i < length - 2:
tables[2][(document[i], document[i + 1], document[i + 2])] += 1
for j in range(3, n):
if i < length - j + 1:
ngram = tuple(document[i:i + j])
tables[j][ngram] += 1
return tables
def calculate_probability(sequence, char, tables):
"""
Calculates the probability of observing a given sequence using the frequency tables.
Parameters:
- sequence: The character sequence for which the probability is computed.
- tables: The frequency tables created by create_frequency_tables().
- char: The character whose probability follows the sequence.
Returns:
- The calculated probability.
"""
n = len(tables)
sequence_length = len(sequence)
if sequence_length == 0:
return tables[0][char] / sum(tables[0].values())
n_used = min(sequence_length, n) - 1
context = tuple(sequence[-n_used:])
context_freq = tables[n_used][context] if n_used > 0 else sum(tables[0].values())
next_char_freq = tables[n_used + 1][tuple(sequence[-n_used:] + (char,))] if n_used + 1 < n else tables[0][char]
return (next_char_freq + 1) / (context_freq + len(tables[0])) # Laplace smoothing
def predict_next_char(sequence, tables, vocabulary):
"""
Predicts the most likely next character based on the given sequence.
Parameters:
- sequence: The sequence used for prediction.
- tables: The frequency tables.
- vocabulary: The set of possible characters.
Returns:
- The character with the highest probability.
"""
max_prob = float('-inf')
max_char = None
for char in vocabulary:
prob = calculate_probability(sequence, char, tables)
if prob > max_prob:
max_prob = prob
max_char = char
return max_char
def main():
# Your large corpus of text goes here for training - use actual text for meaningful predictions
document = "the quick brown fox jumps over the lazy dog. the quick brown fox." # Example text
n = int(input("Enter the number of grams (n): "))
# Create frequency tables based on the training document
tables = create_frequency_tables(document, n)
initial_sequence = input("Enter an initial sequence: ")
k = int(input("Enter the length of completion (k): "))
current_sequence = initial_sequence
# Define the vocabulary based on the training document
vocabulary = set(document) # Create a vocabulary from the document itself
for _ in range(k):
next_char = predict_next_char(current_sequence, tables, vocabulary)
current_sequence += next_char
print(f"Updated sequence: {current_sequence}")
# Ensure to call main() if this script is executed directly
if __name__ == "__main__":
main()
Key Changes Made
Realistic Document: Replaced the placeholder text in the document variable with a small sample that includes a variety of characters. This allows the model to have actual context to predict from.
Dynamic Vocabulary: The vocabulary is now created dynamically from the document itself. This captures all characters that appear in the text, enhancing prediction accuracy.
Integration of Functions: The overall interaction remains; the program asks for user input and provides predictions step by step.
Testing the Changes
Run the script as before. It will prompt for the number of grams, the initial sequence, and the length of completion.
You should now see meaningful characters appended to your original input sequence, rather than just spaces.
Make sure the document you use is rich enough (with a variety of characters) to give a strong model for predictions.
Please test the script and confirm whether it now works as intended, providing meaningful predictions based on the input sequence. Let me know if you have further questions or adjustments!
There was nothing so very remarkable in that, nor did Alice think it so
very much out of the way to hear the Rabbit say to itself, "Oh dear! Oh
dear! I shall be too late!" But when the Rabbit actually took a watch
out of its waistcoat-pocket and looked at it and then hurried on, Alice
started to her feet, for it flashed across her mind that she had never
before seen a rabbit with either a waistcoat-pocket, or a watch to take
out of it, and, burning with curiosity, she ran across the field after
it and was just in time to see it pop down a large rabbit-hole, under
the hedge. In another moment, down went Alice after it!
[Illustration]
The rabbit-hole went straight on like a tunnel for some way and then
dipped suddenly down, so suddenly that Alice had not a moment to think
about stopping herself before she found herself falling down what seemed
to be a very deep well.
Either the well was very deep, or she fell very slowly, for she had
plenty of time, as she went down, to look about her. First, she tried to
make out what she was coming to, but it was too dark to see anything;
then she looked at the sides of the well and noticed that they were
filled with cupboards and book-shelves; here and there she saw maps and
pictures hung upon pegs. She took down a jar from one of the shelves as
she passed. It was labeled "ORANGE MARMALADE," but, to her great
disappointment, it was empty; she did not like to drop the jar, so
managed to put it into one of the cupboards as she fell past it.
Down, down, down! Would the fall never come to an end? There was nothing
else to do, so Alice soon began talking to herself. "Dinah'll miss me
very much to-night, I should think!" (Dinah was the cat.) "I hope
they'll remember her saucer of milk at tea-time. Dinah, my dear, I wish
you were down here with me!" Alice felt that she was dozing off, when
suddenly, thump! thump! down she came upon a heap of sticks and dry
leaves, and the fall was over.
Alice was not a bit hurt, and she jumped up in a moment. She looked up,
but it was all dark overhead; before her was another long passage and
the White Rabbit was still in sight, hurrying down it. There was not a
moment to be lost. Away went Alice like the wind and was just in time to
hear it say, as it turned a corner, "Oh, my ears and whiskers, how late
it's getting!" She was close behind it when she turned the corner, but
the Rabbit was no longer to be seen.
She found herself in a long, low hall, which was lit up by a row of
lamps hanging from the roof. There were doors all 'round the hall, but
they were all locked; and when Alice had been all the way down one side
and up the other, trying every door, she walked sadly down the middle,
wondering how she was ever to get out again.
Suddenly she came upon a little table, all made of solid glass. There
was nothing on it but a tiny golden key, and Alice's first idea was that
this might belong to one of the doors of the hall; but, alas! either the
locks were too large, or the key was too small, but, at any rate, it
would not open any of them. However, on the second time 'round, she came
upon a low curtain she had not noticed before, and behind it was a
little door about fifteen inches high. She tried the little golden key
in the lock, and to her great delight, it fitted!
[Illustration]
Alice opened the door and found that it led into a small passage, not
much larger than a rat-hole; she knelt down and looked along the passage
into the loveliest garden you ever saw. How she longed to get out of
that dark hall and wander about among those beds of bright flowers and
those cool fountains, but she could not even get her head through the
doorway. "Oh," said Alice, "how I wish I could shut up like a telescope!
I think I could, if I only knew how to begin."
Alice went back to the table, half hoping she might find another key on
it, or at any rate, a book of rules for shutting people up like
telescopes. This time she found a little bottle on it ("which certainly
was not here before," said Alice), and tied 'round the neck of the
bottle was a paper label, with the words "DRINK ME" beautifully printed
on it in large letters.
"No, I'll look first," she said, "and see whether it's marked 'poison'
or not," for she had never forgotten that, if you drink from a bottle
marked "poison," it is almost certain to disagree with you, sooner or
later. However, this bottle was not marked "poison," so Alice ventured
to taste it, and, finding it very nice (it had a sort of mixed flavor of
cherry-tart, custard, pineapple, roast turkey, toffy and hot buttered
toast), she very soon finished it off.
code
* * * * *
"What a curious feeling!" said Alice. "I must be shutting up like a
telescope!"
And so it was indeed! She was now only ten inches high, and her face
brightened up at the thought that she was now the right size for going
through the little door into that lovely garden.
After awhile, finding that nothing more happened, she decided on going
into the garden at once; but, alas for poor Alice! When she got to the
door, she found she had forgotten the little golden key, and when she
went back to the table for it, she found she could not possibly reach
it: she could see it quite plainly through the glass and she tried her
best to climb up one of the legs of the table, but it was too slippery,
and when she had tired herself out with trying, the poor little thing
sat down and cried.
"Come, there's no use in crying like that!" said Alice to herself rather
sharply. "I advise you to leave off this minute!" She generally gave
herself very good advice (though she very seldom followed it), and
sometimes she scolded herself so severely as to bring tears into her
eyes.
Soon her eye fell on a little glass box that was lying under the table:
she opened it and found in it a very small cake, on which the words "EAT
ME" were beautifully marked in currants. "Well, I'll eat it," said
Alice, "and if it makes me grow larger, I can reach the key; and if it
makes me grow smaller, I can creep under the door: so either way I'll
get into the garden, and I don't care which happens!"
She ate a little bit and said anxiously to herself, "Which way? Which
way?" holding her hand on the top of her head to feel which way she was
growing; and she was quite surprised to find that she remained the same
size. So she set to work and very soon finished off the cake.
[Illustration]
II--THE POOL OF TEARS
"Curiouser and curiouser!" cried Alice (she was so much surprised that
for the moment she quite forgot how to speak good English). "Now I'm
opening out like the largest telescope that ever was! Good-by, feet! Oh,
my poor little feet, I wonder who will put on your shoes and stockings
for you now, dears? I shall be a great deal too far off to trouble
myself about you."
Just at this moment her head struck against the roof of the hall; in
fact, she was now rather more than nine feet high, and she at once took
up the little golden key and hurried off to the garden door.
Poor Alice! It was as much as she could do, lying down on one side, to
look through into the garden with one eye; but to get through was more
hopeless than ever. She sat down and began to cry again.
She went on shedding gallons of tears, until there was a large pool all
'round her and reaching half down the hall.
After a time, she heard a little pattering of feet in the distance and
she hastily dried her eyes to see what was coming. It was the White
Rabbit returning, splendidly dressed, with a pair of white kid-gloves in
one hand and a large fan in the other. He came trotting along in a
great hurry, muttering to himself, "Oh! the Duchess, the Duchess! Oh!
won't she be savage if I've kept her waiting!"
When the Rabbit came near her, Alice began, in a low, timid voice, "If
you please, sir--" The Rabbit started violently, dropped the white
kid-gloves and the fan and skurried away into the darkness as hard as he
could go.
[Illustration]
Alice took up the fan and gloves and she kept fanning herself all the
time she went on talking. "Dear, dear! How queer everything is to-day!
And yesterday things went on just as usual. Was I the same when I got
up this morning? But if I'm not the same, the next question is, 'Who in
the world am I?' Ah, that's the great puzzle!"
As she said this, she looked down at her hands and was surprised to see
that she had put on one of the Rabbit's little white kid-gloves while
she was talking. "How can I have done that?" she thought. "I must be
growing small again." She got up and went to the table to measure
herself by it and found that she was now about two feet high and was
going on shrinking rapidly. She soon found out that the cause of this
was the fan she was holding and she dropped it hastily, just in time to
save herself from shrinking away altogether.
"That was a narrow escape!" said Alice, a good deal frightened at the
sudden change, but very glad to find herself still in existence. "And
now for the garden!" And she ran with all speed back to the little door;
but, alas! the little door was shut again and the little golden key was
lying on the glass table as before. "Things are worse than ever,"
thought the poor child, "for I never was so small as this before,
never!"
As she said these words, her foot slipped, and in another moment,
splash! she was up to her chin in salt-water. Her first idea was that
she had somehow fallen into the sea. However, she soon made out that she
was in the pool of tears which she had wept when she was nine feet high.
[Illustration]
Just then she heard something splashing about in the pool a little way
off, and she swam nearer to see what it was: she soon made out that it
was only a mouse that had slipped in like herself.
"Would it be of any use, now," thought Alice, "to speak to this mouse?
Everything is so out-of-the-way down here that I should think very
likely it can talk; at any rate, there's no harm in trying." So she
began, "O Mouse, do you know the way out of this pool? I am very tired
of swimming about here, O Mouse!" The Mouse looked at her rather
inquisitively and seemed to her to wink with one of its little eyes, but
it said nothing.
"Perhaps it doesn't understand English," thought Alice. "I dare say it's
a French mouse, come over with William the Conqueror." So she began
again: "Où est ma chatte?" which was the first sentence in her French
lesson-book. The Mouse gave a sudden leap out of the water and seemed to
quiver all over with fright. "Oh, I beg your pardon!" cried Alice
hastily, afraid that she had hurt the poor animal's feelings. "I quite
forgot you didn't like cats."
"Not like cats!" cried the Mouse in a shrill, passionate voice. "Would
you like cats, if you were me?"
"Well, perhaps not," said Alice in a soothing tone; "don't be angry
about it. And yet I wish I could show you our cat Dinah. I think you'd
take a fancy to cats, if you could only see her. She is such a dear,
quiet thing." The Mouse was bristling all over and she felt certain it
must be really offended. "We won't talk about her any more, if you'd
rather not."
"We, indeed!" cried the Mouse, who was trembling down to the end of its
tail. "As if I would talk on such a subject! Our family always hated
cats--nasty, low, vulgar things! Don't let me hear the name again!"
[Illustration: Alice at the Mad Tea Party.]
"I won't indeed!" said Alice, in a great hurry to change the subject of
conversation. "Are you--are you fond--of--of dogs? There is such a nice
little dog near our house, I should like to show you! It kills all the
rats and--oh, dear!" cried Alice in a sorrowful tone. "I'm afraid I've
offended it again!" For the Mouse was swimming away from her as hard as
it could go, and making quite a commotion in the pool as it went.
So she called softly after it, "Mouse dear! Do come back again, and we
won't talk about cats, or dogs either, if you don't like them!" When the
Mouse heard this, it turned 'round and swam slowly back to her; its face
was quite pale, and it said, in a low, trembling voice, "Let us get to
the shore and then I'll tell you my history and you'll understand why it
is I hate cats and dogs."
It was high time to go, for the pool was getting quite crowded with the
birds and animals that had fallen into it; there were a Duck and a Dodo,
a Lory and an Eaglet, and several other curious creatures. Alice led the
way and the whole party swam to the shore.
[Illustration]
III--A CAUCUS-RACE AND A LONG TALE
They were indeed a queer-looking party that assembled on the bank--the
birds with draggled feathers, the animals with their fur clinging close
to them, and all dripping wet, cross and uncomfortable.
[Illustration]
The first question, of course, was how to get dry again. They had a
consultation about this and after a few minutes, it seemed quite natural
to Alice to find herself talking familiarly with them, as if she had
known them all her life.
At last the Mouse, who seemed to be a person of some authority among
them, called out, "Sit down, all of you, and listen to me! I'll soon
make you dry enough!" They all sat down at once, in a large ring, with
the Mouse in the middle.
"Ahem!" said the Mouse with an important air. "Are you all ready? This
is the driest thing I know. Silence all 'round, if you please! 'William
the Conqueror, whose cause was favored by the pope, was soon submitted
to by the English, who wanted leaders, and had been of late much
accustomed to usurpation and conquest. Edwin and Morcar, the Earls of
Mercia and Northumbria'--"
"Ugh!" said the Lory, with a shiver.
"--'And even Stigand, the patriotic archbishop of Canterbury, found it
advisable'--"
"Found what?" said the Duck.
"Found it," the Mouse replied rather crossly; "of course, you know
what 'it' means."
"I know what 'it' means well enough, when I find a thing," said the
Duck; "it's generally a frog or a worm. The question is, what did the
archbishop find?"
The Mouse did not notice this question, but hurriedly went on, "'--found
it advisable to go with Edgar Atheling to meet William and offer him the
crown.'--How are you getting on now, my dear?" it continued, turning to
Alice as it spoke.
"As wet as ever," said Alice in a melancholy tone; "it doesn't seem to
dry me at all."
"In that case," said the Dodo solemnly, rising to its feet, "I move that
the meeting adjourn, for the immediate adoption of more energetic
remedies--"
"Speak English!" said the Eaglet. "I don't know the meaning of half
those long words, and, what's more, I don't believe you do either!"
"What I was going to say," said the Dodo in an offended tone, "is that
the best thing to get us dry would be a Caucus-race."
"What is a Caucus-race?" said Alice.
[Illustration]
"Why," said the Dodo, "the best way to explain it is to do it." First it
marked out a race-course, in a sort of circle, and then all the party
were placed along the course, here and there. There was no "One, two,
three and away!" but they began running when they liked and left off
when they liked, so that it was not easy to know when the race was over.
However, when they had been running half an hour or so and were quite
dry again, the Dodo suddenly called out, "The race is over!" and they
all crowded 'round it, panting and asking, "But who has won?"
This question the Dodo could not answer without a great deal of thought.
At last it said, "Everybody has won, and all must have prizes."
"But who is to give the prizes?" quite a chorus of voices asked.
"Why, she, of course," said the Dodo, pointing to Alice with one
finger; and the whole party at once crowded 'round her, calling out, in
a confused way, "Prizes! Prizes!"
Alice had no idea what to do, and in despair she put her hand into her
pocket and pulled out a box of comfits (luckily the salt-water had not
got into it) and handed them 'round as prizes. There was exactly one
a-piece, all 'round.
The next thing was to eat the comfits; this caused some noise and
confusion, as the large birds complained that they could not taste
theirs, and the small ones choked and had to be patted on the back.
However, it was over at last and they sat down again in a ring and
begged the Mouse to tell them something more.
"You promised to tell me your history, you know," said Alice, "and why
it is you hate--C and D," she added in a whisper, half afraid that it
would be offended again.
"Mine is a long and a sad tale!" said the Mouse, turning to Alice and
sighing.
"It is a long tail, certainly," said Alice, looking down with wonder
at the Mouse's tail, "but why do you call it sad?" And she kept on
puzzling about it while the Mouse was speaking, so that her idea of the
tale was something like this:--
code
"Fury said to
a mouse, That
he met in the
house, 'Let
us both go
to law: _I_
will prosecute
_you_.--
Come, I'll
take no denial:
We
must have
the trial;
For really
this morning
I've
nothing
to do.'
Said the
mouse to
the cur,
'Such a
trial, dear
sir, With
no jury
or judge,
would
be wasting
our
breath.'
'I'll be
judge,
I'll be
jury,'
said
cunning
old
Fury;
'I'll
try
the
whole
cause,
and
condemn
you to
death.'"
"You are not attending!" said the Mouse to Alice, severely. "What are
you thinking of?"
"I beg your pardon," said Alice very humbly, "you had got to the fifth
bend, I think?"
"You insult me by talking such nonsense!" said the Mouse, getting up and
walking away.
"Please come back and finish your story!" Alice called after it. And the
others all joined in chorus, "Yes, please do!" But the Mouse only shook
its head impatiently and walked a little quicker.
"I wish I had Dinah, our cat, here!" said Alice. This caused a
remarkable sensation among the party. Some of the birds hurried off at
once, and a Canary called out in a trembling voice, to its children,
"Come away, my dears! It's high time you were all in bed!" On various
pretexts they all moved off and Alice was soon left alone.
"I wish I hadn't mentioned Dinah! Nobody seems to like her down here and
I'm sure she's the best cat in the world!" Poor Alice began to cry
again, for she felt very lonely and low-spirited. In a little while,
however, she again heard a little pattering of footsteps in the distance
and she looked up eagerly.
[Illustration]
[Illustration]
IV--THE RABBIT SENDS IN A LITTLE BILL
It was the White Rabbit, trotting slowly back again and looking
anxiously about as it went, as if it had lost something; Alice heard it
muttering to itself, "The Duchess! The Duchess! Oh, my dear paws! Oh, my
fur and whiskers! She'll get me executed, as sure as ferrets are
ferrets! Where can I have dropped them, I wonder?" Alice guessed in a
moment that it was looking for the fan and the pair of white kid-gloves
and she very good-naturedly began hunting about for them, but they were
nowhere to be seen--everything seemed to have changed since her swim in
the pool, and the great hall, with the glass table and the little door,
had vanished completely.
Very soon the Rabbit noticed Alice, and called to her, in an angry tone,
"Why, Mary Ann, what are you doing out here? Run home this moment and
fetch me a pair of gloves and a fan! Quick, now!"
"He took me for his housemaid!" said Alice, as she ran off. "How
surprised he'll be when he finds out who I am!" As she said this, she
came upon a neat little house, on the door of which was a bright brass
plate with the name "W. RABBIT" engraved upon it. She went in without
knocking and hurried upstairs, in great fear lest she should meet the
real Mary Ann and be turned out of the house before she had found the
fan and gloves.
By this time, Alice had found her way into a tidy little room with a
table in the window, and on it a fan and two or three pairs of tiny
white kid-gloves; she took up the fan and a pair of the gloves and was
just going to leave the room, when her eyes fell upon a little bottle
that stood near the looking-glass. She uncorked it and put it to her
lips, saying to herself, "I do hope it'll make me grow large again, for,
really, I'm quite tired of being such a tiny little thing!"
Before she had drunk half the bottle, she found her head pressing
against the ceiling, and had to stoop to save her neck from being
broken. She hastily put down the bottle, remarking, "That's quite
enough--I hope I sha'n't grow any more."
Alas! It was too late to wish that! She went on growing and growing and
very soon she had to kneel down on the floor. Still she went on growing,
and, as a last resource, she put one arm out of the window and one foot
up the chimney, and said to herself, "Now I can do no more, whatever
happens. What will become of me?"
[Illustration]
Luckily for Alice, the little magic bottle had now had its full effect
and she grew no larger. After a few minutes she heard a voice outside
and stopped to listen.
"Mary Ann! Mary Ann!" said the voice. "Fetch me my gloves this moment!"
Then came a little pattering of feet on the stairs. Alice knew it was
the Rabbit coming to look for her and she trembled till she shook the
house, quite forgetting that she was now about a thousand times as large
as the Rabbit and had no reason to be afraid of it.
Presently the Rabbit came up to the door and tried to open it; but as
the door opened inwards and Alice's elbow was pressed hard against it,
that attempt proved a failure. Alice heard it say to itself, "Then I'll
go 'round and get in at the window."
"That you won't!" thought Alice; and after waiting till she fancied
she heard the Rabbit just under the window, she suddenly spread out her
hand and made a snatch in the air. She did not get hold of anything,
but she heard a little shriek and a fall and a crash of broken glass,
from which she concluded that it was just possible it had fallen into a
cucumber-frame or something of that sort.
Next came an angry voice--the Rabbit's--"Pat! Pat! Where are you?" And
then a voice she had never heard before, "Sure then, I'm here! Digging
for apples, yer honor!"
"Here! Come and help me out of this! Now tell me, Pat, what's that in
the window?"
"Sure, it's an arm, yer honor!"
"Well, it's got no business there, at any rate; go and take it away!"
There was a long silence after this and Alice could only hear whispers
now and then, and at last she spread out her hand again and made another
snatch in the air. This time there were two little shrieks and more
sounds of broken glass. "I wonder what they'll do next!" thought Alice.
"As for pulling me out of the window, I only wish they could!"
She waited for some time without hearing anything more. At last came a
rumbling of little cart-wheels and the sound of a good many voices all
talking together. She made out the words: "Where's the other ladder?
Bill's got the other--Bill! Here, Bill! Will the roof bear?--Who's to go
down the chimney?--Nay, I sha'n't! You do it! Here, Bill! The master
says you've got to go down the chimney!"
Alice drew her foot as far down the chimney as she could and waited till
she heard a little animal scratching and scrambling about in the chimney
close above her; then she gave one sharp kick and waited to see what
would happen next.
The first thing she heard was a general chorus of "There goes Bill!"
then the Rabbit's voice alone--"Catch him, you by the hedge!" Then
silence and then another confusion of voices--"Hold up his head--Brandy
now--Don't choke him--What happened to you?"
Last came a little feeble, squeaking voice, "Well, I hardly know--No
more, thank ye. I'm better now--all I know is, something comes at me
like a Jack-in-the-box and up I goes like a sky-rocket!"
After a minute or two of silence, they began moving about again, and
Alice heard the Rabbit say, "A barrowful will do, to begin with."
"A barrowful of what?" thought Alice. But she had not long to doubt,
for the next moment a shower of little pebbles came rattling in at the
window and some of them hit her in the face. Alice noticed, with some
surprise, that the pebbles were all turning into little cakes as they
lay on the floor and a bright idea came into her head. "If I eat one of
these cakes," she thought, "it's sure to make some change in my size."
So she swallowed one of the cakes and was delighted to find that she
began shrinking directly. As soon as she was small enough to get through
the door, she ran out of the house and found quite a crowd of little
animals and birds waiting outside. They all made a rush at Alice the
moment she appeared, but she ran off as hard as she could and soon found
herself safe in a thick wood.
[Illustration: "The Duchess tucked her arm affectionately into
Alice's."]
"The first thing I've got to do," said Alice to herself, as she
wandered about in the wood, "is to grow to my right size again; and the
second thing is to find my way into that lovely garden. I suppose I
ought to eat or drink something or other, but the great question is
'What?'"
Alice looked all around her at the flowers and the blades of grass, but
she could not see anything that looked like the right thing to eat or
drink under the circumstances. There was a large mushroom growing near
her, about the same height as herself. She stretched herself up on
tiptoe and peeped over the edge and her eyes immediately met those of a
large blue caterpillar, that was sitting on the top, with its arms
folded, quietly smoking a long hookah and taking not the smallest notice
of her or of anything else.
[Illustration]
V--ADVICE FROM A CATERPILLAR
At last the Caterpillar took the hookah out of its mouth and addressed
Alice in a languid, sleepy voice.
"Who are you?" said the Caterpillar.
[Illustration]
Alice replied, rather shyly, "I--I hardly know, sir, just at present--at
least I know who I was when I got up this morning, but I think I must
have changed several times since then."
"What do you mean by that?" said the Caterpillar, sternly. "Explain
yourself!"
"I can't explain myself, I'm afraid, sir," said Alice, "because I'm
not myself, you see--being so many different sizes in a day is very
confusing." She drew herself up and said very gravely, "I think you
ought to tell me who you are, first."
"Why?" said the Caterpillar.
As Alice could not think of any good reason and the Caterpillar seemed
to be in a very unpleasant state of mind, she turned away.
"Come back!" the Caterpillar called after her. "I've something important
to say!" Alice turned and came back again.
"Keep your temper," said the Caterpillar.
"Is that all?" said Alice, swallowing down her anger as well as she
could.
"No," said the Caterpillar.
It unfolded its arms, took the hookah out of its mouth again, and said,
"So you think you're changed, do you?"
"I'm afraid, I am, sir," said Alice. "I can't remember things as I
used--and I don't keep the same size for ten minutes together!"
"What size do you want to be?" asked the Caterpillar.
"Oh, I'm not particular as to size," Alice hastily replied, "only one
doesn't like changing so often, you know. I should like to be a little
larger, sir, if you wouldn't mind," said Alice. "Three inches is such a
wretched height to be."
"It is a very good height indeed!" said the Caterpillar angrily, rearing
itself upright as it spoke (it was exactly three inches high).
In a minute or two, the Caterpillar got down off the mushroom and
crawled away into the grass, merely remarking, as it went, "One side
will make you grow taller, and the other side will make you grow
shorter."
"One side of what? The other side of what?" thought Alice to
herself.
"Of the mushroom," said the Caterpillar, just as if she had asked it
aloud; and in another moment, it was out of sight.
Alice remained looking thoughtfully at the mushroom for a minute, trying
to make out which were the two sides of it. At last she stretched her
arms 'round it as far as they would go, and broke off a bit of the edge
with each hand.
"And now which is which?" she said to herself, and nibbled a little of
the right-hand bit to try the effect. The next moment she felt a violent
blow underneath her chin--it had struck her foot!
She was a good deal frightened by this very sudden change, as she was
shrinking rapidly; so she set to work at once to eat some of the other
bit. Her chin was pressed so closely against her foot that there was
hardly room to open her mouth; but she did it at last and managed to
swallow a morsel of the left-hand bit....
"Come, my head's free at last!" said Alice; but all she could see, when
she looked down, was an immense length of neck, which seemed to rise
like a stalk out of a sea of green leaves that lay far below her.
"Where have my shoulders got to? And oh, my poor hands, how is it I
can't see you?" She was delighted to find that her neck would bend
about easily in any direction, like a serpent. She had just succeeded in
curving it down into a graceful zigzag and was going to dive in among
the leaves, when a sharp hiss made her draw back in a hurry--a large
pigeon had flown into her face and was beating her violently with its
wings.
[Illustration]
"Serpent!" cried the Pigeon.
"I'm not a serpent!" said Alice indignantly. "Let me alone!"
"I've tried the roots of trees, and I've tried banks, and I've tried
hedges," the Pigeon went on, "but those serpents! There's no pleasing
them!"
Alice was more and more puzzled.
"As if it wasn't trouble enough hatching the eggs," said the Pigeon,
"but I must be on the look-out for serpents, night and day! And just as
I'd taken the highest tree in the wood," continued the Pigeon, raising
its voice to a shriek, "and just as I was thinking I should be free of
them at last, they must needs come wriggling down from the sky! Ugh,
Serpent!"
"But I'm not a serpent, I tell you!" said Alice. "I'm a--I'm a--I'm a
little girl," she added rather doubtfully, as she remembered the number
of changes she had gone through that day.
"You're looking for eggs, I know that well enough," said the Pigeon;
"and what does it matter to me whether you're a little girl or a
serpent?"
"It matters a good deal to me," said Alice hastily; "but I'm not
looking for eggs, as it happens, and if I was, I shouldn't want
yours--I don't like them raw."
"Well, be off, then!" said the Pigeon in a sulky tone, as it settled
down again into its nest. Alice crouched down among the trees as well as
she could, for her neck kept getting entangled among the branches, and
every now and then she had to stop and untwist it. After awhile she
remembered that she still held the pieces of mushroom in her hands, and
she set to work very carefully, nibbling first at one and then at the
other, and growing sometimes taller and sometimes shorter, until she had
succeeded in bringing herself down to her usual height.
It was so long since she had been anything near the right size that it
felt quite strange at first. "The next thing is to get into that
beautiful garden--how is that to be done, I wonder?" As she said this,
she came suddenly upon an open place, with a little house in it about
four feet high. "Whoever lives there," thought Alice, "it'll never do to
come upon them this size; why, I should frighten them out of their
wits!" She did not venture to go near the house till she had brought
herself down to nine inches high.
VI--PIG AND PEPPER
For a minute or two she stood looking at the house, when suddenly a
footman in livery came running out of the wood (judging by his face
only, she would have called him a fish)--and rapped loudly at the door
with his knuckles. It was opened by another footman in livery, with a
round face and large eyes like a frog.
[Illustration]
The Fish-Footman began by producing from under his arm a great letter,
and this he handed over to the other, saying, in a solemn tone, "For the
Duchess. An invitation from the Queen to play croquet." The
Frog-Footman repeated, in the same solemn tone, "From the Queen. An
invitation for the Duchess to play croquet." Then they both bowed low
and their curls got entangled together.
When Alice next peeped out, the Fish-Footman was gone, and the other was
sitting on the ground near the door, staring stupidly up into the sky.
Alice went timidly up to the door and knocked.
"There's no sort of use in knocking," said the Footman, "and that for
two reasons. First, because I'm on the same side of the door as you are;
secondly, because they're making such a noise inside, no one could
possibly hear you." And certainly there was a most extraordinary noise
going on within--a constant howling and sneezing, and every now and then
a great crash, as if a dish or kettle had been broken to pieces.
"How am I to get in?" asked Alice.
"Are you to get in at all?" said the Footman. "That's the first
question, you know."
Alice opened the door and went in. The door led right into a large
kitchen, which was full of smoke from one end to the other; the Duchess
was sitting on a three-legged stool in the middle, nursing a baby; the
cook was leaning over the fire, stirring a large caldron which seemed to
be full of soup.
"There's certainly too much pepper in that soup!" Alice said to herself,
as well as she could for sneezing. Even the Duchess sneezed
occasionally; and as for the baby, it was sneezing and howling
alternately without a moment's pause. The only two creatures in the
kitchen that did not sneeze were the cook and a large cat, which was
grinning from ear to ear.
"Please would you tell me," said Alice, a little timidly, "why your cat
grins like that?"
"It's a Cheshire-Cat," said the Duchess, "and that's why."
"I didn't know that Cheshire-Cats always grinned; in fact, I didn't know
that cats could grin," said Alice.
"You don't know much," said the Duchess, "and that's a fact."
Just then the cook took the caldron of soup off the fire, and at once
set to work throwing everything within her reach at the Duchess and the
baby--the fire-irons came first; then followed a shower of saucepans,
plates and dishes. The Duchess took no notice of them, even when they
hit her, and the baby was howling so much already that it was quite
impossible to say whether the blows hurt it or not.
"Oh, please mind what you're doing!" cried Alice, jumping up and down
in an agony of terror.
"Here! You may nurse it a bit, if you like!" the Duchess said to Alice,
flinging the baby at her as she spoke. "I must go and get ready to play
croquet with the Queen," and she hurried out of the room.
Alice caught the baby with some difficulty, as it was a queer-shaped
little creature and held out its arms and legs in all directions. "If I
don't take this child away with me," thought Alice, "they're sure to
kill it in a day or two. Wouldn't it be murder to leave it behind?" She
said the last words out loud and the little thing grunted in reply.
"If you're going to turn into a pig, my dear," said Alice, "I'll have
nothing more to do with you. Mind now!"
Alice was just beginning to think to herself, "Now, what am I to do with
this creature, when I get it home?" when it grunted again so violently
that Alice looked down into its face in some alarm. This time there
could be no mistake about it--it was neither more nor less than a pig;
so she set the little creature down and felt quite relieved to see it
trot away quietly into the wood.
Alice was a little startled by seeing the Cheshire-Cat sitting on a
bough of a tree a few yards off. The Cat only grinned when it saw her.
"Cheshire-Puss," began Alice, rather timidly, "would you please tell me
which way I ought to go from here?"
"In that direction," the Cat said, waving the right paw 'round, "lives
a Hatter; and in that direction," waving the other paw, "lives a March
Hare. Visit either you like; they're both mad."
"But I don't want to go among mad people," Alice remarked.
"Oh, you can't help that," said the Cat; "we're all mad here. Do you
play croquet with the Queen to-day?"
"I should like it very much," said Alice, "but I haven't been invited
yet."
"You'll see me there," said the Cat, and vanished.
Alice had not gone much farther before she came in sight of the house of
the March Hare; it was so large a house that she did not like to go near
till she had nibbled some more of the left-hand bit of mushroom.
VII--A MAD TEA-PARTY
There was a table set out under a tree in front of the house, and the
March Hare and the Hatter were having tea at it; a Dormouse was sitting
between them, fast asleep.
The table was a large one, but the three were all crowded together at
one corner of it. "No room! No room!" they cried out when they saw Alice
coming. "There's plenty of room!" said Alice indignantly, and she sat
down in a large arm-chair at one end of the table.
The Hatter opened his eyes very wide on hearing this, but all he said
was "Why is a raven like a writing-desk?"
"I'm glad they've begun asking riddles--I believe I can guess that," she
added aloud.
"Do you mean that you think you can find out the answer to it?" said the
March Hare.
"Exactly so," said Alice.
"Then you should say what you mean," the March Hare went on.
"I do," Alice hastily replied; "at least--at least I mean what I
say--that's the same thing, you know."
"You might just as well say," added the Dormouse, which seemed to be
talking in its sleep, "that 'I breathe when I sleep' is the same thing
as 'I sleep when I breathe!'"
"It is the same thing with you," said the Hatter, and he poured a
little hot tea upon its nose. The Dormouse shook its head impatiently
and said, without opening its eyes, "Of course, of course; just what I
was going to remark myself."
[Illustration]
"Have you guessed the riddle yet?" the Hatter said, turning to Alice
again.
"No, I give it up," Alice replied. "What's the answer?"
"I haven't the slightest idea," said the Hatter.
"Nor I," said the March Hare.
Alice gave a weary sigh. "I think you might do something better with the
time," she said, "than wasting it in asking riddles that have no
answers."
"Take some more tea," the March Hare said to Alice, very earnestly.
"I've had nothing yet," Alice replied in an offended tone, "so I can't
take more."
"You mean you can't take less," said the Hatter; "it's very easy to
take more than nothing."
At this, Alice got up and walked off. The Dormouse fell asleep instantly
and neither of the others took the least notice of her going, though she
looked back once or twice; the last time she saw them, they were
trying to put the Dormouse into the tea-pot.
[Illustration: The Trial of the Knave of Hearts.]
"At any rate, I'll never go there again!" said Alice, as she picked
her way through the wood. "It's the stupidest tea-party I ever was at in
all my life!" Just as she said this, she noticed that one of the trees
had a door leading right into it. "That's very curious!" she thought. "I
think I may as well go in at once." And in she went.
Once more she found herself in the long hall and close to the little
glass table. Taking the little golden key, she unlocked the door that
led into the garden. Then she set to work nibbling at the mushroom (she
had kept a piece of it in her pocket) till she was about a foot high;
then she walked down the little passage; and then--she found herself
at last in the beautiful garden, among the bright flower-beds and the
cool fountains.
VIII--THE QUEEN'S CROQUET GROUND
A large rose-tree stood near the entrance of the garden; the roses
growing on it were white, but there were three gardeners at it, busily
painting them red. Suddenly their eyes chanced to fall upon Alice, as
she stood watching them. "Would you tell me, please," said Alice, a
little timidly, "why you are painting those roses?"
Five and Seven said nothing, but looked at Two. Two began, in a low
voice, "Why, the fact is, you see, Miss, this here ought to have been a
red rose-tree, and we put a white one in by mistake; and, if the Queen
was to find it out, we should all have our heads cut off, you know. So
you see, Miss, we're doing our best, afore she comes, to--" At this
moment, Five, who had been anxiously looking across the garden, called
out, "The Queen! The Queen!" and the three gardeners instantly threw
themselves flat upon their faces. There was a sound of many footsteps
and Alice looked 'round, eager to see the Queen.
First came ten soldiers carrying clubs, with their hands and feet at the
corners: next the ten courtiers; these were ornamented all over with
diamonds. After these came the royal children; there were ten of them,
all ornamented with hearts. Next came the guests, mostly Kings and
Queens, and among them Alice recognized the White Rabbit. Then followed
the Knave of Hearts, carrying the King's crown on a crimson velvet
cushion; and last of all this grand procession came THE KING AND THE
QUEEN OF HEARTS.
When the procession came opposite to Alice, they all stopped and looked
at her, and the Queen said severely, "Who is this?" She said it to the
Knave of Hearts, who only bowed and smiled in reply.
"My name is Alice, so please Your Majesty," said Alice very politely;
but she added to herself, "Why, they're only a pack of cards, after
all!"
"Can you play croquet?" shouted the Queen. The question was evidently
meant for Alice.
"Yes!" said Alice loudly.
"Come on, then!" roared the Queen.
"It's--it's a very fine day!" said a timid voice to Alice. She was
walking by the White Rabbit, who was peeping anxiously into her face.
"Very," said Alice. "Where's the Duchess?"
"Hush! Hush!" said the Rabbit. "She's under sentence of execution."
"What for?" said Alice.
"She boxed the Queen's ears--" the Rabbit began.
"Get to your places!" shouted the Queen in a voice of thunder, and
people began running about in all directions, tumbling up against each
other. However, they got settled down in a minute or two, and the game
began.
Alice thought she had never seen such a curious croquet-ground in her
life; it was all ridges and furrows. The croquet balls were live
hedgehogs, and the mallets live flamingos and the soldiers had to double
themselves up and stand on their hands and feet, to make the arches.
The players all played at once, without waiting for turns, quarrelling
all the while and fighting for the hedgehogs; and in a very short time,
the Queen was in a furious passion and went stamping about and shouting,
"Off with his head!" or "Off with her head!" about once in a minute.
"They're dreadfully fond of beheading people here," thought Alice; "the
great wonder is that there's anyone left alive!"
She was looking about for some way of escape, when she noticed a curious
appearance in the air. "It's the Cheshire-Cat," she said to herself;
"now I shall have somebody to talk to."
"How are you getting on?" said the Cat.
"I don't think they play at all fairly," Alice said, in a rather
complaining tone; "and they all quarrel so dreadfully one can't hear
oneself speak--and they don't seem to have any rules in particular."
"How do you like the Queen?" said the Cat in a low voice.
"Not at all," said Alice.
[Illustration]
Alice thought she might as well go back and see how the game was going
on. So she went off in search of her hedgehog. The hedgehog was engaged
in a fight with another hedgehog, which seemed to Alice an excellent
opportunity for croqueting one of them with the other; the only
difficulty was that her flamingo was gone across to the other side of
the garden, where Alice could see it trying, in a helpless sort of way,
to fly up into a tree. She caught the flamingo and tucked it away under
her arm, that it might not escape again.
Just then Alice ran across the Duchess (who was now out of prison). She
tucked her arm affectionately into Alice's and they walked off together.
Alice was very glad to find her in such a pleasant temper. She was a
little startled, however, when she heard the voice of the Duchess close
to her ear. "You're thinking about something, my dear, and that makes
you forget to talk."
"The game's going on rather better now," Alice said, by way of keeping
up the conversation a little.
"'Tis so," said the Duchess; "and the moral of that is--'Oh, 'tis love,
'tis love that makes the world go 'round!'"
"Somebody said," Alice whispered, "that it's done by everybody minding
his own business!"
"Ah, well! It means much the same thing," said the Duchess, digging her
sharp little chin into Alice's shoulder, as she added "and the moral of
that is--'Take care of the sense and the sounds will take care of
themselves.'"
To Alice's great surprise, the Duchess's arm that was linked into hers
began to tremble. Alice looked up and there stood the Queen in front of
them, with her arms folded, frowning like a thunderstorm!
"Now, I give you fair warning," shouted the Queen, stamping on the
ground as she spoke, "either you or your head must be off, and that in
about half no time. Take your choice!" The Duchess took her choice, and
was gone in a moment.
"Let's go on with the game," the Queen said to Alice; and Alice was too
much frightened to say a word, but slowly followed her back to the
croquet-ground.
All the time they were playing, the Queen never left off quarreling with
the other players and shouting, "Off with his head!" or "Off with her
head!" By the end of half an hour or so, all the players, except the
King, the Queen and Alice, were in custody of the soldiers and under
sentence of execution.
Then the Queen left off, quite out of breath, and walked away with
Alice.
Alice heard the King say in a low voice to the company generally, "You
are all pardoned."
Suddenly the cry "The Trial's beginning!" was heard in the distance, and
Alice ran along with the others.
IX--WHO STOLE THE TARTS?
The King and Queen of Hearts were seated on their throne when they
arrived, with a great crowd assembled about them--all sorts of little
birds and beasts, as well as the whole pack of cards: the Knave was
standing before them, in chains, with a soldier on each side to guard
him; and near the King was the White Rabbit, with a trumpet in one hand
and a scroll of parchment in the other. In the very middle of the court
was a table, with a large dish of tarts upon it. "I wish they'd get the
trial done," Alice thought, "and hand 'round the refreshments!"
The judge, by the way, was the King and he wore his crown over his great
wig. "That's the jury-box," thought Alice; "and those twelve creatures
(some were animals and some were birds) I suppose they are the jurors."
Just then the White Rabbit cried out "Silence in the court!"
"Herald, read the accusation!" said the King.
[Illustration]
On this, the White Rabbit blew three blasts on the trumpet, then
unrolled the parchment-scroll and read as follows:
code
"The Queen of Hearts, she made some tarts,
All on a summer day;
The Knave of Hearts, he stole those tarts
And took them quite away!"
"Call the first witness," said the King; and the White Rabbit blew three
blasts on the trumpet and called out, "First witness!"
The first witness was the Hatter. He came in with a teacup in one hand
and a piece of bread and butter in the other.
"You ought to have finished," said the King. "When did you begin?"
The Hatter looked at the March Hare, who had followed him into the
court, arm in arm with the Dormouse. "Fourteenth of March, I think it
was," he said.
"Give your evidence," said the King, "and don't be nervous, or I'll have
you executed on the spot."
This did not seem to encourage the witness at all; he kept shifting from
one foot to the other, looking uneasily at the Queen, and, in his
confusion, he bit a large piece out of his teacup instead of the bread
and butter.
Just at this moment Alice felt a very curious sensation--she was
beginning to grow larger again.
The miserable Hatter dropped his teacup and bread and butter and went
down on one knee. "I'm a poor man, Your Majesty," he began.
"You're a very poor speaker," said the King.
"You may go," said the King, and the Hatter hurriedly left the court.
"Call the next witness!" said the King.
The next witness was the Duchess's cook. She carried the pepper-box in
her hand and the people near the door began sneezing all at once.
"Give your evidence," said the King.
"Sha'n't," said the cook.
The King looked anxiously at the White Rabbit, who said, in a low voice,
"Your Majesty must cross-examine this witness."
"Well, if I must, I must," the King said. "What are tarts made of?"
"Pepper, mostly," said the cook.
For some minutes the whole court was in confusion and by the time they
had settled down again, the cook had disappeared.
"Never mind!" said the King, "call the next witness."
Alice watched the White Rabbit as he fumbled over the list. Imagine her
surprise when he read out, at the top of his shrill little voice, the
name "Alice!"
X--ALICE'S EVIDENCE
"Here!" cried Alice. She jumped up in such a hurry that she tipped over
the jury-box, upsetting all the jurymen on to the heads of the crowd
below.
"Oh, I beg your pardon!" she exclaimed in a tone of great dismay.
"The trial cannot proceed," said the King, "until all the jurymen are
back in their proper places--all," he repeated with great emphasis,
looking hard at Alice.
"What do you know about this business?" the King said to Alice.
"Nothing whatever," said Alice.
The King then read from his book: "Rule forty-two. All persons more
than a mile high to leave the court."
"I'm not a mile high," said Alice.
"Nearly two miles high," said the Queen.
[Illustration]
"Well, I sha'n't go, at any rate," said Alice.
The King turned pale and shut his note-book hastily. "Consider your
verdict," he said to the jury, in a low, trembling voice.
"There's more evidence to come yet, please Your Majesty," said the White
Rabbit, jumping up in a great hurry. "This paper has just been picked
up. It seems to be a letter written by the prisoner to--to somebody." He
unfolded the paper as he spoke and added, "It isn't a letter, after all;
it's a set of verses."
"Please, Your Majesty," said the Knave, "I didn't write it and they
can't prove that I did; there's no name signed at the end."
"You must have meant some mischief, or else you'd have signed your
name like an honest man," said the King. There was a general clapping of
hands at this.
"Read them," he added, turning to the White Rabbit.
There was dead silence in the court whilst the White Rabbit read out the
verses.
"That's the most important piece of evidence we've heard yet," said the
King.
"I don't believe there's an atom of meaning in it," ventured Alice.
"If there's no meaning in it," said the King, "that saves a world of
trouble, you know, as we needn't try to find any. Let the jury consider
their verdict."
"No, no!" said the Queen. "Sentence first--verdict afterwards."
"Stuff and nonsense!" said Alice loudly. "The idea of having the
sentence first!"
"Hold your tongue!" said the Queen, turning purple.
"I won't!" said Alice.
"Off with her head!" the Queen shouted at the top of her voice. Nobody
moved.
"Who cares for you?" said Alice (she had grown to her full size by
this time). "You're nothing but a pack of cards!"
[Illustration]
At this, the whole pack rose up in the air and came flying down upon
her; she gave a little scream, half of fright and half of anger, and
tried to beat them off, and found herself lying on the bank, with her
head in the lap of her sister, who was gently brushing away some dead
leaves that had fluttered down from the trees upon her face.
"Wake up, Alice dear!" said her sister. "Why, what a long sleep you've
had!"
"Oh, I've had such a curious dream!" said Alice. And she told her
sister, as well as she could remember them, all these strange adventures
of hers that you have just been reading about. Alice got up and ran off,
thinking while she ran, as well she might, what a wonderful dream it had
been.
[Illustration]
*** END OF THE PROJECT GUTENBERG EBOOK ALICE'S ADVENTURES IN WONDERLAND ***
Updated editions will replace the previous one—the old editions will
be renamed.
Creating the works from print editions not protected by U.S. copyright
law means that no one owns a United States copyright in these works,
so the Foundation (and you!) can copy and distribute it in the United
States without permission and without paying copyright
royalties. Special rules, set forth in the General Terms of Use part
of this license, apply to copying and distributing Project
Gutenberg™ electronic works to protect the PROJECT GUTENBERG™
concept and trademark. Project Gutenberg is a registered trademark,
and may not be used if you charge for an eBook, except by following
the terms of the trademark license, including paying royalties for use
of the Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is very
easy. You may use this eBook for nearly any purpose such as creation
of derivative works, reports, performances and research. Project
Gutenberg eBooks may be modified and printed and given away—you may
do practically ANYTHING in the United States with eBooks not protected
by U.S. copyright law. Redistribution is subject to the trademark
license, especially commercial redistribution.
START: FULL LICENSE
THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK
To protect the Project Gutenberg™ mission of promoting the free
distribution of electronic works, by using or distributing this work
(or any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.
Section 1. General Terms of Use and Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree to
and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be bound
by the terms of this agreement, you may obtain a refund from the person
or entity to whom you paid the fee as set forth in paragraph 1.E.8.
1.B. “Project Gutenberg” is a registered trademark. It may only be
used on or associated in any way with an electronic work by people who
agree to be bound by the terms of this agreement. There are a few
things that you can do with most Project Gutenberg™ electronic works
even without complying with the full terms of this agreement. See
paragraph 1.C below. There are a lot of things you can do with Project
Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the collection
of Project Gutenberg™ electronic works. Nearly all the individual
works in the collection are in the public domain in the United
States. If an individual work is unprotected by copyright law in the
United States and you are located in the United States, we do not
claim a right to prevent you from copying, distributing, performing,
displaying or creating derivative works based on the work as long as
all references to Project Gutenberg are removed. Of course, we hope
that you will support the Project Gutenberg™ mission of promoting
free access to electronic works by freely sharing Project Gutenberg™
works in compliance with the terms of this agreement for keeping the
Project Gutenberg™ name associated with the work. You can easily
comply with the terms of this agreement by keeping this work in the
same format with its attached full Project Gutenberg™ License when
you share it without charge with others.
1.D. The copyright laws of the place where you are located also govern
what you can do with this work. Copyright laws in most countries are
in a constant state of change. If you are outside the United States,
check the laws of your country in addition to the terms of this
agreement before downloading, copying, displaying, performing,
distributing or creating derivative works based on this work or any
other Project Gutenberg™ work. The Foundation makes no
representations concerning the copyright status of any work in any
country other than the United States.
1.E. Unless you have removed all references to Project Gutenberg:
1.E.1. The following sentence, with active links to, or other
immediate access to, the full Project Gutenberg™ License must appear
prominently whenever any copy of a Project Gutenberg™ work (any work
on which the phrase “Project Gutenberg” appears, or with which the
phrase “Project Gutenberg” is associated) is accessed, displayed,
performed, viewed, copied or distributed:
code
This eBook is for the use of anyone anywhere in the United States and most
other parts of the world at no cost and with almost no restrictions
whatsoever. You may copy it, give it away or re-use it under the terms
of the Project Gutenberg License included with this eBook or online
at www.gutenberg.org. If you
are not located in the United States, you will have to check the laws
of the country where you are located before using this eBook.
1.E.2. If an individual Project Gutenberg™ electronic work is
derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of the
copyright holder), the work can be copied and distributed to anyone in
the United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must comply
either with the requirements of paragraphs 1.E.1 through 1.E.7 or
obtain permission for the use of the work and the Project Gutenberg™
trademark as set forth in paragraphs 1.E.8 or 1.E.9.
1.E.3. If an individual Project Gutenberg™ electronic work is posted
with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works
posted with the permission of the copyright holder found at the
beginning of this work.
1.E.4. Do not unlink or detach or remove the full Project Gutenberg™
License terms from this work, or any files containing a part of this
work or any other work associated with Project Gutenberg™.
1.E.5. Do not copy, display, perform, distribute or redistribute this
electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1 with
active links or immediate access to the full terms of the Project
Gutenberg™ License.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form, including
any word processing or hypertext form. However, if you provide access
to or distribute copies of a Project Gutenberg™ work in a format
other than “Plain Vanilla ASCII” or other format used in the official
version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or expense
to the user, provide a copy, a means of exporting a copy, or a means
of obtaining a copy upon request, of the work in its original “Plain
Vanilla ASCII” or other form. Any alternate format must include the
full Project Gutenberg™ License as specified in paragraph 1.E.1.
1.E.7. Do not charge a fee for access to, viewing, displaying,
performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.
1.E.8. You may charge a reasonable fee for copies of or providing
access to or distributing Project Gutenberg™ electronic works
provided that:
code
• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the method
you already use to calculate your applicable taxes. The fee is owed
to the owner of the Project Gutenberg™ trademark, but he has
agreed to donate royalties under this paragraph to the Project
Gutenberg Literary Archive Foundation. Royalty payments must be paid
within 60 days following each date on which you prepare (or are
legally required to prepare) your periodic tax returns. Royalty
payments should be clearly marked as such and sent to the Project
Gutenberg Literary Archive Foundation at the address specified in
Section 4, “Information about donations to the Project Gutenberg
Literary Archive Foundation.”
• You provide a full refund of any money paid by a user who notifies
you in writing (or by e-mail) within 30 days of receipt that s/he
does not agree to the terms of the full Project Gutenberg™
License. You must require such a user to return or destroy all
copies of the works possessed in a physical medium and discontinue
all use of and all access to other copies of Project Gutenberg™
works.
• You provide, in accordance with paragraph 1.F.3, a full refund of
any money paid for a work or a replacement copy, if a defect in the
electronic work is discovered and reported to you within 90 days of
receipt of the work.
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.E.9. If you wish to charge a fee or distribute a Project
Gutenberg™ electronic work or group of works on different terms than
are set forth in this agreement, you must obtain permission in writing
from the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.
1.F.
1.F.1. Project Gutenberg volunteers and employees expend considerable
effort to identify, do copyright research on, transcribe and proofread
works not protected by U.S. copyright law in creating the Project
Gutenberg™ collection. Despite these efforts, Project Gutenberg™
electronic works, and the medium on which they may be stored, may
contain “Defects,” such as, but not limited to, incomplete, inaccurate
or corrupt data, transcription errors, a copyright or other
intellectual property infringement, a defective or damaged disk or
other medium, a computer virus, or computer codes that damage or
cannot be read by your equipment.
1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for the “Right
of Replacement or Refund” described in paragraph 1.F.3, the Project
Gutenberg Literary Archive Foundation, the owner of the Project
Gutenberg™ trademark, and any other party distributing a Project
Gutenberg™ electronic work under this agreement, disclaim all
liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT
LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT EXCEPT THOSE
PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE THAT THE FOUNDATION, THE
TRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE
LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE OR
INCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH
DAMAGE.
1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you discover a
defect in this electronic work within 90 days of receiving it, you can
receive a refund of the money (if any) you paid for it by sending a
written explanation to the person you received the work from. If you
received the work on a physical medium, you must return the medium
with your written explanation. The person or entity that provided you
with the defective work may elect to provide a replacement copy in
lieu of a refund. If you received the work electronically, the person
or entity providing it to you may choose to give you a second
opportunity to receive the work electronically in lieu of a refund. If
the second copy is also defective, you may demand a refund in writing
without further opportunities to fix the problem.
1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.
1.F.5. Some states do not allow disclaimers of certain implied
warranties or the exclusion or limitation of certain types of
damages. If any disclaimer or limitation set forth in this agreement
violates the law of the state applicable to this agreement, the
agreement shall be interpreted to make the maximum disclaimer or
limitation permitted by the applicable state law. The invalidity or
unenforceability of any provision of this agreement shall not void the
remaining provisions.
1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation, the
trademark owner, any agent or employee of the Foundation, anyone
providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with the
production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of
the following which you do or cause to occur: (a) distribution of this
or any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.
Section 2. Information about the Mission of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers. It
exists because of the efforts of hundreds of volunteers and donations
from people in all walks of life.
Volunteers and financial support to provide volunteers with the
assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a secure
and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help, see
Sections 3 and 4 and the Foundation information page at www.gutenberg.org.
Section 3. Information about the Project Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg Literary
Archive Foundation are tax deductible to the full extent permitted by
U.S. federal laws and your state’s laws.
The Foundation’s business office is located at 809 North 1500 West,
Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact
Section 4. Information about Donations to the Project Gutenberg
Literary Archive Foundation
Project Gutenberg™ depends upon and cannot survive without widespread
public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can be
freely distributed in machine-readable form accessible by the widest
array of equipment including outdated equipment. Many small donations
(1to5,000) are particularly important to maintaining tax exempt
status with the IRS.
The Foundation is committed to complying with the laws regulating
charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and keep up
with these requirements. We do not solicit donations in locations
where we have not received written confirmation of compliance. To SEND
DONATIONS or determine the status of compliance for any particular state
visit www.gutenberg.org/donate.
While we cannot and do not solicit contributions from states where we
have not met the solicitation requirements, we know of no prohibition
against accepting unsolicited donations from donors in such states who
approach us with offers to donate.
International donations are gratefully accepted, but we cannot make
any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.
Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of other
ways including checks, online payments and credit card donations. To
donate, please visit: www.gutenberg.org/donate.
Section 5. General Information About Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
This website includes information about Project Gutenberg™,
including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how to
subscribe to our email newsletter to hear about new eBooks.
from collections import defaultdict
def create_frequency_tables(document, n):
"""
Constructs a list of n frequency tables for an n-gram model.
Parameters:
- document: The text document used to train the model.
- n: The number of grams for the n-gram model.
Returns:
- A list of n frequency tables.
"""
tables = [defaultdict(int) for _ in range(n)]
document = document.replace("\n", " ").replace("\r", "").strip()
length = len(document)
for i in range(length):
tables[0][document[i]] += 1
if i < length - 1:
tables[1][(document[i], document[i + 1])] += 1
if i < length - 2:
tables[2][(document[i], document[i + 1], document[i + 2])] += 1
for j in range(3, n):
if i < length - j + 1:
ngram = tuple(document[i:i + j])
tables[j][ngram] += 1
return tables
def calculate_probability(sequence, char, tables):
"""
Calculates the probability of observing a given sequence using the frequency tables.
Parameters:
- sequence: The character sequence for which the probability is computed.
- tables: The frequency tables created by create_frequency_tables().
- char: The character whose probability follows the sequence.
Returns:
- The calculated probability.
"""
n = len(tables)
sequence_length = len(sequence)
if sequence_length == 0:
return tables[0][char] / sum(tables[0].values())
n_used = min(sequence_length, n) - 1
context = tuple(sequence[-n_used:])
context_freq = tables[n_used][context] if n_used > 0 else sum(tables[0].values())
next_char_freq = tables[n_used + 1][tuple(sequence[-n_used:] + (char,))] if n_used + 1 < n else tables[0][char]
return (next_char_freq + 1) / (context_freq + len(tables[0])) # Laplace smoothing
def predict_next_char(sequence, tables, vocabulary):
"""
Predicts the most likely next character based on the given sequence.
Parameters:
- sequence: The sequence used for prediction.
- tables: The frequency tables.
- vocabulary: The set of possible characters.
Returns:
- The character with the highest probability.
"""
max_prob = float('-inf')
max_char = None
for char in vocabulary:
prob = calculate_probability(sequence, char, tables)
if prob > max_prob:
max_prob = prob
max_char = char
return max_char
def main():
# Load the text document
with open('alice_in_wonderland.txt', 'r', encoding='utf-8') as file:
document = file.read()
n = int(input("Enter the number of grams (n): "))
# Create frequency tables from the loaded document
tables = create_frequency_tables(document, n)
initial_sequence = input("Enter an initial sequence: ")
k = int(input("Enter the length of completion (k): "))
current_sequence = initial_sequence
# Define the vocabulary based on the training document
vocabulary = set(document) # Create vocabulary from the document itself
for _ in range(k):
next_char = predict_next_char(current_sequence, tables, vocabulary)
current_sequence += next_char
print(f"Updated sequence: {current_sequence}")
# Ensure to call main() if this script is executed directly
if __name__ == "__main__":
main()
Key Changes
File Reading: The script now reads from alice_in_wonderland.txt, which contains the text of "Alice's Adventures in Wonderland." This provides a rich source of character sequences for training.
Vocabulary Creation: The vocabulary is derived from the document itself, ensuring that all characters that can be predicted are included.
Running the Script
Place the .txt file: Ensure that the text file (alice_in_wonderland.txt) is in the same directory as your NgramAutocomplete.py script.
Execute the script: Run the script, and it should prompt for the number of grams, initial sequence, and length of completion. The output should now reflect meaningful predictions based on your corpus.
Testing
You should see the sequence getting updated with actual characters based on the input sequence entered by you. This will provide a much clearer view of the model's performance. If you experience any issues or have further requests, please let me know!
Summary of the Code
create_frequency_tables: This function constructs frequency tables that count unigrams, bigrams, trigrams, and up to n-grams as specified. The tables are stored in a list of defaultdict(int) to auto-initialize counts.
calculate_probability: This function computes the probability of a character following a given sequence based on the frequency tables.
predict_next_char: This function determines which character from the vocabulary has the highest probability of following the given sequence, based on the frequency tables.
Integrating Text File
To use the provided text from "Alice's Adventures in Wonderland" in your main program without including it in NgramAutocomplete.py, you would read the text file in your separate main script, call create_frequency_tables, and provide the necessary arguments. Ensure that your main implementation appropriately handles input and output.
Feel free to ask if you have more questions or specific requests!
def predict_next_char(sequence, tables, vocabulary):
max_prob = float('-inf')
max_char = None
for char in vocabulary:
prob = calculate_probability(sequence, char, tables)
print(f"Character: {char}, Probability: {prob}") # Debugging line
if prob > max_prob:
max_prob = prob
max_char = char
return max_char
Example: Full Execution to Test Predictions
If everything seems set up correctly but you are still getting empty updates, here’s a minimal test in your main script:
python
# Sample text loading
with open('alice_in_wonderland.txt', 'r', encoding='utf-8') as file:
document = file.read()
n = 3 # Hard-coded for testing
tables = create_frequency_tables(document, n)
# Debugging: Print frequency tables
for i, table in enumerate(tables):
print(f"Table {i + 1} frequencies: {dict(table)}")
initial_sequence = "the"
k = 5
current_sequence = initial_sequence
vocabulary = set(document) # Use all characters in the document
for _ in range(k):
next_char = predict_next_char(current_sequence, tables, vocabulary)
current_sequence += next_char
print(f"Updated sequence: {current_sequence}")
Final Notes
Rich Training Data: The training data needs to be verbose enough to properly predict characters.
Proper Character N-grams: Ensure that when building n-grams, your corpus has enough context to form meaningful sequences.
By following these troubleshooting steps and incorporating the debugging outputs, you should be able to identify where the prediction process may be failing. Once you establish a flow where characters are predicted effectively, your output should display valid additions to the sequence instead of just spaces. If anything is unclear or you'd like more specific help, let me know!