Zero Labs
Industry News / AI

Coding A PoS Tagger from Scratch — A Statistical Part-of-Speech Tagger | NLP | Explaining the…

Source · Towards AI By Shubh Mishra

From the publisher’s feed, collected in the ZeroLabs newsroom.

Coding A PoS Tagger from Scratch — A Statistical Part-of-Speech Tagger | NLP | Explaining the Hidden Markov ModelHey there! I haven’t written one of these ‘from scratch’ implementations for a while now. I'm thinking of getting back in the game, and what better would be to start than implementing from this early 2000s paper on one of the most satisfying statistical models out there - the Hidden Markov Model.We are going to dive into the basic theory and mathematics involved in hidden Markov models. But what I'm actually excited to show you guys is implementing one in action for a well-known NLP task known as POS tagging or Part-of-Speech tagging.This one is going to be quite detailed, so without further ado lets dive straight into it.If you are into NLP, this is something you would’ve definitely heard of. This blog is based on the very famous 2000 paper TnT — A Statistical Part-of-Speech Tagger by Thorsten Brants [1]. Even to this day, the nltk library uses the same methodology as discussed in the paper to predict POS tags for a sentence.Image Soure: Author (Generated with AI)POS tags and Statistical ModelingSay we have a string “I like books” for which the POS tags would be“I” → PRP (personal pronoun), “like” → VBP (verb, present tense), “books” → NNS (noun, plural). The task is to predict the tag sequence ["PRP", "VBP", "NNS"] for the words ["I", "like", "books"].Suppose we have a large corpus W with thousands of words, and we want to compute the probability of “like” appearing after “I.” We would count how many times “like” follows “I” and divide it by the total number of word occurrences, formally:P(“I”, “like”) = Count(“I” “like”)/len(W), where P(“I”, “like”) is the probability of the word “like” given the previous word is “I”.Now, naturally, we know that P(“I”, “like”) > P(“I”, “ice”) because “I like” appears more frequently and is more natural.POS tagging follows the same intuition: with enough data, we estimate how likely certain tags follow others. This probabilistic reasoning forms the foundation of Hidden Markov Models, which extend this idea beyond simple word counting.Hidden Markov ModelsHMMs are used when you have a sequence of observable states (words in the POS case), and you want to figure out the corresponding or most likely sequence of hidden states (POS tags).Imagine you’re stuck in a windowless room, but you want to know what the weather is like outside.Now, you can’t see the sky (that’s the Hidden State), but you can see people walking into the building. If a guy walks in soaking wet with an umbrella, you’re pretty sure it’s raining. If the next person is wearing sunglasses and a tank top, you’d bet your house it’s sunny.In this scenario:The Hidden States: Rainy, Sunny, Snowy (What we want to know).The Observations: Umbrellas, Sunglasses, Coats (The clues we actually see).An HMM uses two simple “rules” or probabilities to make a guess:Transition Probability: If it was sunny yesterday, how likely is it to be sunny or rainy again today?Emission Probability: If it’s actually raining, how likely is it that someone is carrying an umbrella?In NLP, the “Weather” is the POS tag (Noun, Verb, etc.) and the “Clues” are the actual words in the sentence. We see the words, and the model has to work backward to find the hidden tags.An HMM formalizes this guessing game. It uses mathematics to calculate the most likely sequence of weather patterns based on the sequence of outfits you observed.To be very honest If you wanna get into some really good intuition on how Hidden Markov Models work, I would definitely recommend watching this short series from YouTube [2]. If you’re not interested, I still recommend at least going through this short video on HMM. Hidden Markov Models are incredibly satisfying to understand and remain one of the most important and widely used probabilistic models in practice.Applying this for NLP (POS)Let’s say we want to find the best tags for the sentence “The cat”. Our goal is to find a tag sequence, like [Determiner, Noun], that has the highest score. But what makes a score "good"? We need to check two things.Part 1: Is the Tag Sequence Grammatically Valid? (Transition Probability)First, let’s completely ignore the words. We just want to know: does the tag sequence Determiner -> Noun make grammatical sense?We can answer this by looking at how often this pattern appears in real language. If we analyze a huge corpus of tagged sentences, we'd find that a Noun follows a Determiner very often.So, the probability P(Noun | Determiner) is high.Part 2: Do the Words Actually Fit the Tags? (Emission Probability)Grammar alone isn’t enough. We already have the words — “The cat” — and we’re trying different tag combinations to see which one fits best.So when we try the combination [Determiner, Noun], we need to ask: how likely is it that the word "The" would appear as a Determiner? And how likely is "cat" to appear as a Noun?This is the Emission Probability: $P(w_i | t_i)$. It tells us how likely a specific word is, given a specific tag. It's our word-fit score.Combining Both: The Full HMM Score A good tag sequence must satisfy both conditions:The sequence of tags must be grammatically plausible. (High Transition Probability)The words must actually “fit” those tags. (High Emission Probability)The final score is simply the product of both. For each word, we multiply its transition probability by its emission probability.It is very similar to how the probability of two consecutive heads in a coin toss is the product of probabilities in the first toss and second (1/2*12=1/4).Just like that, to get the score of the tags [“Det” “Noun”] for the sentence [“The” “Cat”], we calculate the probability of the word “the” being a Det, and what is the probability of “Det” coming right after “Start” (the previous tag aka BOS) and the probability of Cat being a Noun and Noun being followed by a Det (the previous tag).Notice the pattern: for each word, we ask “How likely is this word given this tag?” (emission) and “How likely is that tag given the previous tag?” (transition). We multiply these together for the entire sequence.This is the heart of the HMM formula:We are searching for the tag sequence ($\operatorname{argmax}$) that maximizes the product of transition and emission probabilities for every word in the sentence.TnT TaggersPart-of-Speech Taggingwhere f is the frequency (count) of that tag and N is the total number of tokens in the training corpus.P(t3|t1, t2) = λ1*P(t3) + λ2*P (t3|t2) + λ3*P (t3|t1, t2)Here, t3 is the first tag in the sequence (t1 and t2 both are BOS tags). Generally, to compute this, we only need to find the number of times tag t3 appears in our training corpus, given the last two tags are t1 and t2. However, that leads to an issue, if a particular trigram (t1, t2, t3) is rare or doesn’t exist, the prob becomes 0. This vanishes the entire score of the sequence to zero; we don’t want that since we do need some score for our sequence. Thus, we use a mix of unigram, bigram and trigram probabilities.Significance of λIt's used to smooth out the given weights (importance) to each transition probability. In a way, this allows us to weight Trigrams when we’ve seen them often, bigrams when trigrams are shaky, unigrams when nothing else works; all blended so Viterbi never dead-ends.ImplementationOur TnT Tagger basically has two phases.TrainingCounting the frequency f of unigrams, bigrams, trigrams, and lexical (EOS)Computing the values of λ_1, λ_2, λ_32. Beams Search: Predicting the sequence of tags for our sequence of wordsTrainingclass HybridValue: def __init__(self): self._counter = 0 self._nested = {} def __iadd__(self, other): self._counter += other return self def __getitem__(self, key): if key not in self._nested: self._nested[key] = HybridValue() return self._nested[key] def __setitem__(self, key, value): self._nested[key] = valueclass SimpleCFD(dict): def __getitem__(self, key): if key not in self: self[key] = HybridValue() return dict.__getitem__(self, key)The way we’re coding is pretty much the most basic and standard implementation for TnT you’ll get out there. The thing is that we need to keep the count of nested states, which we can not do through normal dictionaries, so we take dict as a base class and build our own classes for getting our conditional frequency distribution CFD and HybridValue container.What these functions actually do will make sense when we get to the rest of the code. For now, just think of SimpleCFD as a counter for keeping records of our tags.Training datafrom nltk.corpus import treebankimport nltknltk.download('treebank')data = treebank.tagged_sents()print(data)# Output:-# Our Data is available in pairs of (words, tag)[('Neither', 'DT'), ('Lorillard', 'NNP'), ('nor', 'CC'), ('the', 'DT'), ('researchers', 'NNS'), ('who', 'WP'), ('*T*-3', '-NONE-'), ('studied', 'VBD'), ('the', 'DT'), ('workers', 'NNS'), ('were', 'VBD'), ('aware', 'JJ'), ('of', 'IN'), ('any', 'DT'), ('research', 'NN'),Populatingclass TnTTagger: def __init__(self): self.w_t = SimpleCFD() self.uni_t = SimpleCFD() self.bi_t = SimpleCFD() self.tri_t = SimpleCFD() self._EOS = SimpleCFD() self.size_ = 0 self._N = 1000 # Initialize lambda values self.l1 = 0 self.l2 = 0 self.l3 = 0 def __populate__(self, trainset): for sent in trainset: current_states = [('BOS', False), ('BOS', False)] for word, tag in sent: self.size_ += 1 _uP = word[0].isupper() tag = (tag, _uP) self.w_t[word][tag] += 1 self.uni_t[tag] += 1 self.bi_t[current_states[1]][tag] += 1 self.tri_t[tuple(current_states)][tag] += 1 current_states.append((tag)) current_states.pop(0) self._EOS[tag][('EOS', False)] += 1 self.size_ += 1 self.__lambda__()__lambda__ is the function that computes the correct value of our three lambda scalers.def __lambda__(self): # Remeber the structure of tri_t is following: # { # (t1, t2) : { # t3 : count # } # } # where t is a tuple (t, _uP) for t1t2 in self.tri_t.keys(): for t3 in self.tri_t[t1t2]._nested.keys(): if self.tri_t[t1t2][t3]._counter > 0: f_tri = ( (self.tri_t[t1t2][t3]._counter - 1) / (self.bi_t[t1t2[0]][t1t2[1]]._counter - 1 or math.inf) ) f_bi = ( (self.bi_t[t1t2[1]][t3]._counter - 1) / (self.uni_t[t1t2[1]]._counter - 1 or math.inf) ) f_uni = ( (self.uni_t[t3]._counter - 1) / (self.size_ - 1 or math.inf) ) if f_tri == max(f_tri, f_bi, f_uni): self.l3 += self.tri_t[t1t2][t3]._counter if f_bi == max(f_tri, f_bi, f_uni): self.l2 += self.tri_t[t1t2][t3]._counter if f_uni == max(f_tri, f_bi, f_uni): self.l1 += self.tri_t[t1t2][t3]._counter net_lmbda = np.sqrt(sum(l**2 for l in [self.l1, self.l2, self.l3])) net_lmbda = self.l1 + self.l2 + self.l3 self.l1 = self.l1/net_lmbda self.l2 = self.l2/net_lmbda self.l3 = self.l3/net_lmbdaThis function finds out the avg lambda values that we can use to smooth our transition probabilities as given in the official paper.Image Source: TnT — A Statistical Part-of-Speech TaggerThe explanation is pretty intuitive:We begin by looping within a trigram to reach every single tag and calculate its probability with respective previous tag(s) in the sequence.For f_tri what we calculate is F(t1, t2, t3) / F(t1, t2), which is read as the number of times tag t3 appears right after tags t1 and t2 for all the times t2 appeared right after t1.Similarly F(t2, t3) / F(t2) is the number of times tag t3 comes right after t2 for all the times t2 appears. This gives up relative frequency for a trigram’s frequency over its bigram, thus giving us information regarding how strong a trigram's appearance is compared to its bigram.NOTE: We use or NOTE: We use orhe denominator because in case frequency is every zero we would want to avoid the zero division error and consider that frequency null or 0. Also we substract the numerator and denominator with -1. (i.e F(t2, t3) -1 / F(t2)-1) to avoid counting the current instance of tag[3].Example: How likely is the word (in our case, tag) “Cats” come after “I like” for ever time “I like” is used Vs How likely does “like Cat” come after “I” for every time “I like” is used in the corpus? If the former is more likely, that means we have to give more weight to the trigram transition probability we’ll calculate over the bigram transition probability.In the end, we just do this for every single trigram in our corpus and average them out.Beam Search — HMM in Action!def beamSearchTagger(self, sent, current_states): """ sent = "She said do you love me I told her I only partly" current_states = [([("BOS", False), ("BOS", False)], 0.0)] """ if sent == []: (h, logp) = current_states[0] return h word = sent[0] sent = sent[1:] new_states = [] C = False if word[0].isupper(): C = True if word in self.w_t: for history, curr_sent_logprob in current_states: for tag in self.w_t[word]._nested.keys(): p_uni = self.uni_t[tag]._counter/self.size_ p_bi = self.bi_t[history[-1]][tag]._counter/(self.uni_t[history[-1]]._counter or math.inf) p_tri = self.tri_t[tuple(history[-2:])][tag]._counter/(self.bi_t[history[-2]][history[-1]]._counter or math.inf) p_w = self.w_t[word][tag]._counter /(self.uni_t[tag]._counter or math.inf) p = self.l1 * p_uni + self.l2 * p_bi + self.l3 * p_tri try: p2 = log(p, 2) + log(p_w, 2) except: p2 = 0.1 new_states.append((history + [tag], curr_sent_logprob + p2)) else: tag = ("Unk", C) for history, _ in current_states: history.append(tag) new_states = current_states new_states.sort(reverse=True, key=itemgetter(1)) if len(new_states) > self._N: new_states = new_states[: self._N] return self.beamSearchTagger(sent, new_states)The logic is as follows:The function takes the next word from the sentence.For each history in the current state beam, it generates new potential paths by trying every possible_tag for that word.Each new path’s score is calculated by adding the log of the transition probability (p) and the emission probability (p_w) to the previous path's score.After generating all candidates, it sorts them by score and keeps only the top _N (beam size).It then calls itself with the rest of the sentence and this new, pruned beam.When the sentence is empty, the recursion stops, and the history of the single best path or highest score is returned. (i.e., current_states[0] as the list of states is sorted from max probability)if word in self.w_t: for history, curr_sent_logprob in current_states: for tag in self.w_t[word]._nested.keys(): p_uni = self.uni_t[tag]._counter/self.size_ p_bi = self.bi_t[history[-1]][tag]._counter/(self.uni_t[history[-1]]._counter or math.inf) p_tri = self.tri_t[tuple(history[-2:])][tag]._counter/(self.bi_t[history[-2]][history[-1]]._counter or math.inf) p_w = self.w_t[word][tag]._counter /(self.uni_t[tag]._counter or math.inf) p = self.l1 * p_uni + self.l2 * p_bi + self.l3 * p_tri try: p2 = log(p, 2) + log(p_w, 2) except: p2 = 0.1We start with the initial state: [([("BOS", False), ("BOS", False)], 0.0)]. Each state contains the last two tags (history) and the current log score (starting at 0.0). As we move through the sentence, this score is updated for every possible tag sequence. If a word does not appear in the training set, we skip probability computation and directly assign it the UNK (unknown) tag.For known words, we compute the Hidden Markov Model score for each possible tag:For every tag that we find for this word we calculate:A: Transition Probabilityp_uni: the number of times tag t appeared in our entire corpus.p_bi: the number of times current tag (which we call t3) appeared given previous tag t2 for every time t2 appeared in the training corpus.p_tri: similar to p_bi, how often the current tag appears but given the previous two tags.These are combined using interpolation weights (λ1, λ2, λ3) to produce the final transition probability.B: Emission ProabilityNow we have the transition probability of current tag given the previous (which is just BOS for first word’s tag) we can get the emission probability.p_w here gets us the probability of the current word having this particular tag by finding the number of times this word had the given tag for every time this tag appeared in the training corpus.We multiply the transition and emission probabilities and take the logarithm for numerical stability. This gives the updated score for that tag sequence.After generating the score for each tag, we append that tag to new_states. This becomes our current_states in the next recursive call.What’s really happening here in the for loops:for history, curr_sent_logprob in current_states: for tag in self.w_t[word]._nested.keys(): ... existing code ... new_states.append((history + [tag], curr_sent_logprob + p2))After computing the score for each possible tag, we append the new (history + [tag], updated_score) pair to new_states. These new_states then become the current_states for the next recursive step.What the nested loops are doing is simple but expensive:For every existing tag history, we try every possible tag for the current word and compute a new score. As the sentence grows, the number of possible sequences explodes, for even a 10-word sentence, this can become extremely large.To control this growth, we sort new_states in descending order of score and keep only the top 1000 sequences before moving to the next step.This technique is called beam search, and the fixed limit (1000 here) is known as the beam width. Instead of exploring all possible sequences, we only continue with the most promising candidates.Finally, when the sentence is finished, it returns the states with the highest score (current_states[0]) as the list of states in the 0th position is sorted to have max probability, which we use later to return the final result.def tag_sent(self, sent): current_state = [([("BOS", False), ("BOS", False)], 0.0)] tags = self.beamSearchTagger(sent, current_state) res = [] for i in range(len(sent)): (t, C) = tags[i + 2] res.append((sent[i], t)) return res Example:-res = tag_sent("This is so peak")print(res)Output:-[('This', 'DT'), ('is', 'VBZ'), ('so', 'RB'), ('peak', 'NN')]AND THAT IS IT!!We have implemented a statistical model from the paper TnT - A Statistical Part-of-Speech Tagger, using Hidden Markov Models to predict the POS Tags of a word sequence. You can check the entire code put together with an executable script on my GitHub.As usual.. I can’t thank you guys enough for reading this article so far.Thank you very much for giving learning a chance (that too, a probabilistic NLP model). Anyways. If you have any questions, feel free to ask me in the comments. See you in the next one!Reference[1] TnT — A Statistical Part-of-Speech Tagger[2] Hidden Markov Models Explained[3] During computing lambda values subtract by one in F(t2, t3) -1 / F(t2)-1) to avoid counting the current instance of tag t3 after t2 and only account for the rest of the ocurrences of t3 after t2 for numerator and rest of the occurences of t2 except the current t2. This is done because for example say a rare trigram (t3, after t1, t2) appears only once in your entire corpus, the formula f(tri)/f(bi) results in 1 or a “perfect” probability of 100%. But this pattern is just be a fluke, Subtracting 1 turns that “perfect” (but fluke) 1.0 into a 0. The __lambda__ function tries to determine how much to trust the trigram, bigram, and unigram models. Thus, we only favor the trigram model if it has enough repeated evidence to be truly trustworthy and avoid such overfitting.Coding A PoS Tagger from Scratch — A Statistical Part-of-Speech Tagger | NLP | Explaining the… was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.