-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPredict User Rating.py
449 lines (228 loc) · 8.06 KB
/
Predict User Rating.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
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
#This project focusses on the following areas :
#Analysis of the dataset
#Understanding of the User's Rating Distribution
#Predict Recommend Status based on the subjective review provided by the user
# In[ ]:
#Cleaning the Datset
# In[ ]:
import pandas as pd
df = pd.read_csv(r"C:\Users\nayacha\Downloads\Consumer Reviews of Amazon Products/1429_1.csv")
df1_oasis = df.iloc[2816:3482,]
df2_fire_16gb = df.iloc[14448:15527,]
df3_paperwhite_4gb = df.iloc[17216:20392,]
df4_voyage = df.iloc[20392:20972,]
df5_paperwhite = df.iloc[20989:21019,]
#df.head(5)
# In[13]:
print(df1_oasis.shape)
print(df2_fire_16gb.shape)
print(df3_paperwhite_4gb.shape)
print(df4_voyage.shape)
print(df5_paperwhite.shape)
# In[14]:
df1_oasis.to_csv('Oasis.csv')
df2_fire_16gb.to_csv('Fire.csv')
df4_voyage.to_csv('Voyage.csv')
# In[15]:
frames = [df3_paperwhite_4gb,df5_paperwhite]
df4_voyage.to_csv('Voyage.csv')
kp = pd.concat(frames)
print(kp.head(5))
print(kp.tail(5))
kp = kp.reset_index()
print(kp.columns)
print(kp['reviews.rating'].describe())
kp.columns = ['Index','ID','Name','ASINS','Brand','Categories','Keys','Manufacturer','ReviewDate','ReviewDateAdded','ReviewDateSeen','PurchasedOnReview','RecommendStatus','ReviewID','ReviewHelpful','Rating','SourceURL','Comments','Title','UserCity','UserProvince','Username']
kp.columns
kp.head(5)
print(kp.columns.nunique())
kp = kp.drop(['ReviewID' , 'UserCity' , 'UserProvince','PurchasedOnReview'],axis = 1)
print(kp.columns.nunique())
print(kp.Rating.value_counts())
kp.Rating.value_counts()
# In[ ]:
#Analysing Data
# In[16]:
kp.RecommendStatus.nunique()
import matplotlib.pyplot as plt
kp.hist(column = 'Rating', by = 'RecommendStatus', color = 'Red')
plt.show()
print(kp.info())
# In[17]:
kp['Categories'] = 'Tablets'
kp['Name'] = 'Amazon Kindle Paperwhite'
print(kp.head(5))
print(kp.ReviewHelpful.value_counts())
# In[18]:
pd.DataFrame(kp[(kp.Rating==5)&(kp.RecommendStatus==False)]['Comments'])
# In[19]:
print(kp.Username.nunique())
print(kp.shape)
sum(kp['Username'].value_counts()>1)
# In[20]:
len(kp['Username'].value_counts()>1)
# In[21]:
kp.head(2)
kp = kp.drop('Keys',axis = 1)
print(kp.columns.nunique())
kp =kp.reset_index()
print(kp.head(2))
# In[ ]:
#Transforming Date Time
# In[22]:
kp.ReviewDate = pd.to_datetime(kp['ReviewDate'], dayfirst= True)
kp.ReviewDateAdded =pd.to_datetime(kp.ReviewDateAdded , dayfirst= True)
#kp.ReviewDateSeen = pd.to_datetime(kp.ReviewDateSeen, dayfirst = True)
# In[23]:
kp['ReviewDateSeen'] = kp['ReviewDateSeen'].str.split(',',expand = True).apply(lambda x:x.str.strip())
kp.ReviewDateSeen = pd.to_datetime(kp.ReviewDateSeen,dayfirst= True)
print(kp.head(4))
# In[ ]:
#Likert Scale Analysis
# In[24]:
import numpy as np
promoters = sum(kp.Rating==5)
passive = sum(kp.Rating == 4)
detractors = sum(np.logical_and(kp.Rating >= 1, kp.Rating <=3))
respondents = promoters+passive+detractors
NPS_P = ((promoters - detractors)/respondents )*100
print(NPS_P)
# In[25]:
print(kp.tail(2))
# In[26]:
kp.plot(x = 'ReviewDate',y = 'Rating', kind = 'line', figsize=(10,10))
# In[27]:
review_date = kp.ReviewDate
rating = kp.Rating
df_dr = pd.concat([review_date,rating],axis = 1)
print(df_dr.tail(5))
print(df_dr.shape)
# In[28]:
df_dr = df_dr.groupby(['ReviewDate','Rating']).size().unstack(fill_value = 0)
print(df_dr.loc['2017-02-04'])
# In[29]:
print(df_dr.head(5))
# In[30]:
df_dr.columns = ['A','B','C','Passive','Promoters']
df_dr['Detractors'] = df_dr['A'] + df_dr['B'] + df_dr['C']
df_dr.head(5)
# In[31]:
df_dr = df_dr.drop(labels = ['A','B','C'],axis = 1)
print(df_dr.head(5))
# In[32]:
df_dr['NPS'] = (df_dr['Promoters'] - df_dr['Detractors']) * 100 / (df_dr['Passive'] + df_dr['Promoters'] + df_dr['Detractors'])
print(df_dr.head(5))
# In[33]:
df_dr = df_dr.reset_index()
df_dr.plot( x = 'ReviewDate', y = 'NPS',kind = 'line', figsize=(10,10))
# In[34]:
df_dr.shape
# In[ ]:
#Sentiment Analysis - NLTK to find Compound Score
# In[35]:
kp.Name.nunique()
kp.head(2)
# In[36]:
data = kp.drop(['Index','ID','Name','ASINS','Brand','Categories','Manufacturer','ReviewDateAdded','ReviewDateSeen','SourceURL'], axis = 1)
# Cleaned Dataset Now becomes
data = data.reset_index()
data.head(5)
# In[37]:
data = data.drop(['ReviewDate'], axis = 1)
data.columns
# In[38]:
def status(data):
if(data == True):
data = "Recommend"
return data
else:
data = "Not Recommend"
return data
data['RecommendStatus'] = pd.DataFrame(data['RecommendStatus'].apply(lambda x : status(x)))
data.head(5)
# In[41]:
dsa = data
dsa['feedback'] = dsa['Comments'] + dsa['Title']
dsa = dsa.drop(['Comments','Title'], axis = 1)
# In[42]:
dsa.head(5)
# In[43]:
import nltk
# In[44]:
from nltk.sentiment.vader import SentimentIntensityAnalyzer
sid = SentimentIntensityAnalyzer()
def polar_score(text):
score = sid.polarity_scores(text)
x = score['compound']
return x
dsa['Compound_Score'] = dsa['feedback'].apply(lambda x : polar_score(x))
# In[45]:
dsa.head(5)
# In[46]:
dsa['length'] = dsa['feedback'].apply(lambda x: len(x) - x.count(" "))
dsa.head(2)
# In[ ]:
#Ideally people who'll Not Recommend the product, would have a lot to say against the features of the product
# In[47]:
import numpy as np
from matplotlib import pyplot
get_ipython().run_line_magic('matplotlib', 'inline')
# In[51]:
bins = np.linspace(0,200,40)
pyplot.hist(dsa[dsa['RecommendStatus'] == 'Not Recommend']['length'],bins,alpha = 0.5,density = True, label = 'Not Recommend')
pyplot.hist(dsa[dsa['RecommendStatus'] == 'Recommend']['length'],bins,alpha = 0.5,density = True, label = 'Recommend')
pyplot.legend(loc = 'upper right')
pyplot.show()
# In[ ]:
#Using TF-IDF and Random Forest to predict Recommendation Status
# In[52]:
import string
import nltk
import re
stopword = nltk.corpus.stopwords.words('english')
ps = nltk.PorterStemmer()
# In[53]:
def clean(text):
no_punct = "".join([word.lower() for word in text if word not in string.punctuation])
tokens = re.split('\W+',no_punct)
text_stem = ([ps.stem(word) for word in tokens if word not in stopword])
return text_stem
# In[54]:
from sklearn.feature_extraction.text import TfidfVectorizer
tf_idf = TfidfVectorizer(analyzer= clean)
Xtf_idfVector = tf_idf.fit_transform(dsa['feedback'])
# In[55]:
import pandas as pd
Xfeatures_data = pd.concat([dsa['Compound_Score'], dsa['length'], pd.DataFrame(Xtf_idfVector.toarray())], axis = 1)
Xfeatures_data.head(5)
# In[ ]:
#dataframe we would be applying Machine Learning to
# In[56]:
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import precision_recall_fscore_support as score
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(Xfeatures_data, dsa['RecommendStatus'], test_size = 0.2)
rf = RandomForestClassifier(n_estimators= 50, max_depth= 20, n_jobs= -1)
rf_model = rf.fit(X_train,y_train)
sorted(zip(rf.feature_importances_,X_train.columns), reverse = True)[0:10]
# In[ ]:
#Applying Grid Search to change hyper parameters and then applying RF
# In[57]:
def compute(n_est, depth):
rf = RandomForestClassifier(n_estimators= n_est, max_depth= depth)
rf_model = rf.fit(X_train, y_train)
y_pred = rf_model.predict(X_test)
precision,recall,fscore,support = score(y_test,y_pred, pos_label= 'Recommend', average = 'binary')
print('Est: {}\ Depth: {}\ Precision: {}\ Recall: {}\ Accuracy: {}'.format(n_est, depth, round(precision,3), round(recall,3), (y_pred == y_test).sum()/ len(y_pred)))
# In[58]:
for n_est in [10,30,50,70]:
for depth in [20,40,60,80,90]:
compute(n_est,depth)
# In[ ]:
#Feature Engineering played a key role in boosting the model's performance matrix.
#The length of the text and calculation of compound_score using sentiment analysis served as a basis to strike a balance between Precision & Recall (0.975 vs 1.0).
#further made the model robust enough to predict user's recommend status to 97.5%
#This concludes our Analysis of the Kindle Paperwhite.