**Introduction**

In lecture, we saw how Markov models capture the statistical relationships present in a language like English. These models allow us to go beyond simplistic observations, like the frequency with which specific letters or words appear in a language, and instead to capture the relationships between words or letters in sequences. As a result, we can not only appreciate that the letter “q” appears in text at a certain rate, but also that it is virtually always followed by a “u.” Similarly, “to be” is a much more likely word sequence than “to is.”

In class, we discussed how to generate realistic-looking, if nonsensical, text, by randomly choosing words while keeping in mind the influence of the preceding words. Another application of Markov models is in analyzing actual text and assessing the likelihood that a particular person uttered it. That is one of the objects of this assignment.

In lecture, we also talked about hash tables: data structures that store associations between keys and values (exactly like dictionaries in Python) and provide an efficient means of looking up the value associated with a given key. Hash tables find a desired entry rapidly by limiting the set of places where it can be. They avoid “hot spots,” even with data that might otherwise all seem to belong in the same place, by dispersing the data through hashing.

These benefits are why Python, in fact, uses hash tables behind the scenes in its implementation of dictionaries. The concept of hashing is so fundamental and useful in so many ways, however, that now is the time to peel back the curtain and see how dictio- naries work by building your own. That is the other object of this assignment.

Apart from developing an appreciation of how hashing and hash tables work, you will also be better prepared if ever you need to write your own hash table in the future. For instance, you may use a language (like C) that does not feature a built-in hash table. Or, the hash table that is used by a language, like Python, may interact poorly with your particular data, obligating you to design a custom-tailored one. After completing this assignment, you should consider hash tables to be in your programming repertoire.

**Getting started**

Follow these start-up instructions.

**Hash tables and Linear Probing**

In the interest of building and testing code one component at a time, we will start by building a hash table. Once we have gotten this module up and running, we will use it in our construction of a Markov model for speaker attribution. The hash table imple- mentation will account for approximately two-thirds of the points for this assignment; the speaker recognition application of the hash table will account for the remainder.

There are different types of hash tables; for this assignment, we will use the type that is implemented with linear probing. We de- scribed how these work in lecture; here is a reference on the topic.

Please look at Hash_Table.py. This file must implement a hash table that uses linear probing. The class Hash_Table must have:

A hash function that takes in a string and returns a hash value. Use the standard string hashing function.

A constructor that takes in the fixed number of cells to use and a default value to return when looking up a key that has not been inserted. It must create a list of empty cells with the specified length.

lookup, which takes in a key and returns its associated value: either the one stored in the hash table, if present, or the default value, if not.

update, which takes in a key and value, and updates the existing value for that key with the new value or inserts the key-value pair into the hash table, as appropriate.

A hash table built on linear probing does not have unlimited capacity, since each cell can only contain a single value and there are a fixed number of cells. But, we do not want to have to anticipate how many cells might be used for a given hash table in advance and hard-code that number in for the capacity of the hash table. Therefore, we will take the following approach: the cell capacity passed into the constructor will represent the initial size of the table. If the fraction of occupied cells ever grows beyond the con- stant TOO_FULL, then we will perform an operation called rehashing: We will expand the size of our hash table, and migrate all the data into their proper locations in the newly-expanded hash table (i.e., each key-value pair is hashed again, with the hash function now considering the new size of the table). We will grow the size of the table by GROWTH_RATIO; for instance, if this is 2, the size of the hash table will double each time it becomes too full.

Once you complete your hash table implementation, you can (and should) test it until you are convinced it is working properly.

**Markov model for sequences of letters**

Next, we will use this hash table to track the number of times letter sequences appear in a text.

A k-th order Markov model tracks the last k letters as the context for the present letter. We will build a class called Markov that will work for any value of k provided. This class, natrually, resides in Markov.py.

While we use the term “letter,” we will actually work with all characters, whether they be letters, digits, spaces, or punctuation, and will distinguish between upper- and lower-case letters.

We will discuss how we will use this class to help identify the speaker of a particular text. Then, we will circle back and explain how it learns the characteristics of a given speaker in the first place.

**Determining the likelihood of unidentified text**

Given a string of text from an unidentified speaker, we will use the Markov model to assess the likelihood that it was uttered by the particular speaker to which that particular Markov model corresponds. If we have built models for different speakers, then we will have likelihood values for each, and will choose the speaker with the highest likelihood as the probable source.

As we saw in lecture, these probabilities can be very small, since they take into account every possible phrase of a certain length that a speaker could have uttered. Therefore, we expect that all likelihoods are low in an absolute sense, but will still find their relative comparisons to be meaningful. Very small numbers are problematic, however, because they tax the computer’s level of precision for floating-point values. The solution we will adopt for this problem is to use log probabilities instead of the probabilities themselves. This way, even a very small number is represented by a negative value in the range between zero and, for instance, -20. If our log probabilities are negative and we want to determine which probability is more likely, will the greater number (the one closer to zero) represent the higher or lower likelihood, based on how logarithms work?

Note that when we use Python’s built-in log function, we will calculate natural logarithms. Your code should use this base for its logarithms. While any base would suffice to ameliorate our real number precision problem, we will be comparing your results to

the results from our implementation, which itself uses natural logs.

As we scan down the string of text from the unidentified speaker, at every character, we will consider it and the k characters that preceded it in our k-th order Markov model. We will use the model to calculate the probability that the current character would have been uttered by the modeled speaker, given the context of the previous k characters. This represents a likelihood for that par- ticular letter. Were we calculating a probability for the entire phrase, we would multiply together all the per-letter probabilities to yield the value for the entire phrase. But, since we are working with log probabilities…?

What is the probability of a given character in the context of the last k? One reasonable way to calculate this is to look at how many times we have seen the modeled speaker utter the k preceding characters followed by the current character (a k + 1 length sequence), divided by the number of times we have observed the speaker to have uttered the k preceding characters (a k-letter sequence). In the count we use for the denominator, we only look at the k preceding characters in a row, but each time they appeared, they were fol- lowed by some other character. Thus, we are taking the ratio of all the times they were followed by the current character over all the times they were followed by some character, to yield the likelihood that the current character was that “some character.” As an ex- ample (k=2), if we have the sequence “The”, we divide the number of times we have seen “The” by the number of times we have seen “Th”. Each of those occurrences of “Th” may have been part of “The”, but also could have been part of “Tha”, “Thi”, “Tho”, and “Thu”.

While this seems reasonable, we need to keep in mind that we are constructing the model with one set of text and using it to evalu- ate other text. The specific letter sequences that appear in that new text are not necessarily guaranteed ever to have appeared in the original text. Consequently, we are at risk of dividing by zero.

It turns out that there is a theoretically-justifiable solution to this issue, called Laplace smoothing. We modify the simple equation above by adding to the denominator the number of unique characters that appeared in the original text we used for modeling. For instance, if every letter in the alphabet appeared in the text, we add 26. (In practice, the number is likely to be greater, because we distinguish between upper- and lower-case letters, and consider spaces, digits, and punctuation as well.) Because we have added this constant to the denominator, it will never be zero. Next, we must compensate for the fact that we have modified the denominator; a theoretically sound way to balance this is to add one to the numerator. Symbolically, if N is the number of times we have observed the k preceding letters and M is the number of times we have observed those letters followed by the present letter, and S is the size of the “alphabet” of possible characters, then our probability is (M+1)/(N+S).

One final complication: what do we do when we do not have k characters of context available? For instance, the first k characters in the sequence will have fewer preceding letters than we need for our analysis. To address this, we will “wrap around”: we will think of the string circularly, and glue the end of the string on to the beginning to provide a source of the needed context. For instance, if k = 2, and we have the string “ABCD”, then the two letters of context for D will be BC, but the two letters of context for A will wrap around and be CD.

**Learning the statistics of text**

Now that we have identified the information we need for our end goal of calculating probabilities, we will briefly discuss how to col- lect it.

To learn the statistical characteristics of a particular speaker, we will be given a string of text that they have uttered. Using this string, and based on the previous section, determine the information you need to collect about the frequencies of characters, and the contexts in which they appear. Then, consider the data structure to use to hold this information.

You may find it helpful to think back to the example of modeling rigged dice in class and the tables we used to capture their sta- tistics. (Later in the lecture, we discussed text generation, and an exotic optimization involving duplicate list entries. This optimiza- tion helped with generation of text, not recognition of text, so do not be misled into trying to apply that approach here.)

There was one relevant insight we encountered when we switched from dice to text, however: because dice rolls are numeric, a sim- ple matrix was suitable. Text, on the other hand, lends itself to being the key in a dictionary, and so we used a dictionary where the key was the previous word or words of context and the value was information on what might follow.

Hash tables and Python dictionaries support the same operations and benefit from the same highly-efficient implementation. Be- cause the goal of this assignment is to give you practice both implementing and using hash tables, you should not use a stock Python dictionary, but rather, your own hash table implementation, for your data structure.

As we determine the counts of occurrences of sequences, we again will encounter the issue of insufficient context for the early let-

ters in a string. As before, the solution is to “wrap around.”

Structuring your code

Your Markov class will have the following methods:

A constructor that takes in a value of k and a string of text to create the model. It will create one or more hash tables with HASH_CELLS many cells; we have provided this constant to be a suitable number that is a good starting size for your hash tables, although they will have to grow significantly to accommodate all the statistics you will learn as you scan over the sample text we have provided.

log_probability is a method that takes in a new string and returns the log probability that the modeled speaker uttered it, using the approach described in a prior section.

While these are the only methods whose details we are dictating, your code will benefit dramatically from a careful selection of helper functions to encapsulate algorithms that are used in multiple scenarios.

Using the Markov class

While the log_probability method yields the likelihood that a particular speaker uttered a specified string of text, this probabili- ty may be misleading because it depends upon the length of the string. Because there are many more possible strings of a greater length, and these probabilities are calculated across the universe of all possible strings of the same length, we should expect to see significant variance in these values for different phrases. To reduce this effect, we will divide all of our probabilities by the length of the string, to yield normalized ones. To be clear, this division does not occur in log_probability, but rather, in the code we are about to write. Also, note that we will be calculating log probabilities, under different models, for the same string. Thus, string length differences are not a factor during a single run of our program. Rather, we choose to normalize in this fashion because we want outputs for different runs to be more directly comparable when they may pertain to different length quotes being analyzed.

Your final task is to complete the function identify_speaker outside of the Markov class. This function is called by the main block with three strings and a value of k. You must learn models for the speakers that uttered the first two strings, calculate the nor- malized log probabilities that those two speakers uttered the third string, and return these two probabilities in a tuple (with the first entry being the probability of the first speaker). Finally, you must compare the probabilities and place in the third slot of your re- turned tuple, aconclusion of which speaker was most likely. This conclusion should be either the string “A” or “B”.. We will call your function and print output, which should look like:

Speaker A: -2.49045540512 Speaker B: -2.44619679933

Conclusion: Speaker B is most likely

Testing your code

We have provided, in your pa4 directory, a set of files containing text from United States presidential debates from the 2004 and 2008 general elections. In the 2004 election, George W. Bush debated John Kerry; in the 2008 debates, Barack Obama went up against John McCain. We have provided single files for Bush, Kerry, Obama, and McCain to use to build models. These files con- tain all the text uttered by the corresponding candidate from two debates. We have also provided directories from the third debates of each election year, containing many files, appropriately labeled, that have remarks made by one of the candidates.

The following command line will allow you to test with the specified files:

python3 Markov.py speakerA.txt speakerB.txt unidentified.txt k

where the first two file names represent the text files that will be used to build the two models, and the third file name is that of the file containing text whose speaker we wish to determine using the Markov approach. THe final argument is the order (k) of the Markov models to use, an integer.

You can run your program by hand to see the determination it makes for a particular file. But, this is an opportunity to practice the

shell. We automated the testing of our code against all the files pertaining to a particular candidate by using a for loop, appending the results of our program to an output file, and counting the number of times we concluded that Speaker A or Speaker B uttered the phrase. The material we discussed on the shell is sufficient to accomplish this.

You should expect that testing against the entire set of quotes from a given candidate will take a few minutes, and that a second-or- der Markov model (which we found to provide the best overall results) will do significantly better than chance, although not

perfectly.

**Submission**

Follow these submission instructions.

**Acknowledgement**

This assignment is based on one developed by Rob Schapire with contributions from Kevin Wayne.