-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathanalyse.py
344 lines (226 loc) · 10.1 KB
/
analyse.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
import pandas as pd
import re
import nltk
from nltk.stem.porter import PorterStemmer
from nltk.stem.snowball import SnowballStemmer
from nltk.corpus import stopwords
from sklearn.grid_search import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
from sklearn.naive_bayes import MultinomialNB
from sklearn.naive_bayes import BernoulliNB
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import SGDClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import VotingClassifier
from datetime import datetime
t0 = datetime.now()
df = pd.read_csv('./movie_data.csv')
def preprocessor(text):
text = re.sub('<[^>]*>', '', text)
emoticons = re.findall('(?::|;|=)(?:-)?(?:\)|\(|D|P)', text)
text = re.sub('[\W]+', ' ', text.lower()) +\
' '.join(emoticons).replace('-', '')
return text
df['review'] = df['review'].apply(preprocessor)
nltk.download('stopwords')
porter = PorterStemmer()
stemmer = SnowballStemmer("english")
def tokenizer(text):
return text.split()
def tokenizer_porter(text):
return [porter.stem(word) for word in text.split()]
def tokenizer_stemmer(text):
return [stemmer.stem(word) for word in text.split()]
stop = stopwords.words('english')
'''
X_train = df.loc[:25000, 'review'].values
y_train = df.loc[:25000, 'sentiment'].values
X_test = df.loc[25000:, 'review'].values
y_test = df.loc[25000:, 'sentiment'].values
'''
X_train = df.loc[:25, 'review'].values
y_train = df.loc[:25, 'sentiment'].values
X_test = df.loc[25:50, 'review'].values
y_test = df.loc[25:50, 'sentiment'].values
tfidf = TfidfVectorizer(strip_accents=None,
lowercase=False,
preprocessor=None)
#LogisticRegression
print ("--------------------LogisticRegression--------------------")
lr_param_grid = [{'vect__ngram_range': [(1, 1)],
'vect__stop_words': [stop],
'vect__tokenizer': [tokenizer_porter],
'clf__penalty': ['l2'],
'clf__C': [1.0]}
]
lr_pipeline = Pipeline([('vect', tfidf),
('clf', LogisticRegression(random_state=0))])
gs_lr_tfidf = GridSearchCV(lr_pipeline, lr_param_grid,
scoring='accuracy',
cv=5,
verbose=1,
n_jobs=-1)
gs_lr_tfidf.fit(X_train, y_train)
#print('LogisticRegression : Best parameter set: %s ' % gs_lr_tfidf.best_params_)
#print('LogisticRegression : CV Accuracy: %.3f' % gs_lr_tfidf.best_score_)
lr_clf = gs_lr_tfidf.best_estimator_
#print('LogisticRegression : Test Accuracy: %.3f' % lr_clf.score(X_test, y_test))
y_predicted = lr_clf.predict(X_test)
cm = metrics.confusion_matrix(y_test, y_predicted)
print (cm)
# Print the classification report
print(metrics.classification_report(y_test, y_predicted,target_names=['neg','pos']))
#LinearSVC
print ("--------------------LinearSVC--------------------")
lsvc_param_grid = [{'vect__ngram_range': [(1, 1)],
'vect__stop_words': [stop],
'vect__tokenizer': [tokenizer]}
]
lsvc_pipeline = Pipeline([('vect', tfidf),
('clf', LinearSVC(C=1000))])
gs_lsvc_tfidf = GridSearchCV(lsvc_pipeline, lsvc_param_grid,
scoring='accuracy',
cv=5,
verbose=1,
n_jobs=-1)
gs_lsvc_tfidf.fit(X_train, y_train)
#print('LinearSVC : Best parameter set: %s ' % gs_lsvc_tfidf.best_params_)
#print('LinearSVC : CV Accuracy: %.3f' % gs_lsvc_tfidf.best_score_)
lsvc_clf = gs_lsvc_tfidf.best_estimator_
#print('LinearSVC : Test Accuracy: %.3f' % lsvc_clf.score(X_test, y_test))
y_predicted = lsvc_clf.predict(X_test)
cm = metrics.confusion_matrix(y_test, y_predicted)
print (cm)
# Print the classification report
print(metrics.classification_report(y_test, y_predicted,target_names=['neg','pos']))
#MultinomialNB
print ("--------------------MultinomialNB--------------------")
mnb_param_grid = [{'vect__ngram_range': [(1, 1)],
'vect__stop_words': [stop],
'vect__tokenizer': [tokenizer]}
]
mnb_pipeline = Pipeline([('vect', tfidf),
('clf', MultinomialNB())])
gs_mnb_tfidf = GridSearchCV(mnb_pipeline, mnb_param_grid,
scoring='accuracy',
cv=5,
verbose=1,
n_jobs=-1)
gs_mnb_tfidf.fit(X_train, y_train)
#print('MultinomialNB : Best parameter set: %s ' % gs_mnb_tfidf.best_params_)
#print('MultinomialNB : CV Accuracy: %.3f' % gs_mnb_tfidf.best_score_)
mnb_clf = gs_mnb_tfidf.best_estimator_
#print('MultinomialNB : Test Accuracy: %.3f' % mnb_clf.score(X_test, y_test))
y_predicted = mnb_clf.predict(X_test)
cm = metrics.confusion_matrix(y_test, y_predicted)
print (cm)
# Print the classification report
print(metrics.classification_report(y_test, y_predicted,target_names=['neg','pos']))
#BernoulliNB
print ("--------------------BernoulliNB--------------------")
bnb_param_grid = [{'vect__ngram_range': [(1, 1)],
'vect__stop_words': [stop],
'vect__tokenizer': [tokenizer_stemmer]}
]
bnb_pipeline = Pipeline([('vect', tfidf),
('clf', BernoulliNB())])
gs_bnb_tfidf = GridSearchCV(bnb_pipeline, bnb_param_grid,
scoring='accuracy',
cv=5,
verbose=1,
n_jobs=-1)
gs_bnb_tfidf.fit(X_train, y_train)
#print('BernoulliNB : Best parameter set: %s ' % gs_bnb_tfidf.best_params_)
#print('BernoulliNB : CV Accuracy: %.3f' % gs_bnb_tfidf.best_score_)
bnb_clf = gs_bnb_tfidf.best_estimator_
#print('BernoulliNB : Test Accuracy: %.3f' % bnb_clf.score(X_test, y_test))
y_predicted = bnb_clf.predict(X_test)
cm = metrics.confusion_matrix(y_test, y_predicted)
print (cm)
# Print the classification report
print(metrics.classification_report(y_test, y_predicted,target_names=['neg','pos']))
#RandomForestClassifier
print ("--------------------RandomForestClassifier--------------------")
rfc_param_grid = [{'vect__ngram_range': [(1, 1)],
'vect__stop_words': [stop],
'vect__tokenizer': [tokenizer_porter]}
]
rfc_pipeline = Pipeline([('vect', tfidf),
('clf', RandomForestClassifier())])
gs_rfc_tfidf = GridSearchCV(rfc_pipeline, rfc_param_grid,
scoring='accuracy',
cv=5,
verbose=1,
n_jobs=-1)
gs_rfc_tfidf.fit(X_train, y_train)
#print('RandomForestClassifier : Best parameter set: %s ' % gs_rfc_tfidf.best_params_)
#print('RandomForestClassifier : CV Accuracy: %.3f' % gs_rfc_tfidf.best_score_)
rfc_clf = gs_rfc_tfidf.best_estimator_
#print('RandomForestClassifier : Test Accuracy: %.3f' % rfc_clf.score(X_test, y_test))
y_predicted = rfc_clf.predict(X_test)
cm = metrics.confusion_matrix(y_test, y_predicted)
print (cm)
# Print the classification report
print(metrics.classification_report(y_test, y_predicted,target_names=['neg','pos']))
#SGDClassifier
print ("--------------------SGDClassifier--------------------")
sgd_param_grid = [{'vect__ngram_range': [(1, 1)],
'vect__stop_words': [stop, None],
'vect__tokenizer': [tokenizer_stemmer]}
]
sgd_pipeline = Pipeline([('vect', tfidf),
('clf', SGDClassifier())])
sgd_rfc_tfidf = GridSearchCV(sgd_pipeline, sgd_param_grid,
scoring='accuracy',
cv=5,
verbose=1,
n_jobs=-1)
sgd_rfc_tfidf.fit(X_train, y_train)
#print('SGDClassifier : Best parameter set: %s ' % sgd_rfc_tfidf.best_params_)
#print('SGDClassifier : CV Accuracy: %.3f' % sgd_rfc_tfidf.best_score_)
sgd_clf = sgd_rfc_tfidf.best_estimator_
#print('SGDClassifier : Test Accuracy: %.3f' % sgd_clf.score(X_test, y_test))
y_predicted = sgd_clf.predict(X_test)
cm = metrics.confusion_matrix(y_test, y_predicted)
print (cm)
# Print the classification report
print(metrics.classification_report(y_test, y_predicted,target_names=['neg','pos']))
#KNeighborsClassifier
print ("--------------------KNeighborsClassifier--------------------")
kn_param_grid = [{'vect__ngram_range': [(1, 1)],
'vect__stop_words': [stop],
'vect__tokenizer': [tokenizer_stemmer]}
]
kn_pipeline = Pipeline([('vect', tfidf),
('clf', KNeighborsClassifier())])
gs_kn_tfidf = GridSearchCV(kn_pipeline, kn_param_grid,
scoring='accuracy',
cv=5,
verbose=1,
n_jobs=-1)
gs_kn_tfidf.fit(X_train, y_train)
#print('KNeighborsClassifier : Best parameter set: %s ' % gs_kn_tfidf.best_params_)
#print('KNeighborsClassifier : CV Accuracy: %.3f' % gs_kn_tfidf.best_score_)
kn_clf = gs_kn_tfidf.best_estimator_
#print('KNeighborsClassifier : Test Accuracy: %.3f' % kn_clf.score(X_test, y_test))
y_predicted = kn_clf.predict(X_test)
cm = metrics.confusion_matrix(y_test, y_predicted)
print (cm)
# Print the classification report
print(metrics.classification_report(y_test, y_predicted,target_names=['neg','pos']))
print ("--------------------VotingClassifier--------------------")
e_clf = VotingClassifier(estimators=[('lr', lr_clf), ('lsvc', lsvc_clf), ('mnb', mnb_clf), ('bnb', bnb_clf), ('rfc', rfc_clf), ('sgd', sgd_clf), ('kn', kn_clf)], voting='hard')
e_clf.fit(X_train, y_train)
#print('VotingClassifier : Test Accuracy: %.3f' % e_clf.score(X_test, y_test))
y_predicted = e_clf.predict(X_test)
cm = metrics.confusion_matrix(y_test, y_predicted)
print (cm)
# Print the classification report
print(metrics.classification_report(y_test, y_predicted,target_names=['neg','pos']))
print ("------------------------------------------------------------")
print ("Total time : ")
print (datetime.now() - t0)