-
Notifications
You must be signed in to change notification settings - Fork 0
/
ds1_sentiment_analysis_for_rating_calculation.py
464 lines (324 loc) · 15.6 KB
/
ds1_sentiment_analysis_for_rating_calculation.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
# -*- coding: utf-8 -*-
"""Sentiment_Analysis.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1dB05XA1kmIKfFqAUjvUjIWY4fJN8zsRQ
Importing Libraries
--
"""
import numpy as np
import pandas as pd
"""Dataset
--
"""
from google.colab import drive
drive.mount('/content/drive')
dataset = pd.read_csv('/content/drive/MyDrive/SQA/Project Works/Datasets/App_Reviews.csv', delimiter = ',', nrows=20001)
dataset.shape
dataset.head()
from sklearn.utils import shuffle
df = shuffle(dataset)
df.head()
"""BERT
--
"""
!pip install transformers
!pip install torch==1.8.1+cu111 torchvision==0.9.1+cu111 torchaudio===0.8.1 -f https://download.pytorch.org/whl/torch_stable.html
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
tokenizer = AutoTokenizer.from_pretrained('nlptown/bert-base-multilingual-uncased-sentiment')
model = AutoModelForSequenceClassification.from_pretrained('nlptown/bert-base-multilingual-uncased-sentiment')
def sentiment_score(review):
tokens = tokenizer.encode(review, return_tensors='pt')
result = model(tokens)
return int(torch.argmax(result.logits))+1
X_data = []
Y_data = []
Y_score = []
for i in range(2,len(df)):
try:
Y_out = sentiment_score(df['Reviews'].iloc[i])
Y_true = df['Rating'].iloc[i];
if Y_out>=3 and Y_true>=3:
X_data.append(df['Reviews'].iloc[i])
Y_data.append(Y_true)
Y_score.append(Y_out)
elif Y_out<3 and Y_true<3:
X_data.append(df['Reviews'].iloc[i])
Y_data.append(Y_true)
Y_score.append(Y_out)
except Exception as e:
print(e)
pass
X_data = np.array(X_data)
Y_data = np.array(Y_data)
Y_score = np.array(Y_score)
from sklearn.metrics import confusion_matrix, accuracy_score
cm = confusion_matrix(Y_data, Y_score)
print(cm)
accuracy_score(Y_data, Y_score)
"""Pickle Data
--
"""
pickle_out = open("/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/X.pickle", "wb")
pickle.dump(X_data, pickle_out, protocol=4) # protocol=4 is used for new version of pickle which can serialize more than 4GB data
pickle_out.close()
pickle_out = open("/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/Y.pickle", "wb")
pickle.dump(Y_data, pickle_out, protocol=4) # protocol=4 is used for new version of pickle which can serialize more than 4GB data
pickle_out.close()
pickle_out = open("/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/Y_score.pickle", "wb")
pickle.dump(Y_score, pickle_out, protocol=4) # protocol=4 is used for new version of pickle which can serialize more than 4GB data
pickle_out.close()
"""Data Preprocessing
--
"""
import pickle
pickle_in = open("/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/X.pickle", "rb")
X = pickle.load(pickle_in)
pickle_in = open("/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/Y.pickle", "rb")
Y = pickle.load(pickle_in)
len(X)
len(Y)
import re
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
ps = PorterStemmer()
all_stopwords = stopwords.words('english')
all_stopwords.remove('not')
corpus=[]
for i in range(0, len(X)):
review = re.sub('[^a-zA-Z]', ' ', str(X[i]))
review = review.lower()
review = review.split()
review = [ps.stem(word) for word in review if not word in set(all_stopwords)]
review = ' '.join(review)
corpus.append(review)
corpus
len(corpus)
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing.text import Tokenizer
tokens_model = Tokenizer(num_words = 64)
tokens_model.fit_on_texts(corpus)
seq = tokens_model.texts_to_sequences(corpus)
word_index = tokens_model.word_index
print(tokens_model.word_index)
len(word_index)
print(seq)
max_length = 0
for review_num in range(len(seq)):
num_words = len(seq[review_num])
if num_words > max_length:
max_length = num_words
print(max_length)
from tensorflow.keras.preprocessing.sequence import pad_sequences
import numpy as np
X_vec = pad_sequences(seq, maxlen=max_length)
Y = np.asarray(Y)
X_vec.shape
Y.shape
Y = Y - 1
Y
"""Training and Test Splitting
--
"""
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X_vec, Y, test_size=0.2, random_state=1)
X_test, X_val, Y_test, Y_val = train_test_split(X_test, Y_test, test_size=0.5, random_state=1)
print('Train:', len(X_train), '\nTest:', len(X_test), '\nValidation:', len(X_val))
pickle_out = open("/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/X_train.pickle", "wb")
pickle.dump(X_train, pickle_out, protocol=4) # protocol=4 is used for new version of pickle which can serialize more than 4GB data
pickle_out.close()
pickle_out = open("/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/Y_train.pickle", "wb")
pickle.dump(Y_train, pickle_out, protocol=4) # protocol=4 is used for new version of pickle which can serialize more than 4GB data
pickle_out.close()
pickle_out = open("/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/X_test.pickle", "wb")
pickle.dump(X_test, pickle_out, protocol=4) # protocol=4 is used for new version of pickle which can serialize more than 4GB data
pickle_out.close()
pickle_out = open("/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/Y_test.pickle", "wb")
pickle.dump(Y_test, pickle_out, protocol=4) # protocol=4 is used for new version of pickle which can serialize more than 4GB data
pickle_out.close()
pickle_out = open("/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/X_val.pickle", "wb")
pickle.dump(X_val, pickle_out, protocol=4) # protocol=4 is used for new version of pickle which can serialize more than 4GB data
pickle_out.close()
pickle_out = open("/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/Y_val.pickle", "wb")
pickle.dump(Y_val, pickle_out, protocol=4) # protocol=4 is used for new version of pickle which can serialize more than 4GB data
pickle_out.close()
"""Load Data
--
"""
import pickle
pickle_in = open("/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/X_train.pickle", "rb")
X_train = pickle.load(pickle_in)
pickle_in = open("/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/Y_train.pickle", "rb")
Y_train = pickle.load(pickle_in)
pickle_in = open("/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/X_test.pickle", "rb")
X_test = pickle.load(pickle_in)
pickle_in = open("/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/Y_test.pickle", "rb")
Y_test = pickle.load(pickle_in)
pickle_in = open("/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/X_val.pickle", "rb")
X_val = pickle.load(pickle_in)
pickle_in = open("/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/Y_val.pickle", "rb")
Y_val = pickle.load(pickle_in)
from sklearn.naive_bayes import GaussianNB
classifier = GaussianNB()
classifier.fit(X_train, Y_train)
Y_pred = classifier.predict(X_val)
from sklearn.metrics import confusion_matrix, accuracy_score
cm = confusion_matrix(Y_val, Y_pred)
print(cm)
accuracy_score(Y_val, Y_pred)
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, models
from keras.callbacks import ModelCheckpoint
import sklearn
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
total_words = len(word_index)+1
embedding_dim = 4
model = models.Sequential()
model.add(layers.Embedding(total_words, embedding_dim, input_length=max_length, name='embedding_layer'))
model.add(layers.SimpleRNN(64, activation='relu', return_sequences=True, name='rnn1'))
model.add(layers.LSTM(128, dropout=0.2, recurrent_dropout=0.2, return_sequences=True, name='lstm1'))
model.add(layers.SimpleRNN(256, activation='relu', return_sequences=True, name='rnn2'))
model.add(layers.LSTM(512, dropout=0.2, recurrent_dropout=0.2, return_sequences=True, name='lstm2'))
model.add(layers.SimpleRNN(1024, activation='relu', name='rnn3'))
model.add(layers.Dense(5, activation='softmax'))
model.summary()
from keras.callbacks import ModelCheckpoint
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
epochs = 50
filepath = '/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/Models/model-{epoch:02d}-performance-{val_accuracy:.2f}-{val_loss:.2f}.hdf5'
checkpoint_acc = ModelCheckpoint(filepath=filepath, monitor='val_accuracy', verbose=1, save_best_only=True, mode='max')
checkpoint_loss = ModelCheckpoint(filepath=filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='min')
callbacks = [checkpoint_acc, checkpoint_loss]
history = model.fit(X_train, Y_train, validation_data=(X_val, Y_val), epochs=epochs, callbacks=callbacks)
"""Re_Train
--
"""
r_model = tf.keras.models.load_model('/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/Models/model-37-performance-0.61-1.16.hdf5')
from keras.callbacks import ModelCheckpoint
r_model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
epochs = 100
filepath = '/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/Models/model-v2-{epoch:02d}-performance-{val_accuracy:.2f}-{val_loss:.2f}.hdf5'
checkpoint_acc = ModelCheckpoint(filepath=filepath, monitor='val_accuracy', verbose=1, save_best_only=True, mode='max')
checkpoint_loss = ModelCheckpoint(filepath=filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='min')
callbacks = [checkpoint_acc, checkpoint_loss]
history = r_model.fit(X_train, Y_train, validation_data=(X_val, Y_val), epochs=epochs, callbacks=callbacks)
r_model = tf.keras.models.load_model('/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/Models/model-v2-51-performance-0.63-1.65.hdf5')
from keras.callbacks import ModelCheckpoint
r_model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
epochs = 15
filepath = '/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/Models/model-v3-{epoch:02d}-performance-{val_accuracy:.2f}-{val_loss:.2f}.hdf5'
checkpoint_acc = ModelCheckpoint(filepath=filepath, monitor='val_accuracy', verbose=1, save_best_only=True, mode='max')
checkpoint_loss = ModelCheckpoint(filepath=filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='min')
callbacks = [checkpoint_acc, checkpoint_loss]
history = r_model.fit(X_train, Y_train, validation_data=(X_val, Y_val), epochs=epochs, callbacks=callbacks, batch_size = 128)
"""Save Model
--
"""
r_model.save('/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/Models/model-v3-15-performance-0.60-2.13.hdf5') #save weights
"""Learning Visualization
--
"""
import matplotlib.pyplot as plt
train_acc = [0.5981, 0.6014, 0.6018, 0.6051, 0.6090, 0.6100, 0.6140, 0.6167, 0.6172, 0.6182, 0.6203, 0.6237, 0.6197, 0.6246, 0.6259]
val_acc = [0.5866, 0.5808, 0.5878, 0.5890, 0.5843, 0.5965, 0.5988, 0.5936, 0.5948, 0.5983, 0.6035, 0.5959, 0.5977, 0.6017, 0.5919]
train_loss = [1.0881, 1.0705, 1.0616, 1.0499, 1.0418, 1.0333, 1.0271, 1.0162, 1.0149, 1.0098, 1.0047, 1.0002, 0.9969, 0.9879, 0.9850]
val_loss = [1.0955, 1.0936, 1.0891, 1.0681, 1.0925, 1.0782, 1.0702, 1.0689, 1.0638, 1.0692, 1.0665, 1.0806, 1.0697, 1.0723, 1.0669]
epochs_range = range(15)
plt.figure(figsize=(18, 6))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
"""Performance Analysis
--
"""
model = tf.keras.models.load_model('/content/drive/MyDrive/SQA/Project Works/Datasets/Pickle Data/Models/model-v3-10-performance-0.62-2.03.hdf5')
records = model.evaluate(X_test, Y_test)
predictions = model.predict(X_test) # predict output for all test data
scores = tf.nn.softmax(predictions)
Y_pred = []
for score in scores:
Y_pred.append(np.argmax(score))
Y_pred = np.array(Y_pred) # predicted labels
# Defining function for confusion matrix plot
def plot_confusion_matrix(Y_test, Y_pred, Classes, normalize=False, title=None, cmap=plt.cm.Blues):
# Compute the confusion matrix
conf_mat = confusion_matrix(Y_test, Y_pred)
if normalize:
conf_mat = conf_mat.astype('float32') / conf_mat.sum(axis=1)[:, np.newaxis]
print(title)
else:
print(title)
fig, ax = plt.subplots(figsize=(6,6))
im = ax.imshow(conf_mat, interpolation='nearest', cmap=cmap)
ax.figure.colorbar(im, ax=ax)
# We want to show all ticks...
ax.set(xticks=np.arange(conf_mat.shape[1]), yticks=np.arange(conf_mat.shape[0]),
xticklabels=Classes, yticklabels=Classes,
title=title, ylabel='True label', xlabel='Predicted label')
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor")
# Loop over data dimensions and create text annotations.
fmt = '.2f' if normalize else 'd'
thresh = conf_mat.max() / 2.
for i in range(conf_mat.shape[0]):
for j in range(conf_mat.shape[1]):
ax.text(j, i, format(conf_mat[i, j], fmt),
ha="center", va="center",
color="white" if conf_mat[i, j] > thresh else "black")
fig.tight_layout()
return ax
np.set_printoptions(precision=2)
from sklearn.metrics import confusion_matrix
#Plotting the confusion matrix
confusion_mtx = confusion_matrix(Y_test, Y_pred)
# Plotting non-normalized confusion matrix
plot_confusion_matrix(Y_test, Y_pred, Classes = ['* ', '** ', '*** ', '**** ', '*****'], title='Confusion Matrix')
#Plotting normalized confusion matrix
plot_confusion_matrix(Y_test, Y_pred, Classes = ['* ', '** ', '*** ', '**** ', '*****'], normalize = True, title = 'Confusion Matrix - Normalized')
from sklearn import metrics
def get_metrics(true_labels, predicted_labels):
print('Accuracy:', np.round(metrics.accuracy_score(true_labels, predicted_labels), 4))
print('Precision:', np.round(metrics.precision_score(true_labels, predicted_labels, average='weighted'),4))
print('Recall:', np.round(metrics.recall_score(true_labels, predicted_labels, average='weighted'), 4))
print('F1 Score:', np.round(metrics.f1_score(true_labels, predicted_labels, average='weighted'), 4))
get_metrics(Y_test, Y_pred)
def display_classification_report(true_labels, predicted_labels, Classes):
report = metrics.classification_report(y_true=true_labels, y_pred=predicted_labels, target_names=Classes)
print("\nReport:\n"+report)
display_classification_report(Y_test, Y_pred, Classes=['* ', '** ', '*** ', '**** ', '*****'])
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import roc_curve, auc, roc_auc_score
target= ['* ', '** ', '*** ', '**** ', '*****']
# set plot figure size
fig, c_ax = plt.subplots(1,1, figsize = (12, 8))
# function for scoring roc auc score for multi-class
def multiclass_roc_auc_score(y_test, y_pred, average="macro"):
lb = LabelBinarizer()
lb.fit(y_test)
y_test = lb.transform(y_test)
y_pred = lb.transform(y_pred)
for (idx, c_label) in enumerate(target):
fpr, tpr, thresholds = roc_curve(y_test[:,idx].astype(int), y_pred[:,idx])
c_ax.plot(fpr, tpr, label = '%s (AUC:%0.2f)' % (c_label, auc(fpr, tpr)))
c_ax.plot(fpr, fpr, 'b-', label = 'Random Guessing')
return roc_auc_score(y_test, y_pred, average=average)
print('ROC AUC score:', multiclass_roc_auc_score(Y_test, Y_pred))
c_ax.legend()
c_ax.set_xlabel('False Positive Rate')
c_ax.set_ylabel('True Positive Rate')
plt.show()