Instructions
In this assignment, you will gain experience working with Markov models on text.
A skeleton file homework7.py containing empty definitions for each question has been provided. Since portions of this assignment will be graded automatically, none of the names or function signatures in this file should be modified. However, you are free to introduce additional variables or functions if needed.
You may import definitions from any standard Python library, and are encouraged to do so in case you find yourself reinventing the wheel.
You will find that in addition to a problem specification, most programming questions also include a pair of examples from the Python interpreter. These are meant to illustrate typical use cases, and should not be taken as comprehensive test suites.
You are strongly encouraged to follow the Python style guidelines set forth in PEP 8, which was written in part by the creator of Python. However, your code will not be graded for style. Once you have completed the assignment, you should submit your file on Eniac using the following turnin command, where the flags -c and -p stand for “course” and “project”, respectively.
You may submit as many times as you would like before the deadline, but only the last submission will be saved. To view a detailed listing of the contents of your most recent submission, you can use the following command, where the flag -v stands for “verbose”.
1. Markov Models [45 points]
In this section, you will build a simple language model that can be used to generate random text resembling a source document. Your use of external code should be limited to built-in Python modules, which excludes, for example, NumPy and NLTK.
- [5 points] Write a simple tokenization function tokenize(text) which takes as input a string of text and returns a list of tokens derived from that text. Here, we define a token to be a contiguous sequence of non-whitespace characters, with the exception that any punctuation mark should be treated as an individual token. Hint: Use the built-in constant string.punctuation, found in the string
>>> tokenize(” This is an example. “) >>> tokenize(“‘Medium-rare,’ she said.”) [‘This’, ‘is’, ‘an’, ‘example’, ‘.’] [“‘”, ‘Medium’, ‘-‘, ‘rare’, ‘,’, “‘”,
‘she’, ‘said’, ‘.’]
- [5 points] Write a function ngrams(n, tokens) that produces a list of all G-grams of the specified size from the input token list. Each G-gram should consist of a 0-element tuple (context, token), where the context is itself an &GИ/’-element tuple comprised of the GИ/ words preceding the current token. The sentence should be padded with
GИ/ “<START>” tokens at the beginning and a single “<END>” token at the end. If G; /, all contexts should be empty tuples. You may assume that Gд/.
>>> ngrams(1, [“a”, “b”, “c”]) >>> ngrams(3, [“a”, “b”, “c”])
[((), ‘a’), ((), ‘b’), ((), ‘c’), [((‘<START>’, ‘<START>’), ‘a’),
((), ‘<END>’)] ((‘<START>’, ‘a’), ‘b’),
>>> ngrams(2, [“a”, “b”, “c”]) ((‘a’, ‘b’), ‘c’),
[((‘<START>’,), ‘a’), ((‘a’,), ‘b’), ((‘b’, ‘c’), ‘<END>’)] ((‘b’,), ‘c’), ((‘c’,), ‘<END>’)]
- [5 points] In the NgramModel class, write an initialization method __init__(self, n) which stores the order G of the model and initializes any necessary internal variables.
Then write a method update(self, sentence) which computes the G-grams for the input sentence and updates the internal counts. Lastly, write a method
prob(self, context, token) which accepts an &GИ/’-tuple representing a context
and a token, and returns the probability of that token occuring, given the preceding context.
- [10 points] In the NgramModel class, write a method random_token(self, context) which returns a random token according to the probability distribution determined by the given context. Specifically, let 3 ; ⅩM/*M0*—*MGⅪ be the set of tokens which can occur in the given context, sorted according to Python’s natural lexicographic ordering, and let .гK: / be a random number between . and /. Your method should return the token MB such that
.BИ/ /&MCУamlrcvr’гK: .B /&MCУamlrcvr’,
C;/ C;/
You should use a single call to the random.random() function to generate K.
>>> m = NgramModel(1) >>> m = NgramModel(2)
>>> m.update(“a b c d”) >>> m.update(“a b c d”)
>>> m.update(“a b a b”) >>> m.update(“a b a b”)
>>> random.seed(1) >>> random.seed(2)
>>> [m.random_token(()) >>> [m.random_token((“<START>”,)) for i in range(25)] for i in range(6)]
[‘<END>’, ‘c’, ‘b’, ‘a’, ‘a’, ‘a’, ‘b’, [‘a’, ‘a’, ‘a’, ‘a’, ‘a’, ‘a’]
‘b’, ‘<END>’, ‘<END>’, ‘c’, ‘a’, ‘b’, >>> [m.random_token((“b”,))
‘<END>’, ‘a’, ‘b’, ‘a’, ‘d’, ‘d’, for i in range(6)]
‘<END>’, ‘<END>’, ‘b’, ‘d’, ‘a’, ‘a’] [‘c’, ‘<END>’, ‘a’, ‘a’, ‘a’, ‘<END>’]
- [10 points] In the NgramModel class, write a method random_text(self, token_count) which returns a string of space-separated tokens
chosen at random using the random_token(self, context) method. Your starting context should always be the &GИ/’-tuple (“<START>”, …, “<START>”), and the context should be updated as tokens are generated. If G; /, your context should always be the empty tuple. Whenever the special token “<END>” is encountered, you should reset the context to the starting context.
- [5 points] Write a function create_ngram_model(n, path) which loads the text at the given path and creates an G-gram model from the resulting data. Each line in the file should be treated as a separate sentence.
# No random seeds, so your results may vary
>>> m = create_ngram_model(1, “frankenstein.txt”); m.random_text(15)
‘beat astonishment brought his for how , door <END> his . pertinacity to I felt’
>>> m = create_ngram_model(2, “frankenstein.txt”); m.random_text(15)
‘As the great was extreme during the end of being . <END> Fortunately the sun’
>>> m = create_ngram_model(3, “frankenstein.txt”); m.random_text(15)
‘I had so long inhabited . <END> You were thrown , by returning with greater’
>>> m = create_ngram_model(4, “frankenstein.txt”); m.random_text(15)
‘We were soon joined by Elizabeth . <END> At these moments I wept bitterly and’
- [5 points] Suppose we define the perplexity of a sequence of F tokens ⅩP/*P0*—*PF Ⅺ to be
ИИИИИИИИИИИИИИИ
ИИИИИИИИИИИИИИИ
, /
- , /&P/*P0*—*PF ‘
For example, in the case of a bigram model under the framework used in the rest of the assignment, we would generate the bigrams
Ⅹ&P. ; ⅩQR?PRⅪ*P/‘*&P/*P0‘*—*&PFИ/*PF ‘*&PF *PF)/ ; ⅩCLBⅪ’Ⅺ, and would then compute the perplexity as
GИИИИИИИИИИИИИИ
- F,)/ / ,
FD)/
B;/ /&PBУPBИ/’
Intuitively, the lower the perplexity, the better the input sequence is explained by the model. Higher values indicate the input was “perplexing” from the model’s point of view, hence the term perplexity.
In the NgramModel class, write a method perplexity(self, sentence) which computes the G-grams for the input sentence and returns their perplexity under the current model. Hint: Consider performing an intermediate computation in log-space and reexponentiating at the end, so as to avoid numerical overflow.
Reviews
There are no reviews yet.