-
Notifications
You must be signed in to change notification settings - Fork 0
/
classify.py
executable file
·387 lines (342 loc) · 13 KB
/
classify.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
#!/usr/bin/env python
"""A Supervised ML classifier distinguishing between written output produced by hertiage and non-heritage learners of Polish as a foreign language"""
import math
import numpy as np
import pynini
import spacy
from nltk.tokenize import sent_tokenize
from numpy import ndarray
from sklearn import dummy, feature_extraction, metrics, naive_bayes, svm
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.naive_bayes import ComplementNB, MultinomialNB
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from tabulate import tabulate
class Error(Exception):
pass
# assigns data to variables
heritage_train = "" # file path for a heritage train corpus
nonheritage_train = "" # file path for a non-heritage train corpus
heritage_test = "heritage_test.txt"
nonheritage_test = "nonheritage_test.txt"
lm = "lm.fst"
nlp = spacy.load("pl_core_news_lg")
M_LN2 = math.log(2)
# prepositions that take LOC for static verbs and ACC for dynamic verbs
prepositions = ["o", "na", "po", "w", "we", "O", "Na", "Po", "W", "We"]
# lemmatized verbs that require a genitive object
verbs = [
"wymagać",
"wymagać być",
"uczyć",
"ucyć być",
"nauczyć",
"nauczyć być",
"bać",
"bać być",
"obawiać",
"obawiać być",
"brakować",
"brakować być",
"bronić",
"bronić być",
"chcieć",
"chcieć być",
"napić",
"napić być",
"oczekiwać",
"oczekiwać być",
"pilnować",
"pilnować być",
"potrzebować",
"potrzebować być",
"próbować",
"próbować być",
"spróbować",
"spróbować być",
"pytać",
"pytać być",
"szukać",
"szukać być",
"słuchać",
"słuchać być",
"używać",
"używać być",
"doglądać",
"doglądać być",
"domagać",
"domagać być",
"dotyczyć",
"dotyczyć być",
"dotykać",
"dotykać być",
"nienawidzić",
"nienawidzić być",
"odmawiać",
"odmawiać być",
"poszukiwać",
"poszukiwać być",
"pozbywać",
"pozbywać być",
"pragnąć",
"pragnąć być",
"spodziewać",
"spodziewać być",
"strzec",
"strzec być",
"udzielać",
"udzielać być",
"zabraniać",
"zabraniać być",
"żałować",
"żałować być",
"zapominać",
"zapominać być",
"zazdrościć",
"zazdrościć być",
]
def get_data(path: str) -> list:
"""reads .txt file into a list of strings"""
list_of_lines = []
with open(path, "r") as source:
for line in source:
line = line.rstrip()
if line == False:
continue
else:
list_of_lines.append(line)
return list_of_lines
def get_position(word, sentence) -> int:
"""gets the token index in a tokenized sentence"""
tuples = [(token.text, token.i) for token in sentence]
for tuple in tuples:
if tuple[0] == word:
return tuple[1]
def LOC_post_prep(data: list) -> ndarray:
"""counts the instances of the locative case following bivalent prepositions"""
bow = []
for essay_line in data:
doc = nlp(essay_line)
counts = []
for sentence in doc.sents:
counter = 0
sentence_string = str(sentence)
for preposition in prepositions:
if preposition in sentence_string.split():
prep_position = get_position(preposition, sentence)
post_prep = doc[prep_position + 1]
case = post_prep.morph.get("Case")
if case:
if case[0] == "Loc":
counter += 1
counts.append(counter)
summed = sum(counts)
bow.append(summed)
bow_np = np.array(bow).astype(float)
return bow_np
def genitive(data: list) -> ndarray:
"""extracts the counts of direct objects in the genitive case following verbs that take genitive objects """
bow = []
for essay_line in data:
tokenized_line = sent_tokenize(essay_line, language="polish")
counts = []
for sentence in tokenized_line:
tokenized_sentence = nlp(sentence)
counter = 0
for token in tokenized_sentence:
token_str = str(token)
if token.lemma_ in verbs:
verb_position = get_position(token_str, tokenized_sentence)
post_verb = tokenized_sentence[verb_position + 1 :]
for token in post_verb:
case = token.morph.get("Case")
if case:
if token.dep_ == "obj" and case[0] == "Gen":
counter += 1
counts.append(counter)
summed = sum(counts)
bow.append(summed)
bow_np = np.array(bow).astype(float)
return bow_np
def negation(data: list) -> ndarray:
"""extracts the counts of direct objects redndered in the genitive case following negated verbs"""
bow = []
for essay_line in data:
tokenized_line = sent_tokenize(essay_line, language="polish")
counts = []
for sentence in tokenized_line:
tokenized_sentence = nlp(sentence)
counter = 0
for token in tokenized_sentence:
token_str = str(token)
if token.pos_ == "PART" and token.dep_ == "advmod:neg":
negation_position = get_position(token_str, tokenized_sentence)
post_negation = tokenized_sentence[negation_position + 1 :]
for token in post_negation:
case = token.morph.get("Case")
if case:
if token.dep_ == "obj" and case[0] == "Gen":
counter += 1
counts.append(counter)
summed = sum(counts)
bow.append(summed)
bow_np = np.array(bow).astype(float)
return bow_np
def bits_per_char(string: pynini.Fst, lm: pynini.Fst) -> float:
"""computes bits per character according to the language model (LM FST)"""
eprops = pynini.ACCEPTOR | pynini.STRING | pynini.UNWEIGHTED
oprops = string.properties(eprops, True)
assert eprops == oprops, f"{oprops} != {eprops}"
lattice = pynini.intersect(string, lm)
if lattice.start() == pynini.NO_STATE_ID:
raise Error("Composition failure")
cost = pynini.shortestdistance(lattice, reverse=True)[lattice.start()]
bits = float(cost) / M_LN2
chars = string.num_states() - 1
return bits / chars
def entropy(data: list, lm: pynini.Fst) -> ndarray:
"""computes per-character entropy for each document"""
bow = []
lm = pynini.Fst.read(lm)
for essay_line in data:
essay_line = essay_line.rstrip()
essay_line_fsa = pynini.accep(pynini.escape(essay_line))
try:
score = bits_per_char(essay_line_fsa, lm)
bow.append(score)
except Error:
bow.append(0)
bow_np = np.array(bow).astype(float)
return bow_np
def cross_validate(data: ndarray, target: ndarray, model) -> float:
""""evaluates the accuracy of the model on 10-fold cross-validated data"""
X = data
Y = np.array(target)
score = cross_val_score(model, X, Y, scoring="accuracy", cv=10)
return round(score.mean(), 3)
def main() -> None:
# loads the training data
heritage_train_input = get_data(heritage_train) # list of heritage docs
nonheritage_train_input = get_data(nonheritage_train) # list of non-heritage docs
all_train_input = (
heritage_train_input + nonheritage_train_input
) # combined list of heritage and non-heritage docs
# makes the labels for the train data
heritage_train_labels = [0] * len(heritage_train_input)
nonheritage_train_labels = [1] * len(nonheritage_train_input)
all_train_labels = heritage_train_labels + nonheritage_train_labels
# loads the test data
heritage_test_input = get_data(heritage_test) # list of heritage docs
nonheritage_test_input = get_data(nonheritage_test) # list non-heritage docs
all_test_input = (
heritage_test_input + nonheritage_test_input
) # combined list of heritage and non-heritage docs
# makes the labels for the test data
heritage_test_labels = [0] * len(heritage_test_input)
nonheritage_test_labels = [1] * len(nonheritage_test_input)
all_test_labels = heritage_test_labels + nonheritage_test_labels
# develops a dummy baseline
vectorizer = feature_extraction.text.CountVectorizer(min_df=3, max_df=0.9)
D_train = vectorizer.fit_transform(all_train_input)
D_test = vectorizer.transform(all_test_input)
dumb = dummy.DummyClassifier()
dumb = dumb.fit(D_train, all_train_labels)
dummy_baseline_accuracy = metrics.accuracy_score(
all_test_labels, dumb.predict(D_test)
)
print(
f"\nDummy baseline accuracy:\t{dummy_baseline_accuracy}"
) # this should print 0.5 since there is the same number of heritage and non-heritage essays
# runs the classifier on the test data
multinomial_NB = naive_bayes.MultinomialNB(alpha=1)
complement_NB = naive_bayes.ComplementNB()
decision_tree = DecisionTreeClassifier()
random_forest = RandomForestClassifier()
svc = svm.SVC(kernel="linear", C=1.0)
models = [multinomial_NB, complement_NB, decision_tree, random_forest, svc]
features = [LOC_post_prep, genitive, negation]
scores_per_model = [
[
"Model",
"LOC after Prepositions",
"Genitive after Verbs",
"Genitive of Negation",
"Per-Character Entropy",
"All Features Combined",
]
]
for model in models:
feature_acc_scores = [str(model)]
features_train_list = []
features_test_list = []
for feature in features:
features_train = feature(all_train_input)
features_train_reshaped = features_train.reshape(-1, 1)
features_train_list.append(features_train_reshaped)
features_test = feature(all_test_input)
features_test_reshaped = features_test.reshape(-1, 1)
features_test_list.append(features_test_reshaped)
model.fit(features_train_reshaped, all_train_labels)
prediction = model.predict(features_test_reshaped)
accuracy = metrics.accuracy_score(all_test_labels, prediction)
feature_acc_scores.append(round(accuracy, 3))
# computes entropy as a separate feature
entropy_train = entropy(all_train_input, lm)
entropy_train_reshaped = entropy_train.reshape(-1, 1)
features_train_list.append(entropy_train_reshaped)
entropy_test = entropy(all_test_input, lm)
entropy_test_reshaped = entropy_test.reshape(-1, 1)
features_test_list.append(entropy_test_reshaped)
model.fit(entropy_train_reshaped, all_train_labels)
entropy_prediction = model.predict(entropy_test_reshaped)
entropy_accuracy = metrics.accuracy_score(all_test_labels, entropy_prediction)
feature_acc_scores.append(round(entropy_accuracy, 3))
# computes the score for all features combined
concatenated_train = np.concatenate(features_train_list, axis=1)
concatenated_test = np.concatenate(features_test_list, axis=1)
model.fit(concatenated_train, all_train_labels)
combined_prediction = model.predict(concatenated_test)
combined_accuracy = metrics.accuracy_score(all_test_labels, combined_prediction)
feature_acc_scores.append(round(combined_accuracy, 3))
# puts everything in a table
scores_per_model.append(feature_acc_scores)
# makes and prints the table
print(f"\nTest Data Accuracy:")
print(
f"\n{tabulate(scores_per_model, headers = 'firstrow', tablefmt = 'fancy_grid')}"
)
# runs the classifier on the cross-validated train data
cv_models = [
MultinomialNB(),
ComplementNB(),
DecisionTreeClassifier(),
RandomForestClassifier(),
SVC(),
]
cv_scores_per_model = [
[
"Model",
"LOC after Prepositions",
"Genitive after Verbs",
"Genitive of Negation",
"Per-Character Entropy",
"All Features Combined",
]
]
for model in cv_models:
cv_feature_acc_scores = [str(model)]
for feature in features_train_list:
cv_accuracy = cross_validate(feature, all_train_labels, model)
cv_feature_acc_scores.append(cv_accuracy)
total_cv_accuracy = cross_validate(concatenated_train, all_train_labels, model)
cv_feature_acc_scores.append(total_cv_accuracy)
# puts everything in a table
cv_scores_per_model.append(cv_feature_acc_scores)
# makes and prints the table
print(f"\nCross-Validated Training Data Accuracy:")
print(
f"\n{tabulate(cv_scores_per_model, headers = 'firstrow', tablefmt = 'fancy_grid')}"
)
if __name__ == "__main__":
main()