-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlanguageModels.py
More file actions
479 lines (428 loc) · 20.5 KB
/
Copy pathlanguageModels.py
File metadata and controls
479 lines (428 loc) · 20.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
from collections import defaultdict
from math import log, pow
import argparse
"""
Given a path to the corpus file, process it with our without unk for the models to access it
"""
class ProcessCorpus:
corpusArray = []
wordCountList = {}
totalNumWords = 0
unk = '<unk>'
startSymbol = '<s>'
stopSymbol = '</s>'
"""
Initialialize class objects and process corpus file
"""
def __init__(self, corpusPath, unk=False):
self.corpusPath = corpusPath
self.wordCountList = defaultdict(lambda: 0)
self.totalNumWords = 0
if unk:
self.process_with_unk()
else:
self.process_default()
"""
Process the corpus file, with unk symbols for rare words (count == 1)
"""
def process_with_unk(self):
f = open(self.corpusPath)
self.corpusArray = []
self.totalNumWords = 0
self.wordCountList = defaultdict(lambda: 0)
wordCountListHelper = defaultdict(lambda: 0)
for sentence in f:
words = sentence.split()
for word in words:
wordCountListHelper[word] = wordCountListHelper[word] + 1
self.totalNumWords += 1
rarewords = [key for key, count in wordCountListHelper.items() if count == 1]
f.seek(0)
for sentence in f:
words = sentence.split()
newsentence = []
for word in words:
if word in rarewords:
newsentence.append(self.unk)
self.wordCountList[self.unk] = self.wordCountList[self.unk] + 1
else:
newsentence.append(word)
self.wordCountList[word] = self.wordCountList[word] + 1
self.corpusArray.append(newsentence)
"""
Process the corpus file as is
"""
def process_default(self):
f = open(self.corpusPath)
self.corpusArray = []
self.totalNumWords = 0
self.wordCountList = defaultdict(lambda: 0)
for sentence in f:
sentence = sentence.strip()
words = sentence.split()
self.corpusArray.append(words)
for word in words:
self.wordCountList[word] = self.wordCountList[word] + 1
self.totalNumWords += 1
"""
This class contains the unigram model for the subsequent interpolation
"""
class UnigramModel:
"""
Unigram model already gets the information it needs (word count) from the corpus data
which contains the ProcessCorpus object
"""
def __init__(self, corpusData):
self.trainingCorpus = corpusData
"""
Scores the probability of a given sentence / word (if sentence contains one word
"""
def score_probability_of_sentence(self, sentence):
score = 0.0
for word in sentence:
wordcount = self.trainingCorpus.wordCountList[word]
# log(a/b) = log(a) - log(b)
if wordcount > 0:
score += (log(wordcount, 2) - log(self.trainingCorpus.totalNumWords, 2))
else:
wordcount = self.trainingCorpus.wordCountList[ProcessCorpus.unk]
score += (log(wordcount, 2) - log(self.trainingCorpus.totalNumWords, 2))
return score
"""
This class represents the bigram model which would later be used for interpolation
"""
class BigramModel:
def __init__(self, corpusData):
self.trainingCorpus = corpusData
self.bigramCountList = defaultdict(lambda: 0)
self.train_bigram_model()
"""
Splits corpus into bigrams for training the model as well as storing counts to be used later
"""
def train_bigram_model(self):
for sentence in self.trainingCorpus.corpusArray:
unigram1 = ProcessCorpus.startSymbol
self.trainingCorpus.wordCountList[unigram1] = self.trainingCorpus.wordCountList[unigram1] + 1
unigram2 = ''
for word in sentence:
unigram2 = word
self.bigramCountList[(unigram1,unigram2)] = self.bigramCountList[(unigram1,unigram2)] + 1
unigram1 = word
unigram2 = ProcessCorpus.stopSymbol
self.bigramCountList[(unigram1, unigram2)] = self.bigramCountList[(unigram1, unigram2)] + 1
"""
Scores the log probability of a given sentence using the information computed in the train function
Using Laplace smoothing to prevent undefined probability in zero history situations
"""
def score_probability_of_sentence(self, sentence):
score = 0.0
unigram1 = ProcessCorpus.startSymbol
unigram2 = ''
for word in sentence:
unigram2 = word
bigramFrequency = self.bigramCountList[(unigram1, unigram2)]
#Used laplace smoothing #NOTE
score += (log(bigramFrequency + 1, 2) - (log(self.trainingCorpus.wordCountList[unigram1] + len(self.trainingCorpus.wordCountList), 2)))
unigram1 = word
unigram2 = ProcessCorpus.stopSymbol
bigramFrequency = self.bigramCountList[(unigram1, unigram2)]
score += (log(bigramFrequency + 1, 2) - (log(self.trainingCorpus.wordCountList[unigram1] + len(self.trainingCorpus.wordCountList), 2)))
return score
"""
Score the MLE probability of a bigram from this model's trained data
"""
def score_mle_probability(self, bigram):
score = 0.0
unigram1, unigram2 = bigram
bigramFrequency = self.bigramCountList[bigram]
# Used laplace smoothing here #NOTE
score += (log(bigramFrequency + 1, 2) - (log(self.trainingCorpus.wordCountList[unigram1] + len(self.trainingCorpus.wordCountList), 2)))
return score
"""
This class represents the trigram model which would later be used for interpolation
"""
class TrigramModel:
def __init__(self, corpusData, relatedBigram, delta=0):
self.trainingCorpus = corpusData
self.trigramCountList = defaultdict(lambda: 0)
self.delta = delta
self.relatedBigram = relatedBigram
self.train_trigram_model()
"""
Splits corpus into trigram for training the model as well as storing counts to be used later
"""
def train_trigram_model(self):
for sentence in self.trainingCorpus.corpusArray:
unigram1 = ProcessCorpus.startSymbol
unigram2 = ProcessCorpus.startSymbol
unigram3 = ''
self.relatedBigram.bigramCountList[(unigram1, unigram2)] = self.relatedBigram.bigramCountList[(unigram1, unigram2)] + 1
for word in sentence:
unigram3 = word
self.trigramCountList[(unigram1, unigram2, unigram3)] = self.trigramCountList[(unigram1, unigram2, unigram3)] + 1
unigram1 = unigram2
unigram2 = word
unigram3 = ProcessCorpus.stopSymbol
self.trigramCountList[(unigram1, unigram2, unigram3)] = self.trigramCountList[(unigram1, unigram2, unigram3)] + 1
"""
Scores the log probability of a given sentence using the information computed in the train function
Using Laplace smoothing to prevent undefined probability in zero history situations
"""
def score_probability_of_sentence(self, sentence):
score = 0.0
unigram1 = ProcessCorpus.startSymbol
unigram2 = ProcessCorpus.startSymbol
unigram3 = ''
for word in sentence:
unigram3 = word
trigramFrequency = self.trigramCountList[(unigram1, unigram2, unigram3)]
bigramFrequency = self.relatedBigram.bigramCountList[(unigram1, unigram2)]
#Used laplace smoothing #NOTE
score += (log((trigramFrequency + 1) - self.delta, 2) - (log(bigramFrequency + len(self.trainingCorpus.wordCountList), 2)))
unigram1 = unigram2
unigram2 = word
unigram3 = ProcessCorpus.stopSymbol
trigramFrequency = self.trigramCountList[(unigram1, unigram2, unigram3)]
bigramFrequency = self.relatedBigram.bigramCountList[(unigram1, unigram2)]
score += (log((trigramFrequency + 1) - self.delta, 2) - (log(bigramFrequency + len(self.trainingCorpus.wordCountList), 2)))
return score
"""
Scores the MLE probability of a given trigram from the trained data
"""
def score_mle_probability(self, trigram):
score = 0.0
unigram1, unigram2, unigram3 = trigram
trigramFrequency = self.trigramCountList[trigram]
bigramFrequency = self.relatedBigram.bigramCountList[(unigram1, unigram2)]
#Used laplace smoothing here #NOTE
score += (log((trigramFrequency + 1) - self.delta, 2) - (log(bigramFrequency + len(self.trainingCorpus.wordCountList), 2)))
return score
"""
This model interpolates a unigram, bigram and trigram model with some hyperparameters as weights for each model
"""
class InterpolationModel:
"""
initialize individual models with training done in initialization
"""
def __init__(self, corpusData, uniweight=0.2, biweight=0.3, triweight=0.5):
self.uniweight = uniweight
self.biweight = biweight
self.triweight = triweight
self.trainingData = corpusData
self.unigramModel = UnigramModel(corpusData)
self.bigramModel = BigramModel(corpusData)
self.trigramModel = TrigramModel(corpusData, self.bigramModel, 0)
"""
Score a sentence with the interpolation of the three models and weights
"""
def score_sentence(self, sentence):
score = 0.0
score += self.uniweight * self.unigramModel.score_probability_of_sentence(sentence)
score += self.biweight * self.bigramModel.score_probability_of_sentence(sentence)
score += self.triweight * self.trigramModel.score_probability_of_sentence(sentence)
return score
"""
Calculate perplexity of a corpus for this model
"""
def calculate_perplexity(self, corpus):
logSum = 0.0
numWordsInCorpus = 0
perplexity = 0.0
for sentence in corpus.corpusArray:
numWordsInCorpus += len(sentence)
logSum += (-1 * self.score_sentence(sentence))
perplexity = logSum / numWordsInCorpus
perplexity = pow(2, perplexity)
return perplexity
"""
This model creates the backoff model implementation for the proposed modification to Assignment 1
"""
class BackoffModel:
"""
Initializes with raw corpus data or an existing set of trained unigram, bigram and trigram models
"""
def __init__(self, corpusData, delta, unigramModel = None, bigramModel = None, trigramModel = None):
self.trainingCorpus = corpusData
if unigramModel is not None:
self.unigramModel = unigramModel
else:
self.unigramModel = UnigramModel(corpusData)
if bigramModel is not None:
self.bigramModel = bigramModel
else:
self.bigramModel = BigramModel(corpusData)
if trigramModel is not None:
self.trigramModel = trigramModel
self.trigramModel.delta = delta
else:
self.trigramModel = TrigramModel(corpusData, self.bigramModel, delta)
self.historyList = defaultdict() #for each history contains B(w_i-2, w_i-1) and #B(w_i-1)
self.B1List = defaultdict() #for each bigram contains B(w_i-1)
self.train_model()
"""
Train model by computing additional data to help with 'missing mass' value
"""
def train_model(self):
for history, count in self.bigramModel.bigramCountList.items():
newHistory = BackoffData(history)
unigram1, unigram2 = history
newB1History = BackoffData(unigram2)
totalprob = 0.0
for word, freq in self.trainingCorpus.wordCountList.items():
if self.trigramModel.trigramCountList.get((unigram1, unigram2, word), 0) > 0:
totalprob += self.trigramModel.score_mle_probability((unigram1, unigram2, word))
else:
newHistory.B2.append(word)
if self.bigramModel.bigramCountList.get((unigram2, word), 0) == 0:
newHistory.B1.append(word)
newB1History.B1.append(word)
newHistory.q = 1 - (pow(2, totalprob))
newB1History.q = newHistory.q
self.historyList[history] = newHistory
self.B1List[unigram2] = newB1History
"""
Score a sentence in this model
"""
def score_sentence(self, sentence):
score = 0.0
unigram1 = ProcessCorpus.startSymbol
unigram2 = ProcessCorpus.startSymbol
unigram3 = ''
for word in sentence:
unigram3 = word
trigram = (unigram1, unigram2, unigram3)
bigram = (unigram2, unigram3)
if self.trigramModel.trigramCountList[trigram] > 0:
#p1 case
score += self.trigramModel.score_mle_probability(trigram)
elif (self.trigramModel.trigramCountList[trigram] == 0) and (self.bigramModel.bigramCountList[bigram] > 0):
#p2 case
numerator = self.bigramModel.score_mle_probability(bigram)
denominator = 0.0
historyitem = [historydata for historykey, historydata in self.historyList.items() if historykey == bigram]
historyitem = historyitem[0]
for b2item in historyitem.B2:
denominator += self.bigramModel.score_mle_probability((unigram2, b2item))
score += (numerator/denominator) * 0.5 * historyitem.q
elif self.bigramModel.bigramCountList[bigram] == 0:
#p3 case
numerator = self.unigramModel.score_probability_of_sentence([unigram3])
denominator = 0.0
historyitem = [historydata for historykey, historydata in self.historyList.items() if historykey == bigram]
if len(historyitem) > 0:
historyitem = historyitem[0]
for b1item in historyitem.B1:
denominator += self.unigramModel.score_probability_of_sentence([b1item])
score += (numerator / denominator) * 0.5 * historyitem.q
else:
historyitem = [historydata for historykey, historydata in self.B1List.items() if historykey == unigram2]
if len(historyitem) > 0:
historyitem = historyitem[0]
for b1item in historyitem.B1:
denominator += self.unigramModel.score_probability_of_sentence([b1item])
score += (numerator / denominator) * 0.5 * historyitem.q
else:
# unknown word for unigram calculation
historyitem = [historydata for historykey, historydata in self.B1List.items() if historykey == ProcessCorpus.unk]
if len(historyitem) > 0:
historyitem = historyitem[0]
for b1item in historyitem.B1:
denominator += self.unigramModel.score_probability_of_sentence([b1item])
score += (numerator / denominator) * 0.5 * historyitem.q
unigram1 = unigram2
unigram2 = word
unigram3 = ProcessCorpus.stopSymbol
trigram = (unigram1, unigram2, unigram3)
bigram = (unigram2, unigram3)
if self.trigramModel.trigramCountList[trigram] > 0:
# p1 case
score += self.trigramModel.score_mle_probability(trigram)
elif (self.trigramModel.trigramCountList[trigram] == 0) and (self.bigramModel.bigramCountList[bigram] > 0):
# p2 case
numerator = self.bigramModel.score_mle_probability(bigram)
denominator = 0.0
historyitem = [historydata for historykey, historydata in self.historyList.items() if historykey == bigram]
historyitem = historyitem[0]
for b2item in historyitem.B2:
denominator += self.bigramModel.score_mle_probability((unigram2, b2item))
score += (numerator / denominator) * 0.5 * historyitem.q
elif self.bigramModel.bigramCountList[bigram] == 0:
# p3 case
numerator = self.unigramModel.score_probability_of_sentence([unigram3])
denominator = 0.0
historyitem = [historydata for historykey, historydata in self.historyList.items() if historykey == bigram]
if len(historyitem) > 0:
historyitem = historyitem[0]
for b1item in historyitem.B1:
denominator += self.unigramModel.score_probability_of_sentence([b1item])
score += (numerator / denominator) * 0.5 * historyitem.q
else:
historyitem = [historydata for historykey, historydata in self.B1List.items() if historykey == unigram2]
if len(historyitem) > 0:
historyitem = historyitem[0]
for b1item in historyitem.B1:
denominator += self.unigramModel.score_probability_of_sentence([b1item])
score += (numerator / denominator) * 0.5 * historyitem.q
else:
#unknown word for unigram calculation
historyitem = [historydata for historykey, historydata in self.B1List.items() if historykey == ProcessCorpus.unk]
if len(historyitem) > 0:
historyitem = historyitem[0]
for b1item in historyitem.B1:
denominator += self.unigramModel.score_probability_of_sentence([b1item])
score += (numerator / denominator) * 0.5 * historyitem.q
return score
"""
Calculate perplexity of a corpus for this model
"""
def calculate_perplexity(self, corpus):
logSum = 0.0
numWordsInCorpus = 0
perplexity = 0.0
for sentence in corpus.corpusArray:
numWordsInCorpus += len(sentence)
logSum += (-1 * self.score_sentence(sentence))
perplexity = logSum / numWordsInCorpus
perplexity = pow(2, perplexity)
return perplexity
"""
This holds the data for each history in backoff model
"""
class BackoffData:
def __init__(self, history):
self.history = history #history
self.q = 0.0 #missing mass
self.B2 = [] #B(w_i-2, w_i-1)
self.B1 = [] #B(w_i-1)
#TODO:store this data into file once computed
"""
Parge command line arguments: training file path and test file path for a model
"""
def parse_args():
argParser = argparse.ArgumentParser(description='Parse settings to run models')
argParser.add_argument('filepathtrain', help='Path to file to train model')
argParser.add_argument('filepathtest', help='Path to file to test model')
options = argParser.parse_args()
return options
"""
Execute an instance of interpolation and backoff model for a given train and test corpus
"""
def main():
args = parse_args()
trainDataPath = args.filepathtrain
testDataPath = args.filepathtest
corpusData = ProcessCorpus(trainDataPath, True)
interpolationModel = InterpolationModel(corpusData, 0.05, 0.15, 0.8)
testCorpus = ProcessCorpus(testDataPath, False)
interpolation_perplexity = interpolationModel.calculate_perplexity(testCorpus)
backoffModel = BackoffModel(corpusData, 0.5, interpolationModel.unigramModel, interpolationModel.bigramModel, interpolationModel.trigramModel)
backoff_perplexity = backoffModel.calculate_perplexity(testCorpus)
with open("outputData.txt", 'w') as f:
f.write("Trainfile: " + trainDataPath + '\r\n')
f.write("Testpath: " + testDataPath + '\r\n')
f.write("Interpolation Perplexity: " + str(interpolation_perplexity) + '\r\n')
f.write("Backoff Perplexity: " + str(backoff_perplexity) + '\r\n')
f.write("Interpolation hyperparameters: 0.05, 0.15, 0.8" + '\r\n')
f.write("Backoff delta hyperparameters: 0.5" + '\r\n')
if __name__ == '__main__':
main()