-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmodel.py
250 lines (145 loc) · 8.23 KB
/
model.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
# -*- coding: utf-8 -*-
"""model.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/15A3q1bF9jHKEkAXcntUZ_uAtbiRB9zAp
## Install and import the required packages
"""
import re
from tqdm import tqdm
import pandas as pd
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC, LinearSVC
from sklearn.naive_bayes import MultinomialNB
from sklearn.ensemble import RandomForestClassifier
import pickle
"""## Mount Google Drive and import dataset"""
from google.colab import drive
drive.mount("/content/drive")
data = pd.read_csv("/content/drive/MyDrive/Colab Notebooks/deploy-ml-web-workshop/mbpt_dataset.csv")
data.head()
data.count()
data['type'].value_counts()
"""## Split train and test (to ensure balanced distribution of data)"""
train_data, test_data = train_test_split(data, test_size = 0.2, random_state = 42, stratify = data.type)
print("\033[93m {}\033[00m" .format('TRAIN DATA \n'), train_data)
print(train_data['type'].value_counts())
print("\033[93m {}\033[00m" .format('TEST DATA \n'), test_data)
print(test_data['type'].value_counts())
# PS: "\033[93m {}\033[00m" .format('\n AFTER \n') is just a way
# to change the color of the printed string 'TRAIN DATA \n' using ANSI Escape Code.
title = "Pie Chart: Train vs Test Data"
values = ["TRAIN DATA", "TEST DATA"]
data = [train_data.posts.count(), test_data.posts.count()]
fig = plt.figure(figsize =(10, 10))
plt.pie(data, labels = values, autopct=lambda p:f'{p:.2f}% ({p*sum(data)/100 :.0f})')
plt.title(title, bbox={"facecolor":"0.9", "pad":5})
plt.legend(loc="lower left")
plt.show()
"""## Data pre-processing and visualization
### Clean the "posts" text data
"""
def clean_data(data):
data_length = []
cleaned_posts = []
for sentence in tqdm(data.posts):
sentence = sentence.lower()
# Remove links from text data
sentence = re.sub('https?://[^\s<>"]+|www\.[^\s<>"]+', ' ', sentence)
# Remove other symbols
sentence = re.sub('[^0-9a-z]', ' ', sentence)
# Append cleaned data to List
data_length.append(len(sentence.split()))
cleaned_posts.append(sentence)
return cleaned_posts, data_length
"""### Print the cleaned "posts" for the entire dataset"""
data_clone = pd.read_csv("/content/drive/MyDrive/Colab Notebooks/deploy-ml-web-workshop/mbpt_dataset.csv")
x, y = clean_data(data_clone)
posts_index = data_clone.columns[1]
data_clone.drop(posts_index, axis = 1, inplace = True)
data_clone[posts_index] = x
print("\033[93m {}\033[00m" .format('\n CLEANED DATA FOR ALL \n'), data_clone)
# data_clone.to_csv(r'cleaned_data.csv', index = False, header = True)
"""### Wordcloud for the cleaned "posts"
"""
all_posts = []
all_posts = '\t'.join(data_clone["posts"])
wc = WordCloud(background_color="white", width=1600, height=800)
plt.figure(figsize=(20,10))
plt.imshow(wc.generate(all_posts), interpolation="bilinear")
plt.axis("off")
# plt.savefig("wordcloud-file.png", format="png", dpi = 1200)
plt.show()
"""### Print the cleaned "train" and "test" data"""
train_data.posts, train_length = clean_data(train_data)
print("\033[93m {}\033[00m" .format('\n CLEANED TRAIN DATA ONLY \n'), train_data.posts)
test_data.posts, test_length = clean_data(test_data)
print("\033[93m {}\033[00m" .format('\n CLEANED TEST DATA ONLY \n'), test_data.posts)
"""## Tokenize and transform the data"""
vectorizer = TfidfVectorizer(max_features = 5000, stop_words = "english")
vectorizer.fit(train_data.posts)
train_post = vectorizer.transform(train_data.posts).toarray()
test_post = vectorizer.transform(test_data.posts).toarray()
train_post.shape
target_encoder = LabelEncoder()
train_target = target_encoder.fit_transform(train_data.type)
test_target = target_encoder.fit_transform(test_data.type)
"""## Models testing and selection"""
# Store the accuracy of each model
models_accuracy = {}
"""#### Logistic Regression"""
model_log = LogisticRegression(max_iter = 3000, C = 0.5, n_jobs = -1)
model_log.fit(train_post, train_target)
print('Train Classification Report \n ', classification_report(train_target, model_log.predict(train_post), zero_division=0, target_names = target_encoder.inverse_transform([i for i in range(16)])))
print('Test Classification Report \n', classification_report(test_target, model_log.predict(test_post), zero_division=0, target_names = target_encoder.inverse_transform([i for i in range(16)])))
models_accuracy['Logistic Regression'] = accuracy_score(test_target, model_log.predict(test_post))
# Construct a confusion matrix
prd = model_log.predict(test_post)
cm = confusion_matrix(test_target, prd)
print(cm)
"""#### Linear Support Vector Classifier"""
model_linear_svc=LinearSVC(C = 0.1)
model_linear_svc.fit(train_post, train_target)
print('Train Classification Report \n ', classification_report(train_target, model_linear_svc.predict(train_post), zero_division=0, target_names = target_encoder.inverse_transform([i for i in range(16)])))
print('Test Classification Report \n', classification_report(test_target, model_linear_svc.predict(test_post), zero_division=0, target_names = target_encoder.inverse_transform([i for i in range(16)])))
models_accuracy['Linear Support Vector Classifier'] = accuracy_score(test_target, model_linear_svc.predict(test_post))
"""#### Support Vector Classifier"""
model_svc=SVC()
model_svc.fit(train_post, train_target)
print('Train Classification Report \n ', classification_report(train_target, model_svc.predict(train_post), zero_division=0, target_names = target_encoder.inverse_transform([i for i in range(16)])))
print('Test Classification Report \n ', classification_report(test_target, model_svc.predict(test_post), zero_division=0, target_names = target_encoder.inverse_transform([i for i in range(16)])))
models_accuracy['Support Vector Classifier'] = accuracy_score(test_target, model_svc.predict(test_post))
"""#### Multinomial Naive Bayes"""
model_multinomial_nb = MultinomialNB()
model_multinomial_nb.fit(train_post, train_target)
print('Train Classification Report \n ', classification_report(train_target,model_multinomial_nb.predict(train_post), zero_division=0, target_names=target_encoder.inverse_transform([i for i in range(16)])))
print('Test Classification Report \n ', classification_report(test_target,model_multinomial_nb.predict(test_post), zero_division=0, target_names=target_encoder.inverse_transform([i for i in range(16)])))
models_accuracy['Multinomial Naive Bayes'] = accuracy_score(test_target, model_multinomial_nb.predict(test_post))
"""#### Random Forest Classifier"""
model_forest = RandomForestClassifier(max_depth = 10)
model_forest.fit(train_post, train_target)
print('Train Classification Report \n ', classification_report(train_target, model_forest.predict(train_post), zero_division=0, target_names = target_encoder.inverse_transform([i for i in range(16)])))
print('Test Classification Report \n ', classification_report(test_target, model_forest.predict(test_post), zero_division=0, target_names = target_encoder.inverse_transform([i for i in range(16)])))
models_accuracy['Random Forest Classifier'] = accuracy_score(test_target, model_forest.predict(test_post))
"""## Models accuracy summary"""
models_accuracy
accuarcy = pd.DataFrame(models_accuracy.items(), columns = ['Models', 'Test accuracy'])
accuarcy.sort_values(by = 'Test accuracy', ascending = False, ignore_index = True).style.background_gradient(cmap = 'Blues')
"""## Save (pickle) the final model"""
# Vectorizer
pickle.dump(vectorizer, open('vectorizer.pkl', 'wb'))
# Model
pickle.dump(model_linear_svc, open('model.pkl', 'wb'))
"""### Load and test the saved model"""
loaded_vectorizer = pickle.load(open('vectorizer.pkl', 'rb'))
loaded_model = pickle.load(open('model.pkl', 'rb'))
message = ["This is pretty much the worse movie I have ever watched. It's completely thrash!"]
message = loaded_vectorizer.transform(message)
result = loaded_model.predict(message)
print(result, target_encoder.inverse_transform(result))