0% found this document useful (0 votes)
23 views3 pages

N-gram Analysis in Python

The document loads the Brown corpus from NLTK and preprocesses it by case folding and extracting the vocabulary. It then calculates bigram and trigram counts by sliding a window over the corpus. Finally, it defines a function that takes a sentence as input and suggests the top 3 most probable next words based on the bigram and trigram counts. It provides examples of running this function on sample inputs.

Uploaded by

lalitha sri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views3 pages

N-gram Analysis in Python

The document loads the Brown corpus from NLTK and preprocesses it by case folding and extracting the vocabulary. It then calculates bigram and trigram counts by sliding a window over the corpus. Finally, it defines a function that takes a sentence as input and suggests the top 3 most probable next words based on the bigram and trigram counts. It provides examples of running this function on sample inputs.

Uploaded by

lalitha sri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

From nltk.

corpus import brown

From [Link] import word_tokenize

#Loading the corpus

Corpus = [Link]

#case folding and getting vocab

Lower_case_corpus = [[Link]() for w in corpus]

Vocab = set(lower_case_corpus)

print(‘CORPUS EXAMPLE:’+str(lower_case_corpus[:30])+’\n\n’)

print(‘VOCAB EXAMPLE:’+str(list(vocab)[:10]))

CORPUS EXAMPLE:
[‘the’,’fulton’,’county’,’grand’,’jury’,’said’,’friday’,’an’,’investigation’,’of’,”atlanta’s”,’recent’,’primary’,’electi
on’,’produced’,’’’’,’no’,’evidence’,’’’’,’that’,’any’,’irregularities’,’took’,’place’,’.’,’the’,’jury’,’further’,’said’,’in’]

VOCAB EXAMPLE:[‘drudgery’,’one-
arm’,’growling’,’cutest’,’rain’,’hops’,”network’s”,’expressionists’,’polarization’,’gaussian’]

print(‘Total words in Corpus:’+str(len(lower_case_corpus)))

print(‘Vocab of the Corpus:’+str(len(vocab)))

Total words in Corpus:1161192

Vocab of the Corpus:49815

bigram_counts={}

trigram_counts={}

#sliding through corpus to get bigram and trigram counts

For I in range(len(lower_case_corpus)-2):

#Gettingt bigram and trigram at each slide

bigram = (lower_case_corpus[i],lower_case_corpus[i+1])

trigram = (lower_case_corpus[i],lower_case_corpus[i+2])

#keeping track of the bigram counts

If bigram in bigram_counts.keys():

bigram_counts[bigram]+=1

else:

bigram_counts[bigram]=1
#keeping track of trigram counts

If trigram in trigram [Link]():

trigram_counts[trigram]+=1

else:

trigram_counts[trigram]=1

print(“Example, count for bigram(‘the’,’king’)is:”+str(bigram_counts(‘the’,’king’)])) Example, count for


bigram(‘the’,’king’)is:51

#Function takes sentences as input and suggests possible words that comes after the sentence

Def suggest_next_word(input_,bigram_counts,trigram_counts,vocab)

#consider the last bigram of sentence

tokenized_input = word_tokenize(input_.lower())

last_bigram = tokenized_input[-2:]

#calculating probability for each word in vocab

Vocab_probabilities = {}

For vocab_word in vocab:

Test_trigram = (last_bigram[0],last_bigram[1],vocab_word)

Test_bigram = (last_bigram[0],last_bigram[1])

Test_trigram_count = trigram_counts.get(test_trigram,0)

Test_bigram_count = bigram_counts.get(test_bigram,0)

Probability = test_trigram_counts/test_bigram_count

Vocab_probabilities[vocab_word] = probability

#sorting the vocab probability in descending order to get top probable words

Top_suggestions = sorted(vocab_probabilities.items(),key=lambda x:x[1],reverse = True)[:3]return


top_suggestions

Suggest_next_word(‘I am the king’,bigram_counts,trigram_counts,vocab)

[(‘james’,0.17647058823529413),(‘of’,0.1568627450980392),(‘arthur’,0.1176470588352941)]

Suggest_next_word(‘I am the king of’,bigram_counts, trigram_counts, vocab)

[(‘france’,0.3333333),(‘hearts’,0.1666666),(‘morocco’,0.0833333)]

Suggest_next_word(‘I am the king of france’, bigram_counts, trigram_counts, vocab)


[(‘and’,0.2666),(‘.’,0.2666),(‘.’,0.2)]

Suggest_next_word(‘I am the king of france and’, bigram_counts, trigram_counts, vocab)

[(‘the’,0.2),(‘germany’,0.1333),(‘some’,0.066667)]

Common questions

Powered by AI

The key outputs for the context 'I am the king' include the top three suggested words with probabilities: [('james', 0.176), ('of', 0.156), ('arthur', 0.117)]. This indicates that 'james' is the most probable next word following the given context.

Sorting vocabulary probabilities in descending order helps to directly retrieve the top probable next words by rearranging items based on probability values, which are calculated by dividing trigram counts over bigram counts. This approach implies an efficient means of determining the top candidates by linear scanning through the probabilities, which can be computationally expensive with large vocabularies but avoids mis-selection of less probable words .

The excerpt highlights limitations such as the assumption of conditional independence between words, ignoring broader context beyond the n-1 window. This leads to difficulties with idiomatic expressions or language requiring deep context, resulting in mispredictions. Moreover, it struggles with unseen n-grams, assigns zero probabilities without smoothing, and faces issues with data sparsity that impair model robustness and applicability .

The probability of a word following a sentence is calculated by dividing the count of a test trigram by the count of the last bigram of the sentence. The sentence is tokenized and the last bigram is determined: `last_bigram = tokenized_input[-2:]`. Each vocabulary word forms a test trigram with this bigram, and its probability is calculated: `Probability = test_trigram_counts/test_bigram_count` . This approach assumes independence between turns in context.

Using only bigrams and trigrams may not effectively capture long-range dependencies in language, as these models rely solely on local context within the n-1 window. They often lead to high perplexity with novel word combinations and struggle with sparse data issues that affect probability calculations. Moreover, without smoothing techniques, these models assign zero probabilities to unobserved n-grams, potentially limiting predictive accuracy .

The process involves converting all words in the corpus to lowercase to ensure uniformity, using a list comprehension: `Lower_case_corpus = [w.lower() for w in corpus]`. Then, a set is created from this lowercase list, which automatically filters unique words to form the vocabulary: `Vocab = set(lower_case_corpus)` .

The method uses a sliding window approach, iterating over the corpus to extract n-grams: `For i in range(len(lower_case_corpus)-2)`. It relies on dictionary keys to track occurrences, incrementing counts on existing keys or initializing counts for new ones . A potential pitfall of this approach is inefficiency with large datasets due to constant dictionary lookups and updates, which could slow down as dictionary size grows significantly.

The n-gram model could be improved by incorporating smoothing techniques like Add-one or Kneser-Ney to address zero probability issues. Utilizing models like Long Short-Term Memory (LSTM) networks could capture dependencies beyond the immediate context. Also, integrating context-aware models that factor in syntactic and semantic understanding, such as transformers, could improve prediction accuracy and capability handling diverse language use .

The sentence input is tokenized using NLTK's word_tokenize method, which converts the string into a list of words: `tokenized_input = word_tokenize(input_.lower())`. This facilitates extraction of the last bigram, which forms the basis for subsequent analysis and probability calculations to predict the next word in sequence .

In the suggest_next_word function, bigrams establish context, serving as a reference framework for each word in the vocabulary during probability calculations. Trigrams expand upon this by including a candidate vocabulary word, allowing estimation of the likelihood that a word follows the observed bigram. Together, they enable pairing of immediate context with potential continuations, essential for context-sensitive word prediction .

You might also like