-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwiki.py
405 lines (332 loc) · 10.7 KB
/
wiki.py
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
"""
Wikipedia language detector
This program classifies two languages Italian and Dutch
based on 20 word sentences
Models implemented: DecisionTree, AdaBoost
author - Abhishek Inamdar (ai2363@rit.edu)
"""
import math
import pickle # serialization-deserialization utility
import sys
from data_line import getLines
from data_line import getPredictionLines
from decisionTree import dTree
TRAINING_FILE = "./data/train_data.txt"
VALIDATION_FILE = "data/validation_data.txt"
D_TREE_OBJECT_FILE = "./objects/dTree.obj"
A_BOOST_OBJECT_FILE = "./objects/aBoost.obj"
class DecisionTreeModel:
"""
Decision tree Model
"""
__slots__ = "data", "out_file", "tree"
def __init__(self, train_file, out_file):
"""
Constructor method
:param train_file: training data
:param out_file: object output file
"""
lines = getLines(train_file)
self.data = {"train": lines[0]}
self.out_file = out_file
self.tree = None
def train(self, depth):
"""
training method
persisting decision tree object into file
:param depth: depth of decision tree
:return: None
"""
examples = self.data["train"]
features = set(examples[0].features.keys())
self.tree = dTree(examples, features, [], depth)
f = open(self.out_file, "wb")
pickle.dump(self, f)
f.close()
def test(self, test_file):
"""
test method
:param test_file: test data file
:return: results
"""
if not self.tree:
raise FileNotFoundError("Training is required")
if not test_file:
raise ValueError("Test file is required")
examples = getLines(test_file)
results = []
for ex in examples[0]:
decision = self.tree.decide(ex)
results.append({"value": ex.value, "goal": ex.goal, "decision": decision})
return results
def predict(self, predict_file):
"""
predict method
:param predict_file: prediction data file
:return: results
"""
if not self.tree:
raise FileNotFoundError("Training is required")
if not predict_file:
raise ValueError("Prediction file is required")
examples = getPredictionLines(predict_file)
results = []
for ex in examples[0]:
decision = self.tree.decide(ex)
results.append({"value": ex.value, "decision": decision})
return results
class WeightedSample:
"""
weighted sample representation
"""
__slots__ = "data", "sum", "dist_sum"
def __init__(self, dataLines):
"""
constructor method
:param dataLines: list of instances.
"""
self.data = dataLines
self.sum = 0
for dataLine in self.data:
dataLine.weight = 1
self.sum += dataLine.weight
self.dist_sum = self.sum
def normalize(self):
"""
normalize method
:return: None
"""
z = self.dist_sum / self.sum
self.sum = 0
for dataLine in self.data:
dataLine.weight *= z
self.sum += dataLine.weight
def changeWeight(self, i, new_weight):
"""
Change the weight of dataLine in the sample
:param i: index of the dataLine
:param new_weight: new weight
:return: None
"""
self.sum -= self.data[i].weight
self.data[i].weight = new_weight
self.sum += new_weight
class AdaBoostModel:
"""
Ada Boost Model
"""
__slots__ = "data", "out_file", "stumps", "dTree"
def __init__(self, train_file, out_file):
"""
constructor method
:param train_file: training data
:param out_file: object output data
"""
lines = getLines(train_file)
self.data = {"train": lines[0]}
self.out_file = out_file
self.stumps = []
self.dTree = None
def train(self, no_of_stumps):
"""
training method
persisting AdaBoost object into file
:param no_of_stumps: no of stumps to be used
:return: None
"""
examples = self.data["train"]
features = set(examples[0].features.keys())
# AdaBoost Algorithm
sample = WeightedSample(examples)
self.stumps = []
for i in range(no_of_stumps):
# decision tree with depth 1
stump = dTree(examples, features, [], 1)
error = 0
for example in examples:
decision = stump.decide(example)
if decision != example.goal:
error += example.weight
for j in range(len(examples)):
example = examples[j]
decision = stump.decide(example)
if decision == example.goal:
new_weight = example.weight * error / (sample.dist_sum - error)
sample.changeWeight(j, new_weight)
sample.normalize()
stump.weight = math.log(sample.dist_sum - error) / error
self.stumps.append(stump)
f = open(self.out_file, "wb")
pickle.dump(self, f)
f.close()
def test(self, test_file):
"""
Test method
:param test_file: test data
:return: None
"""
if not self.stumps:
raise FileNotFoundError("Training is required")
if not test_file:
raise ValueError("Test file is required")
examples = getLines(test_file)
results = []
for ex in examples[0]:
decision = self.vote(ex)
results.append({"value": ex.value, "goal": ex.goal, "decision": decision})
return results
def predict(self, predict_file):
"""
predict method
:param predict_file: prediction data file
:return: results
"""
if not self.stumps:
raise FileNotFoundError("Training is required")
if not predict_file:
raise ValueError("Prediction file is required")
examples = getPredictionLines(predict_file)
results = []
for ex in examples[0]:
decision = self.vote(ex)
results.append({"value": ex.value, "decision": decision})
return results
def vote(self, dataLine):
"""
classifies dataLine based on vote
:param dataLine: line of data to classify
:return: classification
"""
count = {}
max_count = 0
result = None
for stump in self.stumps:
decision = stump.decide(dataLine)
if decision in count:
count[decision] += stump.weight
else:
count[decision] = stump.weight
if count[decision] > max_count:
max_count = count[decision]
result = decision
return result
def showUsageMessage(showBothMessages):
"""
helper method for showing Usage messages
:param showBothMessages: to show messages or not
:return: None
"""
if showBothMessages:
print("Usage: python3 wiki.py train <training-data-file>")
print("Usage: python3 wiki.py predict <DT|AB|BS> <predict-data-file>")
else:
print("Incorrect Arguments.")
print("Usage: python3 wiki.py predict <DT|AB|BS> <predict-data-file>")
exit(1)
def printResults(results, modelName):
"""
Print results based on model's results and given examples
:param results: list of results
:param modelName: Name of the Model
"""
correct = 0
total = 0
for res in results:
total += 1
if res["decision"] == res["goal"]:
correct += 1
accuracyPercentage = round((correct / total) * 100, 2)
print(modelName + " Model Accuracy: " + str(accuracyPercentage) + "%")
def printPredictionResults(predictions):
"""
Print results based on model's prediction and given examples
:param predictions: list of predictions
"""
total = 0
print()
for res in predictions:
total += 1
print("Segment:", res["value"][:30], "| Prediction:", res["decision"])
print()
def train(examples):
"""
train method
:param examples: examples to train model,
each example will be in the following format:
<IT or DU><|><20 word sentence>
"IT" denotes Italian, "DU" denotes Dutch,
<|> is delimiter between identifier and sentence
:return: None
"""
dt_model = DecisionTreeModel(examples, D_TREE_OBJECT_FILE)
# depth of the decision tree
dt_model.train(5)
ab_model = AdaBoostModel(examples, A_BOOST_OBJECT_FILE)
# number of stumps
ab_model.train(10)
def validate(validate_file):
"""
validates trained models
:param validate_file: validation set file
each line will be in the following format:
<IT or DU><|><20 word sentence>
"IT" denotes Italian, "DU" denotes Dutch,
<|> is delimiter between identifier and sentence
:return: None
"""
objFile = D_TREE_OBJECT_FILE
objFile = open(objFile, "rb")
model = pickle.load(objFile)
objFile.close()
results = model.test(validate_file)
printResults(results, "Decision Tree")
objFile = A_BOOST_OBJECT_FILE
objFile = open(objFile, "rb")
model = pickle.load(objFile)
objFile.close()
results = model.test(validate_file)
printResults(results, "AdaBoost")
def predict(model, predict_file):
"""
predicts given examples based on the given trained model
each example should be in the following format:
<20 word sentence>
:param model: which model to use?
:param predict_file: prediction file containing test examples
:return: None
"""
if model == "DT":
objFile = D_TREE_OBJECT_FILE
else:
objFile = A_BOOST_OBJECT_FILE
objFile = open(objFile, "rb")
model = pickle.load(objFile)
objFile.close()
predictions = model.predict(predict_file)
printPredictionResults(predictions)
def main():
"""
Main method
:return: None
"""
if len(sys.argv) < 3:
showUsageMessage(True)
action = sys.argv[1]
if action == "train":
examples = sys.argv[2]
train(examples)
print("Training Done!!")
validate(VALIDATION_FILE)
print("Validation Done!!")
elif action == "predict":
if len(sys.argv) < 4:
showUsageMessage(False)
model = sys.argv[2]
if model not in {"DT", "AB", "BS"}:
showUsageMessage(False)
predict_file = sys.argv[3]
print("Prediction Starts...")
predict(model, predict_file)
print("Prediction End!")
if __name__ == '__main__':
main()