-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel_new.py
More file actions
358 lines (233 loc) · 11.7 KB
/
model_new.py
File metadata and controls
358 lines (233 loc) · 11.7 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
import copy
import os
import string
import sys
import nltk
import numpy as np
from nltk.stem.porter import *
from sklearn import datasets
from sklearn import metrics
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_selection import SelectPercentile
from sklearn.feature_selection import chi2
from sklearn.svm import LinearSVC
def stem_tokens(tokens, stemmer):
stemmed = []
for item in tokens:
stemmed.append(stemmer.stem(item))
return stemmed
def tokenize(text):
stemmer = PorterStemmer()
tokens = nltk.word_tokenize(text)
stems = stem_tokens(tokens, stemmer)
return stems
training_data = datasets.load_files(sys.argv[1], encoding="utf-8", decode_error='ignore')
test_data = datasets.load_files(sys.argv[2], encoding="utf-8", decode_error='ignore')
def show_top10(classifier, vectorizer, categories):
feature_names = np.asarray(vectorizer.get_feature_names())
for i, category in enumerate(categories):
top10 = np.argsort(classifier.coef_[i])[-20:]
print("%s: %s" % (category, " ".join(feature_names[top10])))
print("\n---------------------------------\nTFIDF VECTORIZER\n")
print("Config 3. Using tfidf vectorizer + stop_words filter + stemming (porter stemmer)\n----------------------------\n")
bigram_tfidf_vectorizer = TfidfVectorizer(ngram_range=(1, 2),tokenizer=tokenize, stop_words='english')
bigram_vectors = bigram_tfidf_vectorizer.fit_transform(training_data.data)
bigram_vectors_test = bigram_tfidf_vectorizer.transform(test_data.data)
print(bigram_vectors.shape)
print("\nSVM\n")
clf = LinearSVC()
print("\nbigram\n")
clf.fit(bigram_vectors, training_data.target)
pred = clf.predict(bigram_vectors_test)
print(metrics.f1_score(test_data.target, pred, average='macro'))
print(metrics.precision_recall_fscore_support(test_data.target, pred, average='macro'))
print("Config 4 Using tfidf vectorizer + stop_words filter + stemming + penalty L1 \n----------------------------\n")
bigram_tfidf_vectorizer = TfidfVectorizer(ngram_range=(1, 2),tokenizer=tokenize, stop_words='english')
bigram_vectors = bigram_tfidf_vectorizer.fit_transform(training_data.data)
bigram_vectors_test = bigram_tfidf_vectorizer.transform(test_data.data)
print("\nSVM\n")
clf = LinearSVC(penalty="l1",dual=False)
print("\nbigram\n")
clf.fit(bigram_vectors, training_data.target)
pred = clf.predict(bigram_vectors_test)
print(metrics.f1_score(test_data.target, pred, average='macro'))
print(metrics.precision_recall_fscore_support(test_data.target, pred, average='macro'))
print("\nConfig 5 Using tfidf vectorizer + stop_words filter + stemming + penalty L2 + select Percentile 30 \n----------------------------\n")
bigram_tfidf_vectorizer = TfidfVectorizer(ngram_range=(1, 2),tokenizer=tokenize, stop_words='english')
bigram_vectors = bigram_tfidf_vectorizer.fit_transform(training_data.data)
bigram_vectors_test = bigram_tfidf_vectorizer.transform(test_data.data)
print(bigram_vectors.shape)
selector = SelectPercentile(chi2, 30)
bigram_vectors = selector.fit_transform(bigram_vectors, training_data.target)
bigram_vectors_test = selector.transform(bigram_vectors_test)
print("After SelectPercentile. No. of features in bigram tfidf vector =" + str(bigram_vectors.shape))
print("\nSVM\n")
clf = LinearSVC(penalty="l2",C=1.0)
print("\nbigram\n")
clf.fit(bigram_vectors, training_data.target)
pred = clf.predict(bigram_vectors_test)
print(metrics.f1_score(test_data.target, pred, average='macro'))
print(metrics.precision_recall_fscore_support(test_data.target, pred, average='macro'))
print("\nConfig 8 Using tfidf vectorizer + stop_words filter + stemming + penalty L2 + select Percentile 30 + C=6.0\n----------------------------\n")
bigram_tfidf_vectorizer = TfidfVectorizer(ngram_range=(1, 2),tokenizer=tokenize, stop_words='english')
bigram_vectors = bigram_tfidf_vectorizer.fit_transform(training_data.data)
bigram_vectors_test = bigram_tfidf_vectorizer.transform(test_data.data)
print(bigram_vectors.shape)
selector = SelectPercentile(chi2, 30)
bigram_vectors = selector.fit_transform(bigram_vectors, training_data.target)
bigram_vectors_test = selector.transform(bigram_vectors_test)
print("After SelectPercentile. No. of features in bigram tfidf vector =" + str(bigram_vectors.shape))
print("\nSVM\n")
clf = LinearSVC(penalty="l2",dual=False, C=6.0)
print("\nbigram\n")
clf.fit(bigram_vectors, training_data.target)
pred = clf.predict(bigram_vectors_test)
print(metrics.f1_score(test_data.target, pred, average='macro'))
print(metrics.precision_recall_fscore_support(test_data.target, pred, average='macro'))
print("\nConfig 9 Using tfidf vectorizer + stop_words filter + stemming + penalty L2 + select Percentile 25 + C = 5.0 \n----------------------------\n")
bigram_tfidf_vectorizer = TfidfVectorizer(ngram_range=(1, 2),tokenizer=tokenize, stop_words='english')
bigram_vectors = bigram_tfidf_vectorizer.fit_transform(training_data.data)
bigram_vectors_test = bigram_tfidf_vectorizer.transform(test_data.data)
print(bigram_vectors.shape)
selector = SelectPercentile(chi2, 25)
bigram_vectors = selector.fit_transform(bigram_vectors, training_data.target)
bigram_vectors_test = selector.transform(bigram_vectors_test)
print("After SelectPercentile. No. of features in bigram tfidf vector =" + str(bigram_vectors.shape))
print("\nSVM\n")
clf = LinearSVC(penalty="l2",dual=False, C=5.0)
print("\nbigram\n")
clf.fit(bigram_vectors, training_data.target)
pred = clf.predict(bigram_vectors_test)
print(metrics.f1_score(test_data.target, pred, average='macro'))
print(metrics.precision_recall_fscore_support(test_data.target, pred, average='macro'))
print("\nCount vectorizer\n------------------\n")
print("\nConfig 1\n------------------\n")
bigram_count_vectorizer = CountVectorizer(token_pattern=r'\b\w+\b', stop_words='english')
bigram_vectors = bigram_count_vectorizer.fit_transform(training_data.data)
bigram_vectors_test = bigram_count_vectorizer.transform(test_data.data)
print(bigram_vectors.shape)
print("\nSVM\n")
clf = LinearSVC()
print("\nbigram\n")
clf.fit(bigram_vectors, training_data.target)
pred = clf.predict(bigram_vectors_test)
print(metrics.f1_score(test_data.target, pred, average='macro'))
print(metrics.precision_recall_fscore_support(test_data.target, pred, average='macro'))
print("\nConfig 2\n------------------\n")
bigram_count_vectorizer = CountVectorizer( tokenizer=tokenize, token_pattern=r'\b\w+\b', stop_words='english')
bigram_vectors = bigram_count_vectorizer.fit_transform(training_data.data)
bigram_vectors_test = bigram_count_vectorizer.transform(test_data.data)
print(bigram_vectors.shape)
print("\nSVM\n")
clf = LinearSVC()
print("\nbigram\n")
clf.fit(bigram_vectors, training_data.target)
pred = clf.predict(bigram_vectors_test)
print(metrics.f1_score(test_data.target, pred, average='macro'))
print(metrics.precision_recall_fscore_support(test_data.target, pred, average='macro'))
class tw_train:
data = []
filenames = []
target = []
target_names = []
def __init__(self):
self.data = []
self.target_names = []
self.target = []
walk_dir = sys.argv[1]
test_dir = sys.argv[2]
print("\nConfig 6 Using tfidf vectorizer + stop_words filter + stemming + penalty L2 + Strip Headers + remove punctuation\n----------------------------------------\n")
tw = tw_train()
# Copy targets, ie. categories (which are the folder names) to tw.target
tw.target_names = copy.deepcopy([name for name in os.listdir(walk_dir)])
for (dirpath, dirnames, filenames) in os.walk(walk_dir):
for filename in filenames:
tw.filenames.append(filename)
file_path = os.path.join(dirpath, filename)
with open(file_path, 'r') as f:
#Strip Headers
header_offset = 0
while f.readline().strip():
header_offset += 1
content = f.read()
# Remove punctuations, make lowercase
lowers = content.lower()
no_punctuation = lowers.translate(string.punctuation)
# Add training data content
tw.data.append(no_punctuation)
# Add the category index corresponding to training data
tw.target.append(tw.target_names.index(os.path.basename(dirpath)))
test_files = []
test_data = []
test_target = []
for (dirpath, dirnames, filenames) in os.walk(test_dir):
for filename in filenames:
test_files.append(filename)
file_path = os.path.join(dirpath, filename)
with open(file_path, 'r') as f:
#strip headers
header_offset = 0
while f.readline().strip():
header_offset += 1
content = f.read()
# Make text to lower case, remove punctuations
lowers = content.lower()
no_punctuation = lowers.translate(string.punctuation)
# Add training data content
test_data.append(no_punctuation)
test_target.append(tw.target_names.index(os.path.basename(dirpath)))
bigram_tfidf_vectorizer = TfidfVectorizer(ngram_range=(1, 2), tokenizer=tokenize, token_pattern=r'\b\w+\b', stop_words='english')
bigram_vectors = bigram_tfidf_vectorizer.fit_transform(tw.data)
bigram_vectors_test = bigram_tfidf_vectorizer.transform(test_data)
print("\nbigram\n")
print(bigram_vectors.shape)
print("\nSVM\n")
clf = LinearSVC(penalty="l2",dual=False, C=1)
print("\nbigram\n")
clf.fit(bigram_vectors, tw.target)
pred = clf.predict(bigram_vectors_test)
print(metrics.f1_score(test_target, pred, average='macro'))
print(metrics.precision_recall_fscore_support(test_target, pred, average='macro'))
print("\nConfig 7 Using tfidf vectorizer + stop_words filter + stemming + penalty L2 + remove punctuation\n----------------------------------------\n")
# Copy targets, ie. categories (which are the folder names) to tw.target
tw.target_names = copy.deepcopy([name for name in os.listdir(walk_dir)])
for (dirpath, dirnames, filenames) in os.walk(walk_dir):
for filename in filenames:
tw.filenames.append(filename)
file_path = os.path.join(dirpath, filename)
with open(file_path, 'r') as f:
content = f.read()
lowers = content.lower()
no_punctuation = lowers.translate(string.punctuation)
# Add training data content
tw.data.append(no_punctuation)
# Add the category index corresponding to training data
tw.target.append(tw.target_names.index(os.path.basename(dirpath)))
test_files = []
test_data = []
test_target = []
for (dirpath, dirnames, filenames) in os.walk(test_dir):
for filename in filenames:
test_files.append(filename)
file_path = os.path.join(dirpath, filename)
with open(file_path, 'r') as f:
content = f.read()
# Make text to lower case
lowers = content.lower()
no_punctuation = lowers.translate(string.punctuation)
# Add training data content
test_data.append(no_punctuation) # test_data.append(content)
test_target.append(tw.target_names.index(os.path.basename(dirpath)))
bigram_tfidf_vectorizer = TfidfVectorizer(ngram_range=(1, 2), tokenizer=tokenize, token_pattern=r'\b\w+\b', stop_words='english')
bigram_vectors = bigram_tfidf_vectorizer.fit_transform(tw.data)
bigram_vectors_test = bigram_tfidf_vectorizer.transform(test_data)
print("\nbigram\n")
print(bigram_vectors.shape)
print("\nSVM\n")
clf = LinearSVC(penalty="l2",dual=False)
print("\nbigram\n")
clf.fit(bigram_vectors, tw.target)
pred = clf.predict(bigram_vectors_test)
print(metrics.f1_score(test_target, pred, average='macro'))
print(metrics.precision_recall_fscore_support(test_target, pred, average='macro'))