Skip to content
ImagineWorld

Natural Language Processing

node_idnode-book_markov-models-with-python_chapter-07-natural-language-processing
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleNatural Language Processing
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Automatic speech recognition has a lot of potential applications, such as audio transcription, dictation, audio search, and virtual assistants. I am sure that everyone has interacted with at least one of the virtual assistants by now, be it Apple’s Siri, Amazon’s Alexa, or Google’s Assistant. At the core of all these speech recognition systems are a set of statistical models over the different words or sounds in a language. And since speech has a temporal structure, HMMs are the most natural framework to model it.

HMMs are virtually at the core of all speech recognition systems and the core concepts in modeling haven’t changed much in a long time. But over time, a lot of sophisticated techniques have been developed to build better systems. In the following sections, we will try to cover the main concepts leading to the development of these systems.

The first problem that we will look into is known as part-of-speech tagging (POS tagging). According to Wikipedia, POS tagging, also known as grammatical tagging or word-category disambiguation, is the process of marking up a word in a text as corresponding to a particular part of speech based on both its definition and its context, that is, its relationship with adjacent and related words in a phrase, sentence, or paragraph. A simpler version of this, which is usually taught in schools, is classifying words as noun, verbs, adjectives, and so on.

POS tagging is not as easy as it sounds because the same word can take different parts of speech in different contexts. A simple example of this is the word dogs. The word dogs is usually considered a noun, but in the following sentence, it acts like a verb:

The sailor dogs the hatch.

Correct grammatical tagging will reflect that dogs is used as a verb here, not as the more common plural noun. Grammatical context is one way to determine this; semantic analysis can also be used to infer that sailor and hatch implicate dogs as:

  • In the nautical context
  • An action applied to the object hatch

In teaching English, generally only nine parts of speech are taught: noun, verb, article, adjective, preposition, pronoun, adverb, conjunction, and interjection. But we can divide words into more categories and subcategories for finer-grained tagging. For example, nouns can be sub-categorized into plural, possessive, and singular. Similarly, verbs can be sub-categorized on the basis of tense, aspect, and so on. In general, computer-based POS tagging systems are able to distinguish 50 to 150 separate parts of speech for English. Work on stochastic methods for tagging Koine Greek has used over 1,000 parts of speech and found that about as many words were ambiguous there as in English.

For the code example, we will use the pomegranate library to build an HMM for POS tagging. Pomegranate can be installed by running the following on the command line:

pip install pomegranate

In this example, we will not go into the details of the statistical POS tagger. The data we are using is a copy of the Brown corpus. The Brown corpus contains 500 samples of English-language text, totaling roughly 1,000,000 words, compiled from works published in the United States in 1961.

Let’s start by defining some functions to read the data from the corpus files:

# Imports
import random
from itertools import chain
from collections import Counter, defaultdict
import numpy as np
import matplotlib.pyplot as plt
from pomegranate import State, HiddenMarkovModel, DiscreteDistribution
Sentence = namedtuple("Sentence", "words tags")
def read_data(filename):
"""
Function to read tagged sentence data.
Parameters
----------
filename: str
The path to the file from where to read the data.
"""
with open(filename, 'r') as f:
sentence_lines = [l.split("\n") for l in f.read().split("\n\n")]
return OrderedDict(((s[0], Sentence(*zip(*[l.strip().split("\t") for l in s[1:]])))
for s in sentence_lines if s[0])
def read_tags(filename):
"""
Function to read a list of word tag classes.
Parameters
----------
filename: str
The path to the file from where to read the tags.
"""
with open(filename, 'r') as f:
tags = f.read().split("\n")
return frozenset(tags)

Let’s now define a couple of classes, Subset and Dataset, to make it easier to handle the data:

class Subset(namedtuple("BaseSet", "sentences keys vocab X tagset Y N stream")):
"""
Class to handle a subset of the whole data. This is required when we split the
data into training and test sets.
"""
def __new__(cls, sentences, keys):
word_sequences = tuple([sentences[k].words for k in keys])
tag_sequences = tuple([sentences[k].tags for k in keys])
wordset = frozenset(chain(*word_sequences))
tagset = frozenset(chain(*tag_sequences))
N = sum(1 for _ in chain(*(sentences[k].words for k in keys)))
stream = tuple(zip(chain(*word_sequences), chain(*tag_sequences)))
return super().__new__(cls, {k: sentences[k] for k in keys}, keys, wordset,
word_sequences, tagset, tag_sequences, N, stream.__iter__)
def __len__(self):
return len(self.sentences)
def __iter__(self):
return iter(self.sentences.items())
class Dataset(namedtuple("_Dataset", "sentences keys vocab X tagset Y" +
"training_set testing_set N stream")):
"""
Class to represent the data in structured form for easy processing.
"""
def __new__(cls, tagfile, datafile, train_test_split=0.8, seed=112890):
tagset = read_tags(tagfile)
sentences = read_data(datafile)
keys = tuple(sentences.keys())
wordset = frozenset(chain(*[s.words for s in sentences.values()]))
word_sequences = tuple([sentences[k].words for k in keys])
tag_sequences = tuple([sentences[k].tags for k in keys])
N = sum(1 for _ in chain(*(s.words for s in sentences.values())))
# split data into train/test sets
_keys = list(keys)
if seed is not None:
random.seed(seed)
random.shuffle(_keys)
split = int(train_test_split * len(_keys))
training_data = Subset(sentences, _keys[:split])
testing_data = Subset(sentences, _keys[split:])
stream = tuple(zip(chain(*word_sequences), chain(*tag_sequences)))
return super().__new__(cls, dict(sentences), keys, wordset, word_sequences, tagset,
tag_sequences, training_data, testing_data, N, stream.__iter__)
def __len__(self):
return len(self.sentences)
def __iter__(self):
return iter(self.sentences.items())

Now, let’s try to initialize the Dataset class and see how it works:

>>> data = Dataset("tags-universal.txt", "brown-universal.txt", train_test_split=0.8)
>>> print("There are {} sentences in the corpus.".format(len(data)))
There are 57340 sentences in the corpus.
>>> print("There are {} sentences in the training set.".format(len(data.training_set)))
There are 45872 sentences in the training set.
>>> print("There are {} sentences in the testing set.".format(len(data.testing_set)))
There are 11468 sentences in the testing set.

Let’s now explore the data to better understand how our classes store the information. We have randomly selected the b100-38532 key:

>>> key = 'b100-38532'
>>> print("Sentence: {}".format(key))
Sentence: b100–38532
>>> print("words: {!s}".format(data.sentences[key].words))\
words: ('Perhaps', 'it', 'was', 'right', ';', ';')
>>> print("tags: {!s}".format(data.sentences[key].tags))
tags: ('ADV', 'PRON', 'VERB', 'ADJ', '.', '.')

We can also check the unique elements in the corpus:

>>> print("There are a total of {} samples of {} unique words in the corpus.".format(
data.N, len(data.vocab)))
There are a total of 1161192 samples of 56057 unique words in the corpus.
>>> print("There are {} samples of {} unique words in the training set.".format(
data.training_set.N, len(data.training_set.vocab)))
There are 928458 samples of 50536 unique words in the training set.
>>> print("There are {} samples of {} unique words in the testing set.".format(
data.testing_set.N, len(data.testing_set.vocab)))
There are 232734 samples of 25112 unique words in the testing set.
>>> print("There are {} words in the test set that are missing in the training set.".format(
len(data.testing_set.vocab - data.training_set.vocab)))
There are 5521 words in the test set that are missing in the training set.

We can also use the X and Y attributes of the Dataset class to access the words and the corresponding tags:

>>> for i in range(2):
... print("Sentence {}:".format(i + 1), data.X[i])
... print("Labels {}:".format(i + 1), data.Y[i], "\n")
Sentence 1: ('Mr.', 'Podger', ‘had', 'thanked', 'him', 'gravely', ',', 'and', 'now', 'he', 'made', 'use', 'of', 'the', 'advice', '.')
Labels 1: ('NOUN', 'NOUN', 'VERB', 'VERB', 'PRON', 'ADV', '.', 'CONJ', 'ADV', 'PRON', 'VERB', 'NOUN', 'ADP', 'DET', 'NOUN', '.')
Sentence 2: ('But', 'there', 'seemed', 'to', 'be', 'some', 'difference', 'of', 'opinion', 'as', 'to', 'how', 'far', 'the', 'board', 'should', 'go', ',', 'and', 'whose', 'advice', 'it', 'should', 'follow', '.')
Labels 2: ('CONJ', 'PRT', 'VERB', 'PRT', 'VERB', 'DET', 'NOUN', 'ADP', 'NOUN', 'ADP', 'ADP', 'ADV', 'ADV', 'DET', 'NOUN', 'VERB','VERB', '.', 'CONJ', 'DET', 'NOUN', 'PRON', 'VERB', 'VERB', '.')

We can also use the stream method to iterate over pairs of a word and its tag:

>>> for i, pair in enumerate(data.stream()):
... print(pair)
... if i > 3:
... break
('Podger', 'NOUN')
('had', 'VERB')
('thanked', 'VERB')
('him', 'PRON')

Now, just to compare the performance of our HMM model, let’s build a most frequent class tagger (MFC Tagger). We start by defining a function to count the pairs of tags and words:

def pair_counts(tags, words):
d = defaultdict(lambda: defaultdict(int))
for tag, word in zip(tags, words):
d[tag][word] += 1
return d
tags = [tag for i, (word, tag) in enumerate(data.training_set.stream())]
words = [word for i, (word, tag) in enumerate(data.training_set.stream())]

Now, let’s define the MFCTagger class:

FakeState = namedtuple('FakeState', 'name')
class MFCTagger:
missing = FakeState(name = '<MISSING>')
def __init__(self, table):
self.table = defaultdict(lambda: MFCTagger.missing)
self.table.update({word: FakeState(name=tag) for word, tag in table.items()})
def viterbi(self, seq):
"""This method simplifies predictions by matching the Pomegranate viterbi() interface"""
return 0., list(enumerate(["<start>"] + [self.table[w] for w in seq] + ["<end>"]))
tags = [tag for i, (word, tag) in enumerate(data.training_set.stream())]
words = [word for i, (word, tag) in enumerate(data.training_set.stream())]
word_counts = pair_counts(words, tags)
mfc_table = dict((word, max(tags.keys(), key=lambda key: tags[key])) for word, tags in word_counts.items())
mfc_model = MFCTagger(mfc_table)

Here are some helper functions to make predictions from the model:

def replace_unknown(sequence):
return [w if w in data.training_set.vocab else 'nan' for w in sequence]
def simplify_decoding(X, model):
_, state_path = model.viterbi(replace_unknown(X))
return [state[1].name for state in state_path[1:-1]]
>>> for key in data.testing_set.keys[:2]:
... print("Sentence Key: {}\n".format(key))
... print("Predicted labels:\n-----------------")
... print(simplify_decoding(data.sentences[key].words, mfc_model))
... print()
... print("Actual labels:\n--------------")
... print(data.sentences[key].tags)
... print("\n")

To check how well our model performs, let’s evaluate the accuracy of our model:

def accuracy(X, Y, model):
correct = total_predictions = 0
for observations, actual_tags in zip(X, Y):
# The model.viterbi call in simplify_decoding will return None if the HMM
# raises an error (for example, if a test sentence contains a word that
# is out of vocabulary for the training set). Any exception counts the
# full sentence as an error (which makes this a conservative estimate).
try:
most_likely_tags = simplify_decoding(observations, model)
correct += sum(p == t for p, t in zip(most_likely_tags, actual_tags))
except:
pass
total_predictions += len(observations)
return correct / total_predictions
>>> mfc_training_acc = accuracy(data.training_set.X, data.training_set.Y, mfc_model)
>>> print("Training accuracy mfc_model: {:.2f}%".format(100 * mfc_training_acc))
Training accuracy mfc_model: 95.72%
>>> mfc_testing_acc = accuracy(data.testing_set.X, data.testing_set.Y, mfc_model)
>>> print("Testing accuracy mfc_model: {:.2f}%".format(100 * mfc_testing_acc))
Testing accuracy mfc_model: 93.01%

Now, we will try to build a POS tagger using HMM and hopefully it will improve our prediction performance. We will first define some helper functions:

def unigram_counts(sequences):
return Counter(sequences)
tags = [tag for i, (word, tag) in enumerate(data.training_set.stream())]
tag_unigrams = unigram_counts(tags)
def bigram_counts(sequences):
d = Counter(sequences)
return d
tags = [tag for i, (word, tag) in enumerate(data.stream())]
o = [(tags[i],tags[i+1]) for i in range(0,len(tags)-2,2)]
tag_bigrams = bigram_counts(o)
def starting_counts(sequences):
d = Counter(sequences)
return d
tags = [tag for i, (word, tag) in enumerate(data.stream())]
starts_tag = [i[0] for i in data.Y]
tag_starts = starting_counts(starts_tag)
def ending_counts(sequences):
d = Counter(sequences)
return d
end_tag = [i[len(i)-1] for i in data.Y]
tag_ends = ending_counts(end_tag)

Let’s build the model now:

basic_model = HiddenMarkovModel(name="base-hmm-tagger")
tags = [tag for i, (word, tag) in enumerate(data.stream())]
words = [word for i, (word, tag) in enumerate(data.stream())]
tags_count=unigram_counts(tags)
tag_words_count=pair_counts(tags,words)
starting_tag_list=[i[0] for i in data.Y]
ending_tag_list=[i[-1] for i in data.Y]
starting_tag_count=starting_counts(starting_tag_list)#the number of times a tag occurred at the start
ending_tag_count=ending_counts(ending_tag_list) #the number of times a tag occurred at the end
to_pass_states = []
for tag, words_dict in tag_words_count.items():
total = float(sum(words_dict.values()))
distribution = {word: count/total for word, count in words_dict.items()}
tag_emissions = DiscreteDistribution(distribution)
tag_state = State(tag_emissions, name=tag)
to_pass_states.append(tag_state)
basic_model.add_states()
start_prob={}
for tag in tags:
start_prob[tag]=starting_tag_count[tag]/tags_count[tag]
for tag_state in to_pass_states :
basic_model.add_transition(basic_model.start,tag_state,start_prob[tag_state.name])
end_prob={}
for tag in tags:
end_prob[tag]=ending_tag_count[tag]/tags_count[tag]
for tag_state in to_pass_states :
basic_model.add_transition(tag_state,basic_model.end,end_prob[tag_state.name])
transition_prob_pair={}
for key in tag_bigrams.keys():
transition_prob_pair[key]=tag_bigrams.get(key)/tags_count[key[0]]
for tag_state in to_pass_states :
for next_tag_state in to_pass_states :
basic_model.add_transition(tag_state,next_tag_state,transition_prob_pair[(tag_state.name,next_tag_state.name)])
basic_model.bake()
>>> for key in data.testing_set.keys[:2]:
... print("Sentence Key: {}\n".format(key))
... print("Predicted labels:\n-----------------")
... print(simplify_decoding(data.sentences[key].words, basic_model))
... print()
... print("Actual labels:\n--------------")
... print(data.sentences[key].tags)
... print("\n")

>>> hmm_training_acc = accuracy(data.training_set.X, data.training_set.Y, basic_model)
>>> print("Training accuracy basic hmm model: {:.2f}%".format(100 * hmm_training_acc))
Training accuracy basic hmm model: 97.49%
>>> hmm_testing_acc = accuracy(data.testing_set.X, data.testing_set.Y, basic_model)
>>> print("Testing accuracy basic hmm model: {:.2f}%".format(100 * hmm_testing_acc))
Testing accuracy basic hmm model: 96.09%

We can see that the HMM-based model has been able to improve the accuracy of our model.

In the 1950s, Bell Labs was the pioneer in speech recognition. The early designed systems were limited to a single speaker and had a very limited vocabulary. After around 70 years of work, the current speech-recognition systems are able to work with speech from multiple speakers and can recognize thousands of words in multiple languages. A detailed discussion of all the techniques used is beyond the scope of this book as enough work has been done on each technique to have a book on itself.

But the general workflow for a speech-recognition system is to first capture the audio by converting the physical sound into an electrical signal using a microphone. The electrical signal generated by the microphone is analog and needs to be converted to a digital form for storage and processing, for which analog-to-digital converters are used. Once we have the speech in digital form, we can apply algorithms on it to understand the speech.

As mentioned before, most of the state-of-the-art speech-recognition systems still use the concept of Hidden Markov Models (HMM) as their core. This is based on the assumption that a speech signal is a stationary process in a short time period of a few milliseconds. Hence, the first step for the speech-recognition system is to split the signal into small fragments of around 10 milliseconds. Then the power spectrum of each fragment is mapped to a vector of real numbers, known as cepstral coefficients. The dimension of this vector is usually small, although more accurate systems usually work with more than 32 dimensions. The final output of the HMM model is a sequence of these vectors. Once we have these vectors, these groups of vectors are matched to one or more phonemes, which are a fundamental unit of speech. But for effectively matching these groups of vectors to phonemes, we need to train our system since there is a huge variation in the sound of phonemes between different speakers as well as different utterances from the same speaker. Once we have the sequence of phonemes, our system tries to guess the most likely word that could have possibly produced that sequence of phonemes.

As we can imagine, this whole detection process can be computationally quite expensive. For dealing with this complexity issue, modern speech-recognition systems use neural networks for feature-transformation and dimensionality-reduction before using the HMM for recognition. Another commonly used technique to reduce computation is to use voice activity detectors, which can detect the regions in the signal that contain speech. Using this information, we can design the recognizer to only spend computation on the parts of the signal that contain speech.

Fortunately, Python has a very developed ecosystem to work with speech recognition. In the next section, we will look into the different Python packages available for working with speech recognition.

The Python package hosting service, PyPI, has a lot of speech-recognition systems listed. Some of the most commonly used ones are as follows:

Some of these Python packages (such as apiai) offer more than just speech recognition and have implementations of natural language processing algorithms, using which the user can identify the speaker’s intent from speech. The other packages focus only on speech recognition, which can be used to convert audio to text.

In this chapter, we will use the SpeechRecognition package. We have chosen SpeechRecognition for two reasons:

  • It has a very simple-to-use API to directly access and process audio signals. For other packages, we usually need to write small scripts for them to be able to access files.
  • It is a wrapper over several popular speech APIs and therefore is extremely flexible, and multiple services can be used without making much change to our code.

So, to start using SpeechRecognition, we need to install the package. Since it’s hosted on PyPI, it can be installed directly using pip:

pip install SpeechRecognition

The most important class in the package is the Recognizer class as it handles most of the recognition tasks. We can specify different settings and functionality for recognizing speech from an audio source while initializing the class.

The Recognizer class can be initialized very easily without passing any argument:

>>> import speech_recognition as sr
>>> r = sr.Recognizer()

One important thing to keep in mind while using these methods is that since most of these recognition services are offered by companies through web APIs, we need an internet connection to access these services. Also, some of these services only allow usage after registering with them online. Out of these seven, only recognize_sphinx works offline.

Out of all these web APIs, only Google’s Web Speech API works without any registration or API key. Therefore, to keep things simple, we will use that in the rest of this chapter.

The recognize methods throw RequestError if the server is unavailable, there is no internet connection, or the API quota limits are met.

The next thing that we would need in order to do any recognition is some audio data. SpeechRecognition provides direct functionality to either work with an audio file or use audio from an attached microphone. In the following sections, we will look into both of these methods.

To start working with audio files, we first need to download one. For the following example, we will use the harvard.wav file, which can be downloaded from https://raw.githubusercontent.com/realpython/python-speech-recognition/master/audio_files/harvard.wav.

Make sure to save the audio files in the same directory from where the Python interpreter is running. Otherwise, for the following code, the path to the files will need to be modified.

For working with audio files, SpeechRecognition has the AudioFile class, which can be used for reading and working with audio files. We can use the record method of AudioFile to process the contents of the audio file before it can be used with the Recognizer class:

>>> harvard = sr.AudioFile('harvard.wav')
>>> with harvard as source:
... audio = r.record(source)

The context manager opens the audio and records its content into audio, which is an instance of AudioFile. We can check it by calling the type method on audio:

>>> type(audio)
<class 'speech_recognition.AudioData'>

Now, once we have an AudioFile instance, we can call any of the recognize methods with it as an argument. The recognize method would call the specific web API to translate the speech from the audio file and return the following text:

>>> r.recognize_google(audio)
'the stale smell of old beer lingers it takes heat
to bring out the odor a cold dip restores health and
zest a salt pickle taste fine with ham tacos al
Pastore are my favorite a zestful food is the hot
cross bun'

In this case, we transcribed the whole audio file, but what if we want to only translate a specific part of the audio file? This can be done by passing additional arguments to the record method:

>>> with harvard as source:
... audio_part = r.record(source, duration=4)
>>> r.recognize_google(audio_part)
'the stale smell of old beer lingers'

The record method keeps a pointer in the audio file to point at the position until which recording has happened. So, if we do another record of four seconds on the same file, it will record from the four-second mark to the eight-second mark of the original audio file.

In the preceding example, we transcribed a part of the audio file but the starting point was the start of the file. What if we want to start at a different time point? It can be done by passing another argument, offset, to the record method:

>>> with harvard as source:
... audio_offset = r.record(source, offset=4, duration=3)
>>> recognizer.recognize_google(audio_offset)
'it takes heat to bring out the odor'

If you listen to the harvard.wav file, you will realize that the recording is done in perfect conditions without any external noise, but that is usually not the case in real-life audio. Let’s try to transcribe another audio signal, jackhammer.wav, which can be downloaded from https://raw.githubusercontent.com/realpython/python-speech-recognition/master/audio_files/jackhammer.wav. If you listen to the audio file, you can notice that it has a lot of background noise. Let’s try to transcribe this file and see how the recognizer performs:

>>> jackhammer = sr.AudioFile('jackhammer.wav')
>>> with jackhammer as source:
... audio_jack = r.record(source)
>>> r.recognize_google(audio_jack)
'the snail smell of old gear vendors'

As we can see, the transcription is way off. In such cases, we can use the adjust_for_ambient_noise method provided in the Recognizer class to calibrate our audio signal with the noise.

adjust_for_ambient_noise by default uses the first one second of data to do the calibration, but we can change that by passing a duration argument to it:

>>> with jackhammer as source:
... r.adjust_for_ambient_noise(source, duration=1)
... audio = r.record(source)
>>> r.recognize_google(audio)
'still smell of old beer vendors'

If we don’t want to lose much information, we can reduce the value of the duration argument, but that can result in a poorer calibration. As we can see, the transcription is still not perfect, but it is much better than when we didn’t use adjust_for_ambient_noise. We can actually get better results by trying to clean the noise from the audio using signal processing techniques, which are outside the scope of this book.

Another thing that we can do in such cases is to look at all the most likely transcriptions by the recognizer. It can be done by using the show_all argument while calling the recognize method:

>>> r.recognize_google(audio, show_all=True)
{'alternative': [
{'transcript': 'the snail smell like old Beer Mongers'},
{'transcript': 'the still smell of old beer vendors'},
{'transcript': 'the snail smell like old beer vendors'},
{'transcript': 'the stale smell of old beer vendors'},
{'transcript': 'the snail smell like old beermongers'},
{'transcript': 'destihl smell of old beer vendors'},
{'transcript': 'the still smell like old beer vendors'},
{'transcript': 'bastille smell of old beer vendors'},
{'transcript': 'the still smell like old beermongers'},
{'transcript': 'the still smell of old beer venders'},
{'transcript': 'the still smelling old beer vendors'},
{'transcript': 'musty smell of old beer vendors'},
{'transcript': 'the still smell of old beer vendor'}
], 'final': True}

Using this, we can then choose the best transcription for our specific problem.

In the previous section, we used the recognizer methods to transcribe speech from audio files. In this section, we will do a transcription using speech recorded from our microphone.

But before we get into that, we will need to install an additional package, called PyAudio. It is also available on PyPI and can be installed directly using pip: pip install PyAudio.

In the previous section, for working with audio files, we were using the AudioFile class, but for working with a microphone, we will need to use the Microphone class. Most of the recognition API still remains the same. Let’s take a simple example to understand how it works:

>>> import speech_recognition as sr
>>> r = sr.Recognizer()
>>> mic = sr.Microphone()
>>> with mic as source:
... r.adjust_for_ambient_noise(source)
... audio = r.listen(source)

Similarly to how we had initialized the AudioFile class in the previous section, we need to initialize the Microphone class this time. Also, instead of record, we need to call the listen method to record the audio. The Python interpreter would wait for a while to record audio when executing the previous code block. Try saying something into the microphone. Once the interpreter prompt returns, we can call the recognize method to transcribe the recorded audio:

>>> r.recognize_google(audio)
'hello world' # This would depend on what you said in the microphone

In this chapter, we looked into two of the major applications of HMMs: POS tagging and speech recognition. We coded the POS tagger using a most-frequent tag algorithm and used the pomegranate package to build one based on HMM. We compared the performance using both these methods and saw that an HMM-based approach outperforms the most-frequent tag method. Then, we used the SpeechRecognition package to transcribe audio to text using Google’s Web Speech API. We looked into using the package with both audio files and live audio from a microphone.

In the next chapter, we will explore more applications of HMMs, specifically in the field of image recognition.