-
Notifications
You must be signed in to change notification settings - Fork 846
/
Copy pathclassification.py
233 lines (182 loc) · 9.55 KB
/
classification.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
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 26 19:38:26 2016
@author: DIP
"""
from sklearn.datasets import fetch_20newsgroups
from sklearn.cross_validation import train_test_split
def get_data():
data = fetch_20newsgroups(subset='all',
shuffle=True,
remove=('headers', 'footers', 'quotes'))
return data
def prepare_datasets(corpus, labels, test_data_proportion=0.3):
train_X, test_X, train_Y, test_Y = train_test_split(corpus, labels,
test_size=0.33, random_state=42)
return train_X, test_X, train_Y, test_Y
def remove_empty_docs(corpus, labels):
filtered_corpus = []
filtered_labels = []
for doc, label in zip(corpus, labels):
if doc.strip():
filtered_corpus.append(doc)
filtered_labels.append(label)
return filtered_corpus, filtered_labels
dataset = get_data()
print dataset.target_names
corpus, labels = dataset.data, dataset.target
corpus, labels = remove_empty_docs(corpus, labels)
print 'Sample document:', corpus[10]
print 'Class label:',labels[10]
print 'Actual class label:', dataset.target_names[labels[10]]
train_corpus, test_corpus, train_labels, test_labels = prepare_datasets(corpus,
labels,
test_data_proportion=0.3)
from normalization import normalize_corpus
norm_train_corpus = normalize_corpus(train_corpus)
norm_test_corpus = normalize_corpus(test_corpus)
''.strip()
from feature_extractors import bow_extractor, tfidf_extractor
from feature_extractors import averaged_word_vectorizer
from feature_extractors import tfidf_weighted_averaged_word_vectorizer
import nltk
import gensim
# bag of words features
bow_vectorizer, bow_train_features = bow_extractor(norm_train_corpus)
bow_test_features = bow_vectorizer.transform(norm_test_corpus)
# tfidf features
tfidf_vectorizer, tfidf_train_features = tfidf_extractor(norm_train_corpus)
tfidf_test_features = tfidf_vectorizer.transform(norm_test_corpus)
# tokenize documents
tokenized_train = [nltk.word_tokenize(text)
for text in norm_train_corpus]
tokenized_test = [nltk.word_tokenize(text)
for text in norm_test_corpus]
# build word2vec model
model = gensim.models.Word2Vec(tokenized_train,
size=500,
window=100,
min_count=30,
sample=1e-3)
# averaged word vector features
avg_wv_train_features = averaged_word_vectorizer(corpus=tokenized_train,
model=model,
num_features=500)
avg_wv_test_features = averaged_word_vectorizer(corpus=tokenized_test,
model=model,
num_features=500)
# tfidf weighted averaged word vector features
vocab = tfidf_vectorizer.vocabulary_
tfidf_wv_train_features = tfidf_weighted_averaged_word_vectorizer(corpus=tokenized_train,
tfidf_vectors=tfidf_train_features,
tfidf_vocabulary=vocab,
model=model,
num_features=500)
tfidf_wv_test_features = tfidf_weighted_averaged_word_vectorizer(corpus=tokenized_test,
tfidf_vectors=tfidf_test_features,
tfidf_vocabulary=vocab,
model=model,
num_features=500)
from sklearn import metrics
import numpy as np
def get_metrics(true_labels, predicted_labels):
print 'Accuracy:', np.round(
metrics.accuracy_score(true_labels,
predicted_labels),
2)
print 'Precision:', np.round(
metrics.precision_score(true_labels,
predicted_labels,
average='weighted'),
2)
print 'Recall:', np.round(
metrics.recall_score(true_labels,
predicted_labels,
average='weighted'),
2)
print 'F1 Score:', np.round(
metrics.f1_score(true_labels,
predicted_labels,
average='weighted'),
2)
def train_predict_evaluate_model(classifier,
train_features, train_labels,
test_features, test_labels):
# build model
classifier.fit(train_features, train_labels)
# predict using model
predictions = classifier.predict(test_features)
# evaluate model prediction performance
get_metrics(true_labels=test_labels,
predicted_labels=predictions)
return predictions
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import SGDClassifier
mnb = MultinomialNB()
svm = SGDClassifier(loss='hinge', n_iter=100)
# Multinomial Naive Bayes with bag of words features
mnb_bow_predictions = train_predict_evaluate_model(classifier=mnb,
train_features=bow_train_features,
train_labels=train_labels,
test_features=bow_test_features,
test_labels=test_labels)
# Support Vector Machine with bag of words features
svm_bow_predictions = train_predict_evaluate_model(classifier=svm,
train_features=bow_train_features,
train_labels=train_labels,
test_features=bow_test_features,
test_labels=test_labels)
# Multinomial Naive Bayes with tfidf features
mnb_tfidf_predictions = train_predict_evaluate_model(classifier=mnb,
train_features=tfidf_train_features,
train_labels=train_labels,
test_features=tfidf_test_features,
test_labels=test_labels)
# Support Vector Machine with tfidf features
svm_tfidf_predictions = train_predict_evaluate_model(classifier=svm,
train_features=tfidf_train_features,
train_labels=train_labels,
test_features=tfidf_test_features,
test_labels=test_labels)
# Support Vector Machine with averaged word vector features
svm_avgwv_predictions = train_predict_evaluate_model(classifier=svm,
train_features=avg_wv_train_features,
train_labels=train_labels,
test_features=avg_wv_test_features,
test_labels=test_labels)
# Support Vector Machine with tfidf weighted averaged word vector features
svm_tfidfwv_predictions = train_predict_evaluate_model(classifier=svm,
train_features=tfidf_wv_train_features,
train_labels=train_labels,
test_features=tfidf_wv_test_features,
test_labels=test_labels)
import pandas as pd
cm = metrics.confusion_matrix(test_labels, svm_tfidf_predictions)
pd.DataFrame(cm, index=range(0,20), columns=range(0,20))
class_names = dataset.target_names
print class_names[0], '->', class_names[15]
print class_names[18], '->', class_names[16]
print class_names[19], '->', class_names[15]
import re
num = 0
for document, label, predicted_label in zip(test_corpus, test_labels, svm_tfidf_predictions):
if label == 0 and predicted_label == 15:
print 'Actual Label:', class_names[label]
print 'Predicted Label:', class_names[predicted_label]
print 'Document:-'
print re.sub('\n', ' ', document)
print
num += 1
if num == 4:
break
num = 0
for document, label, predicted_label in zip(test_corpus, test_labels, svm_tfidf_predictions):
if label == 18 and predicted_label == 16:
print 'Actual Label:', class_names[label]
print 'Predicted Label:', class_names[predicted_label]
print 'Document:-'
print re.sub('\n', ' ', document)
print
num += 1
if num == 4:
break