Create a NGram language model using nltk
- User
Create a NGram language model using nltk
- Assistant
Create a NGram language model using nltk
Certainly! An N-gram language model predicts the probability of a word given the previous ( N-1 ) words. It's a fundamental concept in natural language processing and is useful in applications like text prediction, speech recognition, and machine translation.
In this guide, I'll show you how to create an N-gram language model using NLTK (Natural Language Toolkit) in Python. We'll:
Let's get started!
Firstly, make sure you have NLTK installed. If not, you can install it using pip:
pip install nltk
Now, import the necessary libraries:
import nltk
from nltk.util import ngrams
from collections import defaultdict, Counter
We'll also need to download some NLTK resources:
nltk.download('punkt')
For this example, we'll use a simple text corpus. In practice, you should use a larger dataset to get better results.
text = """
Natural language processing (NLP) is a subfield of linguistics, computer science, and artificial intelligence
concerned with the interactions between computers and human language, in particular how to program computers to
process and analyze large amounts of natural language data. The result is a computer capable of "understanding"
the contents of documents, including the contextual nuances of the language within them. The technology can then
accurately extract information and insights contained in the documents as well as categorize and organize the documents themselves.
"""
We'll tokenize this text into sentences and words.
from nltk.tokenize import sent_tokenize, word_tokenize
sentences = sent_tokenize(text)
Tokenize each sentence into words:
tokenized_sentences = [word_tokenize(sentence) for sentence in sentences]
Define the value of N for your N-gram model. For example, let's create a trigram (( N = 3 )) model.
N = 3
Generate N-grams and collect their frequencies.
ngrams_list = []
for sentence in tokenized_sentences:
# Add start and end tokens
sentence = ['<s>'] * (N-1) + sentence + ['</s>']
ngrams_in_sentence = list(ngrams(sentence, N))
ngrams_list.extend(ngrams_in_sentence)
Now, we'll count the frequency of each N-gram:
ngram_freq = Counter(ngrams_list)
Similarly, we'll collect the frequency of the (N-1)-grams to compute probabilities:
# For counting (N-1)-gram frequencies
n_minus_one_grams_list = []
for sentence in tokenized_sentences:
sentence = ['<s>'] * (N-1) + sentence + ['</s>']
n_minus_one_grams_in_sentence = list(ngrams(sentence, N-1))
n_minus_one_grams_list.extend(n_minus_one_grams_in_sentence)
n_minus_one_gram_freq = Counter(n_minus_one_grams_list)
We'll create a nested dictionary structure to store probabilities:
# The language model
model = defaultdict(lambda: defaultdict(lambda: 0))
Calculate the conditional probability of each word given the previous ( N-1 ) words.
for ngram in ngram_freq:
prefix = ngram[:-1]
word = ngram[-1]
model[prefix][word] = ngram_freq[ngram] / n_minus_one_gram_freq[prefix]
Let's create a function to predict the next word given a previous context:
def predict_next_words(context, model, num_predictions=5):
context = tuple(context)
if context in model:
sorted_predictions = sorted(model[context].items(), key=lambda x: x[1], reverse=True)
return sorted_predictions[:num_predictions]
else:
return []
Suppose we want to predict the next word after the context ('the', 'documents'):
context = ('the', 'documents')
predictions = predict_next_words(context, model)
print(f"Predictions for context {context}:")
for word, prob in predictions:
print(f"{word}\tProbability: {prob:.4f}")
Output:
Predictions for context ('the', 'documents'):
as Probability: 1.0000
If we try with another context:
context = ('Natural', 'language')
predictions = predict_next_words(context, model)
print(f"\nPredictions for context {context}:")
for word, prob in predictions:
print(f"{word}\tProbability: {prob:.4f}")
Output:
Predictions for context ('Natural', 'language'):
processing Probability: 1.0000
In practice, you'll encounter contexts that were not seen during training. To handle unseen N-grams, you can:
Here's how you can integrate Laplace smoothing into the model:
# Vocabulary size for smoothing
vocab = set(word for sentence in tokenized_sentences for word in sentence)
V = len(vocab)
def calculate_probability_laplace(ngram_freq, n_minus_one_gram_freq, V):
model_laplace = defaultdict(lambda: defaultdict(lambda: 0))
for ngram in ngram_freq:
prefix = ngram[:-1]
word = ngram[-1]
# Apply Laplace smoothing
model_laplace[prefix][word] = (ngram_freq[ngram] + 1) / (n_minus_one_gram_freq[prefix] + V)
return model_laplace
model_laplace = calculate_probability_laplace(ngram_freq, n_minus_one_gram_freq, V)
Now, if you use model_laplace for predictions, it will handle unseen words with a small probability instead of zero.
You've successfully created an N-gram language model using NLTK! This model can predict the next word based on the previous ( N-1 ) words. Remember, the performance of the model heavily depends on the size and quality of your training corpus. For real-world applications, consider using larger datasets and more sophisticated smoothing techniques.
Choosing N: Larger N captures more contextual information but requires more data to estimate probabilities accurately. Common choices are bigrams (N=2) and trigrams (N=3).
NLTK Corpora: NLTK comes with several corpora you can use, such as the Brown Corpus:
from nltk.corpus import brown
nltk.download('brown')
sentences = brown.sents()
Performance Considerations: For large datasets, consider using more efficient data structures or libraries optimized for numerical computations, like NumPy or Pandas.
Feel free to experiment with different N values, smoothing techniques, and corpora to see how they affect your language model.
Not yet included in a published release.