-
Notifications
You must be signed in to change notification settings - Fork 0
/
POSTaggerBigram.java
564 lines (454 loc) · 21.8 KB
/
POSTaggerBigram.java
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
import java.io.*;
import java.util.*;
/**
* POS Tagger
*
* @author Nour Hayek, Jack Zhang
* February 27th, 2020
*/
public class PosTagger {
public HashMap<String, HashMap<String, Double>> transScores; // THe transition probability scores
public HashMap<String, HashMap<String, Double>> obsScores; // the observation probability scores
public double unknownScoreLog = -100.0; // the default scorer for an word not in the observation scores
/**
* instantiate ViterbiTagger without passing in file names (must manually set the transition and observation scores)
*/
public PosTagger() {
}
// instantiate ViterbiTagger with files to train the model
/**
* instantiate ViterbiTagger with files to train the model
*
* @param trainSentencesFileName name of file with sentences for training
* @param trainTagsFileName name of the file with corresponding tags
*/
public PosTagger(String trainSentencesFileName, String trainTagsFileName) {
try {
trainingModel(trainSentencesFileName, trainTagsFileName);
} catch (IOException e) {
System.err.println("Something went wrong while training model");
}
}
/**
* manually sets transition scores
*
* @param scores transition scores
*/
public void setTransScores(HashMap<String, HashMap<String, Double>> scores) {
this.transScores = scores;
}
/**
* manually sets observation scores
*
* @param scores observation scores
*/
public void setobsScores(HashMap<String, HashMap<String, Double>> scores) {
this.obsScores = scores;
}
/**
* trains the model with the training sentences and corresponding tags
*
* @param trainSentencesFileName the file name of the training sentences
* @param trainTagsFileName the file name of the training tags
*/
public void trainingModel(String trainSentencesFileName, String trainTagsFileName) throws IOException {
// read the files
BufferedReader sentencesInput = new BufferedReader(new FileReader(trainSentencesFileName));
BufferedReader tagsInput = new BufferedReader((new FileReader(trainTagsFileName)));
// initializes transition scores and observation scores
transScores = new HashMap<>();
obsScores = new HashMap<>();
//initializes sentence line and tag line from the files
String currentSentenceLine;
String currentTagLine;
// adds the transition score for "start"
transScores.put("start", new HashMap<>());
// updates the count for transition scores and observation scores line by line
while ((currentSentenceLine = sentencesInput.readLine()) != null) {
currentTagLine = tagsInput.readLine();
// initializes array of words and tags for the current line
List<String> words = new ArrayList<>(Arrays.asList(currentSentenceLine.split(" ")));
List<String> tags = new ArrayList<>(Arrays.asList((currentTagLine.split(" "))));
// update transition scores for "start" with the first tag of the line
if (!transScores.get("start").containsKey(tags.get(0))) {
transScores.get("start").put(tags.get(0), 1.0);
} else {
transScores.get("start").put(tags.get(0), transScores.get("start").get(tags.get(0)) + 1.0);
}
// updates the transition scores for the remaining tags
for (int i = 0; i < tags.size() - 1; i++) {
// adds the tag to the map if it is not already in the key set
if (!transScores.containsKey(tags.get(i))) {
HashMap<String, Double> newTransitionMap = new HashMap<>();
newTransitionMap.put(tags.get(i + 1), 1.0);
transScores.put(tags.get(i), newTransitionMap);
// updates the corresponding transition map if the tag is already in the key set
} else {
//increments the score by one if the next tag is already in the map
if (transScores.get(tags.get(i)).containsKey(tags.get(i + 1))) {
transScores.get(tags.get(i)).put(tags.get(i + 1), transScores.get(tags.get(i)).get(tags.get(i + 1)) + 1);
// adds the next tag to the map if it is not already in it
} else {
transScores.get(tags.get(i)).put(tags.get(i + 1), 1.0);
}
}
}
// updates the observation scores line by line
for (int i = 0; i < words.size(); i++) {
// adds the tag to the transition scores map if it's not already in the key set
if (!obsScores.containsKey(tags.get(i))) {
HashMap<String, Double> newWordMap = new HashMap<>();
newWordMap.put(words.get(i), 1.0);
obsScores.put(tags.get(i), newWordMap);
// updates the map for the tag if the tag is already in the key set
} else {
// increments the count by 1 if the word is already in the tag's map
if (obsScores.get(tags.get(i)).containsKey(words.get(i))) {
obsScores.get(tags.get(i)).put(words.get(i), obsScores.get(tags.get(i)).get(words.get(i)) + 1);
// creates a new map if with the word is the word is not in the tag's map
} else {
obsScores.get(tags.get(i)).put(words.get(i), 1.0);
}
}
}
}
// closes the files
sentencesInput.close();
tagsInput.close();
// normalizes the transition scores and observation scores
for (String tag : transScores.keySet()) {
// initializes the total count
int totalTagCount = 0;
// adds the tag counts iteratively
for (String nextTag : transScores.get(tag).keySet()) {
totalTagCount += transScores.get(tag).get(nextTag);
}
// divides each count by the corresponding total
for (String nextTag : transScores.get(tag).keySet()) {
transScores.get(tag).put(nextTag, Math.log(transScores.get(tag).get(nextTag) / totalTagCount));
}
}
// normalizes the observation scores and observation scores
for (String tag : obsScores.keySet()) {
// initializes the total count
int totalWordCount = 0;
// adds the word counts iteratively
for (String word : obsScores.get(tag).keySet()) {
totalWordCount += obsScores.get(tag).get(word);
}
// divides each count by the corresponding total
for (String word : obsScores.get(tag).keySet()) {
obsScores.get(tag).put(word, Math.log(obsScores.get(tag).get(word) / totalWordCount));
}
}
}
/**
* tests the model with the test sentences and corresponding tags
* write a file for the tags
*
* @param testSentencesFileName the file name of the testing sentences
* @param resultFileName the file name of the testing tags
*/
public void testingModel(String testSentencesFileName, String resultFileName) throws IOException {
// opens the file to read
BufferedReader testInput = new BufferedReader(new FileReader(testSentencesFileName));
// opens the file to write
BufferedWriter result = new BufferedWriter(new FileWriter(resultFileName));
// initializes the current line
String currentLine;
// reads each line and calls the Viterbi decoding method
while ((currentLine = testInput.readLine()) != null) {
List<String> currentTagList = viterbiDecoding(currentLine);
// writes in the result file the tags from decoding
String tagLine = "";
for (int i = 0; i < currentTagList.size(); i++) tagLine += currentTagList.get(i) + " ";
tagLine += "\n";
result.write(tagLine);
}
// closes the files
testInput.close();
result.close();
}
/**
* tests the model with the test sentences and corresponding tags
* write a file for the tags
*
* @param resultFileName the file name of the testing tags
* @param correctTagsFileName the file name of the correct tags
* @return Double the accuracy ratio
*/
public Double calculateAccuracy(String resultFileName, String correctTagsFileName) throws IOException {
// initializes the number of tags correct and the total tags in the result file
int numCorrect = 0;
int total = 0;
// opens the files
BufferedReader result = new BufferedReader(new FileReader(resultFileName));
BufferedReader correctTags = new BufferedReader(new FileReader(correctTagsFileName));
// initializes the lines from both files
String currentResultLine;
String currentTagLine;
// iteratively count the number of tags correct by comparing with the corresponding correct tags
while ((currentResultLine = result.readLine()) != null) {
currentTagLine = correctTags.readLine();
List<String> resultList = new ArrayList<>(Arrays.asList(currentResultLine.split(" ")));
List<String> tagList = new ArrayList<>(Arrays.asList((currentTagLine.split(" "))));
for (int i = 0; i < resultList.size(); i++) {
if (resultList.get(i).equals(tagList.get(i))) numCorrect += 1;
total += 1;
}
}
// closes the files
result.close();
correctTags.close();
// outputs the results
System.out.println("The POS tagger identified " + numCorrect + " out of " + total + " tags correctly.");
double accuracyRatio = ((double) numCorrect) / ((double) total);
System.out.println("The accuracy is: " + (accuracyRatio) * 100 + "%");
// returns the accuracy ratio
return accuracyRatio;
}
/**
* viterbi decoding
*
* @param line the string to be decoded to get the tags
* @return List<String> the list of decoded tags
*/
public List<String> viterbiDecoding(String line) throws NullPointerException {
// returns if we do not have the transition scores or observation scores
// they can be manually created and updated with the corresponding setter functions
if (transScores == null || obsScores == null)
throw new NullPointerException("Please provide the transition scores and/or observation scores");
// lowercase all the lines
line = line.toLowerCase();
// initializes the word list by splitting with spaces
List<String> wordsList = new ArrayList<>(Arrays.asList(line.split(" ")));
// initializes the back trace map
List<HashMap<String, String>> backTrace = new ArrayList<>();
// initializes the set of current states and current scores (with "start" as the first state)
Set<String> currStates = new HashSet<>();
currStates.add("start");
Map<String, Double> currScores = new TreeMap<>();
currScores.put("start", 0.0);
// iterates through each word in the line to get the next states
for (int i = 0; i < wordsList.size(); i++) {
// initializes the next states and scores
Set<String> nextStates = new HashSet<>();
Map<String, Double> nextScores = new HashMap<>();
// updates the next scores based on the transition and observation scores
for (String currState : currStates) {
// if the current state is not in the transition scores, we skip it
if (!transScores.containsKey(currState)) continue;
// adds the next states to the next states set
for (String nextState : transScores.get(currState).keySet()) {
nextStates.add(nextState);
Double nextScore;
// if the observation score contains the word, we update according to Viterbi forward propagation
if (obsScores.get(nextState).containsKey(wordsList.get(i))) {
nextScore = currScores.get(currState) + transScores.get(currState).get(nextState) + obsScores.get(nextState).get(wordsList.get(i));
// if the word has not bee encountered in training, we default the observation score
} else {
nextScore = currScores.get(currState) + transScores.get(currState).get(nextState) + unknownScoreLog;
}
// if the next state has not been encountered yet in this line or we found a smaller next score, we update accordingly
if (!nextScores.containsKey(nextState) || nextScore > nextScores.get(nextState)) {
// adds the back pointers to each state
nextScores.put(nextState, nextScore);
if (backTrace.size() < i + 1) {
backTrace.add(i, new HashMap<>());
backTrace.get(i).put(nextState, currState);
} else {
backTrace.get(i).put(nextState, currState);
}
}
}
}
// updates the current states for next iteration
currStates = nextStates;
currScores = nextScores;
}
// initializes the linked list of tags
List<String> tags = new LinkedList();
// initializes the last tag as the one with the highest score
String bestState = Collections.max(currScores.entrySet(), Map.Entry.comparingByValue()).getKey();
tags.add(0, bestState);
// trace backward in the line with the back pointers in the back trace map
for (int i = wordsList.size() - 1; i > 0; i--) {
bestState = backTrace.get(i).get(bestState);
tags.add(0, bestState);
}
// returns the decoded tags in a list
return tags;
}
/**
* console based tagging
*/
public void consoleBasedTagger() {
Scanner in = new Scanner(System.in);
// takes inputs from user until the user quits
while (true) {
System.out.println("Please enter a sentence to get tags (enter \"q\" to quit game)");
System.out.print("> ");
String line = in.nextLine();
// if user inputs "q", the tagger ends
if (line.equals("q")) return;
// calls Viterbi decoding on the provided line
List<String> tagList = viterbiDecoding(line);
// outputs the decoded tags
String tagLine = "";
for (int i = 0; i < tagList.size(); i++) tagLine += tagList.get(i) + " ";
tagLine += "\n";
System.out.println(tagLine);
}
}
// 3 tests for the Viterbi Tagger class
public static void main(String[] args) {
// hard coded transition scores from programming drill
System.out.println("Beginning test 0...");
PosTagger test0 = new PosTagger();
System.out.println("Inserting first HMM graph...");
HashMap<String, HashMap<String, Double>> transScores = new HashMap<>();
HashMap<String, Double> scores = new HashMap<>();
scores.put("NP", (double) (3 / 10));
scores.put("N", (double) (7 / 10));
transScores.put("start", scores);
scores = new HashMap<>();
scores.put("V", (double) (8 / 10));
scores.put("CNJ", (double) (2 / 10));
transScores.put("NP", scores);
scores = new HashMap<>();
scores.put("N", (double) (4 / 6));
scores.put("NP", (double) (2 / 6));
transScores.put("CNJ", scores);
scores = new HashMap<>();
scores.put("CNJ", (double) (2 / 10));
scores.put("V", (double) (8 / 10));
transScores.put("N", scores);
scores = new HashMap<>();
scores.put("NP", (double) (4 / 8));
scores.put("N", (double) (4 / 8));
transScores.put("V", scores);
// manually sets the transition scores
test0.setTransScores(transScores);
// hard coded observation scores from programming drill
HashMap<String, HashMap<String, Double>> obsScores = new HashMap<>();
scores = new HashMap<>();
scores.put("Chase", (double) 1);
obsScores.put("NP", scores);
scores = new HashMap<>();
scores.put("cat", (double) (4 / 10));
scores.put("dog", (double) (4 / 10));
scores.put("watch", (double) (2 / 10));
obsScores.put("N", scores);
scores = new HashMap<>();
scores.put("and", (double) (1));
obsScores.put("CNJ", scores);
scores = new HashMap<>();
scores.put("get", (double) (1 / 10));
scores.put("chase", (double) (3 / 10));
scores.put("watch", (double) (6 / 10));
obsScores.put("V", scores);
// manually sets the observation scores
test0.setobsScores(obsScores);
// testing the hard coded HMM
try {
System.out.println("Testing on sentence: \"cat watch chase and dog\"");
System.out.println("The corresponding tags are: " + test0.viterbiDecoding("cat watch chase and dog"));
} catch (NullPointerException e) {
System.err.println(e.getMessage());
}
System.out.println("\nInserting second HMM graph...");
transScores = new HashMap<>();
scores = new HashMap<>();
scores.put("NP", (double) (1 / 2));
scores.put("VG", (double) (1 / 2));
transScores.put("start", scores);
scores = new HashMap<>();
scores.put("ADJ", (double) (1));
transScores.put("NP", scores);
scores = new HashMap<>();
scores.put("V", (double) (1));
transScores.put("VG", scores);
scores = new HashMap<>();
scores.put("N", (double) (1 / 2));
scores.put("V", (double) (1 / 2));
transScores.put("ADJ", scores);
scores = new HashMap<>();
scores.put("ADJ", (double) (1));
transScores.put("V", scores);
scores = new HashMap<>();
scores.put("VG", (double) (1 / 2));
scores.put("DET", (double) (1 / 2));
transScores.put("DET", scores);
// manually sets the transition scores
test0.setTransScores(transScores);
// hard coded observation scores from programming drill
obsScores = new HashMap<>();
scores = new HashMap<>();
scores.put("I", (double) 1);
obsScores.put("NP", scores);
scores = new HashMap<>();
scores.put("swimming", (double) (1));
obsScores.put("VG", scores);
scores = new HashMap<>();
scores.put("really", (double) (1 / 2));
scores.put("fun", (double) (1 / 2));
obsScores.put("ADJ", scores);
scores = new HashMap<>();
scores.put("enjoy", (double) (1 / 2));
scores.put("is", (double) (1 / 2));
obsScores.put("V", scores);
scores = new HashMap<>();
scores.put("a", (double) (1));
obsScores.put("DET", scores);
scores = new HashMap<>();
scores.put("sport", (double) (1));
obsScores.put("N", scores);
// manually sets the observation scores
test0.setobsScores(obsScores);
// testing the hard coded HMM
try {
System.out.println("Testing on sentence: \"Swimming is a really fun sport\"");
System.out.println("The corresponding tags are: " + test0.viterbiDecoding("Swimming is a really fun sport"));
} catch (NullPointerException e) {
System.err.println(e.getMessage());
}
// tests with the simple training and testing data provdied
System.out.println("\nBeginning test 1...");
System.out.println("Training with the simple sentences");
PosTagger test1 = new PosTagger("texts/simple-train-sentences.txt", "texts/simple-train-tags.txt");
System.out.println("Testing on simple test sentences");
try {
test1.testingModel("texts/simple-test-sentences.txt", "texts/simple-test-tags-result.txt");
} catch (IOException e) {
System.err.println("Something went wrong while testing model");
} catch (NullPointerException e) {
System.err.println(e.getMessage());
}
try {
test1.calculateAccuracy("texts/simple-test-tags-result.txt", "texts/simple-test-tags.txt");
} catch (IOException e) {
System.err.println("Something went wrong while calculating accuracy");
}
// testing with the Brown Corpus
System.out.println("\nBeginning test 2...");
System.out.println("Training with the Brown corpus");
PosTagger test2 = new PosTagger("texts/brown-train-sentences.txt", "texts/brown-train-tags.txt");
System.out.println("Testing on Brown test sentences");
try {
test2.testingModel("texts/brown-test-sentences.txt", "texts/brown-test-tags-result.txt");
} catch (IOException e) {
System.err.println("Something went wrong while testing model");
} catch (NullPointerException e) {
System.err.println(e.getMessage());
}
try {
test2.calculateAccuracy("texts/brown-test-tags-result.txt", "texts/brown-test-tags.txt");
} catch (IOException e) {
System.err.println("Something went wrong while calculating accuracy");
}
// console based tagging that takes user input
System.out.println("\nBeginning console-based tagging...");
test2.consoleBasedTagger();
System.out.println("\nThe end");
}
}