Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

amazon.py 20 KB

You have to be logged in to leave a comment. Sign In
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
  1. import pandas as pd
  2. import pickle
  3. import dash
  4. import dash_core_components as dcc
  5. import dash_html_components as html
  6. import dash_table as dt
  7. import plotly.plotly as py
  8. from dash.dependencies import Input, Output, State
  9. import plotly.graph_objs as go
  10. from sklearn.feature_extraction.text import TfidfVectorizer, TfidfTransformer, CountVectorizer
  11. import nltk
  12. from src.SupportFunction import show_word, show_word_tfidf, stops, meaningful_word_specific
  13. #Data Amazon
  14. dfAmazon = pickle.load(open('amazon_5_percent_complete.sav', 'rb'))
  15. dfAmazonPlot = dfAmazon
  16. #Model
  17. model_title = pickle.load(open('model_predict_amazon_title.sav', 'rb'))
  18. model_review = pickle.load(open('model_predict_amazon_review.sav', 'rb'))
  19. model_combination = pickle.load(open('model_predict_amazon_combination.sav', 'rb'))
  20. #Generate Table
  21. def generate_table(dataframe, pagesize = 10):
  22. return dt.DataTable(
  23. id='table-multicol-sorting',
  24. columns=[{"name": i, "id": i} for i in list(dataframe.columns) ],
  25. pagination_settings={'current_page': 0,'page_size': pagesize},
  26. pagination_mode='be',
  27. style_table={'overflowX': 'scroll'},
  28. style_cell={'minWidth': '0px', 'maxWidth': '180px',
  29. 'whiteSpace': 'no-wrap',
  30. 'overflow': 'hidden',
  31. 'textOverflow': 'ellipsis',
  32. },
  33. css=[{'selector': '.dash-cell div.dash-cell-value',
  34. 'rule': 'display: inline; white-space: inherit; overflow: inherit; text-overflow: inherit;'
  35. }],
  36. sorting='be',
  37. sorting_type='multi',
  38. sorting_settings=[]
  39. )
  40. external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
  41. app = dash.Dash(__name__)
  42. server = app.server
  43. app.title = 'Dashboard Amazon Sentiment'
  44. app.layout = html.Div([
  45. html.H1('Dashboard Amazon Sentiment Prediction'),
  46. html.H3('''
  47. Created by: Cornellius Yudha Wijaya
  48. ''')
  49. ,
  50. dcc.Tabs(id="tabs", value='tab-all', children=[ #Table
  51. dcc.Tab(label='Data amazon', value='tab-1', children=[
  52. html.Div([
  53. html.Div([
  54. html.P('Sentiment: '),
  55. dcc.Dropdown(
  56. id='filtersentiment',
  57. options=[i for i in [{ 'label': 'All', 'value': '' },
  58. { 'label': 'Positive', 'value': 'Positive' },
  59. { 'label': 'Neutral', 'value': 'Neutral' },
  60. { 'label': 'Negative', 'value': 'Negative' }
  61. ]],
  62. value=''
  63. )
  64. ], className='col-4'),
  65. html.Div([
  66. html.P('Rating: '),
  67. dcc.Dropdown(
  68. id='filterrating',
  69. options=[i for i in [{ 'label': 'All', 'value': '' },
  70. { 'label': '1', 'value': 1 },
  71. { 'label': '2', 'value': 2 },
  72. { 'label': '3', 'value': 3 },
  73. { 'label': '4', 'value': 4 },
  74. { 'label': '5', 'value': 5 },
  75. ]],
  76. value=''
  77. )
  78. ], className='col-4')
  79. ], className = 'row'),
  80. html.Br(),
  81. html.Div([
  82. html.Div([
  83. html.Br(),
  84. html.Button('Search', id='buttonsearch', style=dict(width='100%'))
  85. ], className='col-2')
  86. ], className='row'),
  87. html.Br(),html.Br(),html.Br(),
  88. html.Div([
  89. html.Div([
  90. html.P('Max Rows : '),
  91. dcc.Input(
  92. id='filterrowstable',
  93. type='number',
  94. value=10,
  95. style=dict(width='100%')
  96. )
  97. ], className='col-1')
  98. ], className='row'),
  99. html.Center([
  100. html.H2('Data Amazon', className='title'),
  101. html.Div(id='tablediv', children = generate_table(dfAmazon))
  102. ])
  103. ]),
  104. dcc.Tab(label='EDA Plots', value='tab-2', children =[ #EDA Plot
  105. html.Div(children=[
  106. html.Div(children=[
  107. html.P('Kind :'),
  108. dcc.Dropdown(
  109. id='jenisplotcategory',
  110. options=[{'label': i, 'value': i} for i in ['Hist','Bar','Box','Violin']],
  111. value='Hist'
  112. )
  113. ], className = 'col-3'),
  114. html.Div(children=[
  115. html.P('Analysis :'),
  116. dcc.Dropdown(
  117. id='xplotcategory',
  118. options=[{'label': i, 'value': i} for i in ['Sentiment','Rating']],
  119. value='Sentiment'
  120. )
  121. ], className = 'col-3'),
  122. html.Div(children=[
  123. html.P('Number :'),
  124. dcc.Dropdown(
  125. id='yplotcategory',
  126. options=[{'label': i, 'value': i} for i in ['Title_length', 'Review_length', 'Title_sentence_wo_punc', 'Review_sentence_wo_punc']],
  127. value='Title_length'
  128. )
  129. ], className = 'col-3'),
  130. html.Div([
  131. html.P('Stats : '),
  132. dcc.Dropdown(
  133. id='statsplotcategory',
  134. options=[i for i in [{ 'label': 'Mean', 'value': 'mean' },
  135. { 'label': 'Standard Deviation', 'value': 'std' },
  136. { 'label': 'Count', 'value': 'count' },
  137. { 'label': 'Min', 'value': 'min' },
  138. { 'label': 'Max', 'value': 'max' },
  139. { 'label': '25th Percentiles', 'value': '25%' },
  140. { 'label': 'Median', 'value': '50%' },
  141. { 'label': '75th Percentiles', 'value': '75%' }]],
  142. value='mean',
  143. disabled=False
  144. )
  145. ], className='col-3')
  146. ], className = 'row'),
  147. html.Br(),html.Br(),html.Br(),html.Br(),html.Br(),
  148. dcc.Graph(
  149. id='categorygraph'
  150. )
  151. ]),
  152. dcc.Tab(label='Word plots', value ='tab-3', children = [ #Word Generator Plot
  153. html.Div(children = [
  154. html.Div(children = [
  155. html.P('Sentiment: '),
  156. dcc.Dropdown(
  157. id='sentimentword',
  158. options=[i for i in [{ 'label': 'All', 'value': '' },
  159. { 'label': 'Positive', 'value': 'Positive' },
  160. { 'label': 'Neutral', 'value': 'Neutral' },
  161. { 'label': 'Negative', 'value': 'Negative' }
  162. ]],
  163. value=''
  164. )
  165. ], className='col-3'),
  166. html.Div(children = [
  167. html.P('Type: '),
  168. dcc.Dropdown(
  169. id = 'typeword',
  170. options = [{'label' : 'Count', 'value': 'Count'},
  171. {'label': 'TF-IDF', 'value': 'TF-IDF'}],
  172. value = 'Count'
  173. )
  174. ], className ='col-3'),
  175. html.Div(children = [
  176. html.P('Direction: '),
  177. dcc.Dropdown(
  178. id = 'directionword',
  179. options = [{'label' : 'Highest', 'value': 'Highest'},
  180. {'label': 'Lowest', 'value': 'Lowest'}],
  181. value = 'Highest'
  182. )
  183. ], className = 'col-3'),
  184. html.Div(children = [
  185. html.P('Category: '),
  186. dcc.Dropdown(
  187. id = 'categoryword',
  188. options = [{'label' : 'Title', 'value': 'Title_meaningful'},
  189. {'label': 'Review', 'value': 'Review_meaningful'}],
  190. value = 'Title_meaningful'
  191. )
  192. ], className = 'col-3')
  193. ], className = 'row'),
  194. html.Br(), html.Br(),
  195. html.Div([
  196. html.Div(children = [
  197. html.P('Gram: '),
  198. dcc.Dropdown(
  199. id = 'gramword',
  200. options = [{'label' : 'Unigram', 'value': 1},
  201. {'label': 'Bigram', 'value': 2}],
  202. value = 1
  203. )
  204. ], className = 'col-3'),
  205. html.Div(children=[
  206. html.P('Number: '),
  207. dcc.Input(
  208. id='numberword',
  209. type='number',
  210. value=20,
  211. style=dict(width='100%')
  212. )
  213. ], className='col-1'),
  214. html.Div([
  215. html.Br(),
  216. html.Button('Search', id='buttonword', style=dict(width='100%'))
  217. ], className='col-2')
  218. ], className='row'),
  219. html.Br(),
  220. dcc.Graph(
  221. id='wordgraph'
  222. )
  223. ]),
  224. dcc.Tab(label = 'Sentiment Prediction Model', value = 'tab=4', children=[
  225. html.Div([
  226. html.Div([
  227. html.Center([
  228. html.H2('Amazon Sentiment Prediction Model', className='title')])
  229. ]),
  230. html.Br(),
  231. html.Div([
  232. html.P('Insert Title: '),
  233. dcc.Input(
  234. id ='titlepredict',
  235. type='text',
  236. placeholder='Enter the title..',
  237. value = '',
  238. style=dict(width='100%')
  239. )], className = 'col-12 row'),
  240. html.Br(),
  241. html.Div([
  242. html.P('Insert Review: '),
  243. dcc.Textarea(
  244. id = 'reviewpredict',
  245. placeholder='Enter the review..',
  246. value='',
  247. style={'width': '100%'}
  248. )], className = 'col-12 row'
  249. ),
  250. html.Br(),
  251. html.Div([
  252. html.Button('Predict', id='buttonpredict', style=dict(width='100%'))
  253. ], className='col-2 row'),
  254. html.Div([
  255. html.Center([],id ='outputpredict')
  256. ])]
  257. )]
  258. )
  259. ],
  260. style = {
  261. 'fontFamily': 'system-ui'
  262. }, content_style = {
  263. 'fontFamily': 'Arial',
  264. 'borderBottom': '1px solid #d6d6d6',
  265. 'borderLeft': '1px solid #d6d6d6',
  266. 'borderRight': '1px solid #d6d6d6',
  267. 'padding': '44px'
  268. })
  269. ], style ={
  270. 'maxWidth': '1200px',
  271. 'margin': '0 auto'
  272. })
  273. #Table Callback
  274. @app.callback(
  275. Output('table-multicol-sorting', "data"),
  276. [Input('table-multicol-sorting', "pagination_settings"),
  277. Input('table-multicol-sorting', "sorting_settings")])
  278. def callback_sorting_table(pagination_settings, sorting_settings):
  279. if len(sorting_settings):
  280. dff = dfAmazon.sort_values(
  281. [col['column_id'] for col in sorting_settings],
  282. ascending=[
  283. col['direction'] == 'asc'
  284. for col in sorting_settings
  285. ],
  286. inplace=False
  287. )
  288. else:
  289. # No sort is applied
  290. dff = dfAmazon
  291. return dff.iloc[
  292. pagination_settings['current_page']*pagination_settings['page_size']:
  293. (pagination_settings['current_page'] + 1)*pagination_settings['page_size']
  294. ].to_dict('rows')
  295. @app.callback(
  296. Output(component_id='tablediv', component_property='children'),
  297. [Input('buttonsearch', 'n_clicks'),
  298. Input('filterrowstable', 'value')],
  299. [State('filtersentiment', 'value'),
  300. State('filterrating', 'value')
  301. ]
  302. )
  303. def update_table(n_clicks,maxrows, sentiment, rating):
  304. global dfAmazon
  305. dfAmazon = pickle.load(open('amazon_5_percent_complete.sav', 'rb'))
  306. if (sentiment != '') & (rating != ''):
  307. dfAmazon = dfAmazon[(dfAmazon['Sentiment'] == sentiment) & (dfAmazon['Rating'] == rating)]
  308. elif (sentiment != ''):
  309. dfAmazon = dfAmazon[dfAmazon['Sentiment'] == sentiment]
  310. elif (rating != ''):
  311. dfAmazon = dfAmazon[dfAmazon['Rating'] == rating]
  312. return generate_table(dfAmazon, pagesize=maxrows)
  313. #callback EDA plots
  314. listGoFunc ={
  315. 'Bar': go.Bar,
  316. 'Box' : go.Box,
  317. 'Violin' : go.Violin
  318. }
  319. def generateValuePlot(xplot,yplot,stats = 'mean'):
  320. return{
  321. 'x': {
  322. 'Bar': dfAmazonPlot[xplot].unique(),
  323. 'Box': dfAmazonPlot[xplot],
  324. 'Violin': dfAmazonPlot[xplot]
  325. },
  326. 'y': {
  327. 'Bar': dfAmazonPlot.groupby(xplot)[yplot].describe()[stats],
  328. 'Box': dfAmazonPlot[yplot],
  329. 'Violin': dfAmazonPlot[yplot]
  330. }
  331. }
  332. @app.callback(
  333. Output(component_id= 'categorygraph', component_property = 'figure'),
  334. [Input(component_id='jenisplotcategory', component_property = 'value'),
  335. Input(component_id='xplotcategory', component_property = 'value'),
  336. Input(component_id='yplotcategory', component_property = 'value'),
  337. Input(component_id='statsplotcategory', component_property='value')]
  338. )
  339. def callback_update_category_graph(jenisplot, xplot, yplot, stats):
  340. dfAmazonPlot = pickle.load(open('amazon_5_percent_complete.sav', 'rb'))
  341. if jenisplot != 'Hist':
  342. newDict = dict(
  343. layout = go.Layout(
  344. title = '{} Plot Amazon'.format(jenisplot),
  345. xaxis = {"title": f'{xplot}'},
  346. yaxis = {'title': f'{yplot}'},
  347. boxmode = 'group',
  348. violinmode ='group'
  349. ),
  350. data = [
  351. listGoFunc[jenisplot](
  352. x = generateValuePlot(xplot,yplot)['x'][jenisplot],
  353. y = generateValuePlot(xplot,yplot, stats)['y'][jenisplot]
  354. )]
  355. )
  356. return newDict
  357. else:
  358. if xplot == 'Sentiment':
  359. color = ['red', 'blue', 'green']
  360. newDict = dict(
  361. data=[
  362. go.Histogram(
  363. x=dfAmazonPlot[dfAmazonPlot['Sentiment'] == i][yplot],
  364. name= i,
  365. marker=dict(
  366. color=j,
  367. opacity = 0.7
  368. )
  369. )
  370. for i,j in zip(dfAmazonPlot['Sentiment'].unique(), color)],
  371. layout=go.Layout(
  372. title='Histogram {} Amazon'.format(yplot),
  373. xaxis=dict(title=yplot),
  374. yaxis=dict(title='Count'),
  375. height=400, width=1000
  376. )
  377. )
  378. return newDict
  379. elif xplot == 'Rating':
  380. color = ['red', 'green', 'blue', 'yellow', 'brown']
  381. newDict = dict(
  382. data=[
  383. go.Histogram(
  384. x=dfAmazonPlot[dfAmazonPlot['Rating'] == i][yplot],
  385. name= str(i),
  386. marker=dict(
  387. color=j,
  388. opacity = 0.7
  389. )
  390. )
  391. for i, j in zip(dfAmazonPlot['Rating'].unique(), color)],
  392. layout=go.Layout(
  393. title='Histogram {} Amazon'.format(yplot),
  394. xaxis=dict(title=yplot),
  395. yaxis=dict(title='Count'),
  396. height=400, width=1000
  397. )
  398. )
  399. return newDict
  400. @app.callback(
  401. Output(component_id='statsplotcategory', component_property='disabled'),
  402. [Input(component_id='jenisplotcategory', component_property='value')]
  403. )
  404. def update_disabled_stats(jenisplot):
  405. if(jenisplot == 'Bar') :
  406. return False
  407. return True
  408. # Callback word plot
  409. @app.callback(
  410. Output(component_id='wordgraph', component_property='figure'),
  411. [Input('buttonword', 'n_clicks')],
  412. [State('sentimentword', 'value'),
  413. State('typeword', 'value'),
  414. State('directionword','value'),
  415. State('numberword','value'),
  416. State('categoryword', 'value'),
  417. State('gramword', 'value')
  418. ]
  419. )
  420. def word_graph(n_clicks, sentiment, type, direction, number, category,gram):
  421. dfAmazonPlot = pickle.load(open('amazon_5_percent_complete.sav', 'rb'))
  422. if type == 'Count':
  423. data = show_word(sentiment, category, gram, direction, number, df = dfAmazonPlot)
  424. elif type == 'TF-IDF':
  425. data = show_word_tfidf(gram, sentiment, category, direction, number, df = dfAmazonPlot)
  426. figure_word = dict(
  427. data = [go.Bar(
  428. y=data['y'],
  429. x=data['x']
  430. )],
  431. layout = go.Layout(
  432. title="{} {} {}-gram {} words of the {} {}".format(number, direction, gram, type, sentiment, category),
  433. yaxis=dict(
  434. ticklen=8
  435. )
  436. ))
  437. return figure_word
  438. # Callback Prediciton Model
  439. @app.callback(
  440. Output(component_id='outputpredict', component_property='children'),
  441. [Input('buttonpredict', 'n_clicks')],
  442. [State('titlepredict', 'value'),
  443. State('reviewpredict', 'value')]
  444. )
  445. def amazon_predict(n_clicks, title_text, review_text):
  446. predict_dict = {'Negative': 0, 'Neutral': 1, 'Positive': 2}
  447. title_text = str(title_text)
  448. review_text = str(review_text)
  449. if (title_text == '') and (review_text == ''):
  450. return html.H3('Please fill either the title or the review text box')
  451. elif (title_text != '') and (review_text == ''):
  452. title = model_title.predict([title_text])[0]
  453. title_prob = model_title.predict_proba([title_text])[0, predict_dict[title]]
  454. return [html.H3('This title is classified as {} Sentiment text with probability {}%'.format(title, round(title_prob*100,2)))]
  455. elif (title_text == '') and (review_text != ''):
  456. review = model_review.predict([review_text])[0]
  457. review_prob = model_review.predict_proba([review_text])[0, predict_dict[review]]
  458. return [html.H3('This review is classified as {} Sentiment text with probability {}%'.format(review, round(review_prob*100,2)))]
  459. elif (title_text != '') and (review_text != ''):
  460. title = model_title.predict([title_text])[0]
  461. title_prob = model_title.predict_proba([title_text])[0, predict_dict[title]]
  462. review = model_review.predict([review_text])[0]
  463. review_prob = model_review.predict_proba([review_text])[0, predict_dict[review]]
  464. combination_text = ' '.join([title_text, review_text])
  465. combination = model_combination.predict([combination_text])[0]
  466. combination_prob = model_combination.predict_proba([combination_text])[0, predict_dict[combination]]
  467. return [html.H3('The Title is classified as {} Sentiment text with probability {}%'.format(title, round(title_prob*100,2))),
  468. html.H3('The Review is classified as {} Sentiment text with probability {}%'.format(review, round(review_prob*100,2))),
  469. html.H3('Combination of the Title and The Review is classified as {} Sentiment text with probability {}%'.format(combination, round(combination_prob*100)))]
  470. if __name__ == '__main__':
  471. app.run_server(debug=True)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...