-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sentimental Analysis - NLP Model-s.py
328 lines (153 loc) · 5.2 KB
/
Sentimental Analysis - NLP Model-s.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
#!/usr/bin/env python
# coding: utf-8
# # Kotak Playstore Application Reviews Scarping and NLP
# In[1]:
import google_play_scraper
import warnings
warnings.filterwarnings('ignore')
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import re
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem.wordnet import WordNetLemmatizer
from wordcloud import WordCloud, STOPWORDS,ImageColorGenerator
from transformers import pipeline
sentiment_analysis = pipeline('sentiment-analysis')
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import confusion_matrix,accuracy_score,precision_score,recall_score
# In[2]:
from google_play_scraper import reviews,Sort
# In[3]:
kotak_app = reviews('com.msf.kbank.mobile',count=1000,sort=Sort.NEWEST)
# In[4]:
df_kotak = pd.DataFrame(kotak_app[0])
# In[5]:
df_kotak_ = df_kotak[['userName','content','score','reviewCreatedVersion','at']]
# In[6]:
df_kotak_
# ### Data Cleaning
# In[7]:
filtered_comments=[]
for i in range(0,len(df_kotak_.content)):
text = df_kotak_.content[i].lower()
text = re.sub('[^a-zA-Z]',' ',text.strip())
text = re.sub('\n','',text.strip())
filtered_comments.append(text.strip())
# In[8]:
df_kotak_['filtered_comments'] = filtered_comments
# In[9]:
df_kotak_[df_kotak_['filtered_comments']==''].head()
# In[10]:
df_kotak_.drop(df_kotak_[df_kotak_['filtered_comments']==''].index.tolist(),axis=0,inplace=True)
df_kotak_.reset_index(inplace=True)
df_kotak_.drop(columns=['index'],inplace=True)
# In[11]:
count=[]
for i in range(0,len(df_kotak_.filtered_comments)):
text = len(df_kotak_.filtered_comments[i])
if text <= 3:
a=''
else:
a=text
count.append(a)
# In[12]:
df_kotak_['num'] = count
df_kotak_[df_kotak_['num']==''].head()
# In[13]:
df_kotak_.drop(df_kotak_[df_kotak_['num']==''].index.tolist(),axis=0,inplace=True)
df_kotak_.reset_index(inplace=True)
df_kotak_.drop(columns=['index','num'],inplace=True)
# In[14]:
response =[]
for i in range(0,len(df_kotak_.filtered_comments)):
text = sentiment_analysis(df_kotak_.filtered_comments[i])[0]['label']
response.append(text)
# In[15]:
df_kotak_['response'] = response
# In[16]:
#df_kotak_.to_excel("C:\\Users\\Manikanta\\Downloads\\kotak.xlsx")
# In[17]:
df_kotak_.info()
# In[18]:
df_kotak_.reviewCreatedVersion.replace('None',np.nan,inplace=True)
# ## Word Cloud
# In[19]:
wc = df_kotak_['filtered_comments']
# In[20]:
toz_ = [word_tokenize(word) for word in wc]
# In[21]:
stop_words =[]
for i in (toz_):
a=[]
for j in i:
if len(j) > 2:
if not j in stopwords.words('english'):
a.append(j)
stop_words.append(a)
# In[22]:
lemm = WordNetLemmatizer()
lemmatize=[]
for i in stop_words:
for j in i:
text = ''.join(j)
lemmatize.append(text)
text =' '.join(lemmatize)
# In[23]:
plt.figure(figsize=(10,10))
text = text
stopwords = set(STOPWORDS)
wordcloud = WordCloud(max_font_size=50, max_words=100, background_color="white",scale=3,random_state=0).generate(text)
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off");
# ## Observations By Insights
# In[24]:
plt.figure(figsize=(7,5))
sns.set_style('darkgrid')
plt.title('Sentimental Analysis',fontdict={'family':'times new roman','size':25})
sns.countplot(x=df_kotak_.response,order=df_kotak_.response.value_counts().index,hatch='///')
sns.despine();
# In[25]:
plt.rcParams.update({'figure.figsize':(25,6)})
df_kotak_.groupby(['response','reviewCreatedVersion'])[['reviewCreatedVersion']].count().plot.bar(hatch='||').set_title('Version Wise Sentimental Analysis',fontsize=20)
plt.xticks(fontsize=15);
# In[26]:
plt.figure(figsize=(15,7))
sample = pd.DataFrame(df_kotak_.groupby('reviewCreatedVersion')['score'].mean().round()).reset_index()
plt.title('Version Vs Avg-Rating',fontsize=20)
sns.barplot(x=sample.reviewCreatedVersion,y=sample.score,hatch='...');
# ## NLP Model
# In[27]:
df_kotak_.head()
# In[28]:
x_var = df_kotak_.filtered_comments
y_var = df_kotak_.response
x_train,x_test,y_train,y_test = train_test_split(x_var,y_var,test_size=0.20,random_state=0)
# In[29]:
vec= TfidfVectorizer()
log = LogisticRegression(solver='lbfgs')
model = Pipeline([('vectorizer',vec),('classifier',log)])
model.fit(x_train,y_train)
pred_y = model.predict(x_test)
# In[30]:
cf = confusion_matrix(pred_y,y_test)
print(cf)
# In[31]:
plt.figure(figsize=(10,5))
sns.heatmap(cf,annot=True);
# In[32]:
print('\nAccuarcy Score {:.3f}\n'.format(accuracy_score(y_test,pred_y)))
print('Precision Score {:.3f}\n'.format(precision_score(y_test,pred_y,average='weighted')))
print('Recall Score {:.3f}'.format(recall_score(y_test,pred_y,average='weighted')))
# In[33]:
comment = ['so many bugs are there some times it is not working quickly']
print(model.predict(comment))
# In[35]:
comment =['it is very easy to operate and i have good experience with the app so far']
print(model.predict(comment))