-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsentiment_analysis.html
More file actions
438 lines (348 loc) · 16.6 KB
/
sentiment_analysis.html
File metadata and controls
438 lines (348 loc) · 16.6 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<!-- META TAGS-->
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Twitter Sentiment Analysis ~ Tanmay's Portfolio</title>
<meta name="description" content="Tanmay's Career Portfolio・タンマイのキャリアポートフォリオ">
<meta name="twitter:image" content="photos/Helloname.jpeg">
<meta property="og:image" content="photos/Helloname.jpeg">
<!-- All the important imports-->
<link rel="icon" type="image/x-icon" href="photos/Favicon.png">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Abel">
<link href='https://fonts.googleapis.com/css?family=Rubik' rel='stylesheet'>
<link rel="stylesheet" href="https://fonts.googleapis.com/earlyaccess/kokoro.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP" rel="stylesheet">
<link rel="stylesheet" href="css_folder/styles.css">
<link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" />
<link rel="stylesheet" href="css_folder/data_analysis_styles.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.4.0/styles/atom-one-dark.min.css">
</head>
<body class="fade-in-text">
<!-- NAV BAR-->
<header class="nav-bar">
<div id="navitem"><h3><a href="index.html">Home</a></h3></div>
<div id="navitem"><h3><a href="#top">Top of Page</a></h3></div>
</header>
<h2 class="tottori_title">Twitter Sentiment Analysis On Python to find out the sentiment of people in Japan in regards to the 'Tourism in Tottori'</h2>
<h3 class="tottori_japan_title">日本語での説明はこちら</h3>
<div class="data_intro">
<p class="intro">Ever wondered what the people think about a certain topic over the internet? Or what kind of sentiment they have regarding
the topic? Current developments in Machine Learning and Data Mining have enabled us to find sentiment of the masses
over the internet regarding on almost any topic.
</p>
<img class="data_intro_photo" src="photos/graph_woman_laugh.png" alt="Photo_of_women_doing_graph" >
</div>
<div class="intro_div">
<p class="intro_desc">
The current topic will look into how the netizens on Twitter feel about Tourism in Tottori and gain some insights into people's
tendency of looking at Tottori as a potential place for a holiday
</p>
<p class="intro_desc_jp">日本語説明</p>
<p id="date">Made on 24th March 2023</p>
</div>
<img class="tottoriimg" src="photos/Tottori.jpeg">
<div class="senti_analysis_body">
<h2 id="question1" ><span>What is Sentiment Analysis?</span></h2>
<p class="projectbodycontent" id="p1">
Sentiment analysis (or opinion mining) is a natural language processing (NLP) technique used to determine whether data is positive, negative or neutral. Sentiment analysis is often performed on textual data to help businesses monitor brand and product sentiment in customer feedback, and understand customer needs.
<br>
However, Sentiment analysis can be used for research purposes as well!
Lets have a look!
</p>
<p class="projectbodycontent" id="p2">
Japan's countryside has been struggling to get its tourism industry running and back on track
since the end of the pandemic. <span>What could be the case?</span>
</p>
<p class="projectbodycontent" id="p3">In this context the <a href="https://www.tottori-guide.jp/zenkokuwari-tottori/">Tottori's prefectural government</a> has put out a lot of offers to attract
more tourist from all over the country and even abroad, but how has the public reacted to it?
</p>
<p class="projectbodycontent" id="p4">
One way to find out that perception is by doing <span>sentiment analysis</span> using the
python programming language
</p>
<p class="projectbodycontent" id="p5">
I have tried to solve this problem through the following steps:
<ol class="projectbodycontent" id="projectlist">
<li>Data mining around a 1000 tweets from Twitter regarding the keyword: 鳥取観光</li>
<li>Using Google Translate packages in python to translate all the mined tweets</li>
<li>Use Natural Language processing packages such 'Roberta' by hugging face to perform Sentiment analysis</li>
<li>Visualise the result on a graph</li>
</ol>
</p>
<p class="projectbodycontent" id="p6">
So let's get started
<br>
We wil mine tweets for the first step, we need some libraries installed to Mine tweets
</p>
</div>
<pre>
<code>
import snscrape.modules.twitter as sntwitter
import pandas as pd
</code>
</pre>
<p class="senti_analysis_body" id="p7">Next we mine tweets from Twitter (I have used a method where we don't need to use the twitter API!) I used the keyword '鳥取観光' to mine the 1000 tweets from all over Twitter in the span of One year from Feb 20, 2022 to Feb 20, 2023 </p>
<pre>
<code>
query = "鳥取観光 until:2023-02-20 since:2022-02-20"
tweets = []
limit = 1000
for tweet in sntwitter.TwitterSearchScraper(query).get_items():
if len(tweets) == limit:
break
else:
tweets.append([tweet.date, tweet.user.username, tweet.content])
df = pd.DataFrame(tweets, columns = ['Date', 'User', 'Tweet'])
df.to_csv('tottori_tweets.csv')
</code>
</pre>
<p class="senti_analysis_body" id="p8">
We check if the dataset is perfectly mined from the website using the following code
</p>
<pre>
<code>
import pandas as pd
data = pd.read_csv("tottori_tweets.csv")
print(data.head())
</code>
</pre>
<p class="senti_analysis_body">
The output will look like the following in the terminal
</p>
<pre>
<code>
Unnamed: 0 Date User \
0 0 2023-02-19 23:26:52+00:00 senryuji_hino
1 1 2023-02-19 17:25:52+00:00 oimo_0222
2 2 2023-02-19 13:16:13+00:00 hiko39115
3 3 2023-02-19 01:54:44+00:00 recruit_oe
4 4 2023-02-18 22:38:56+00:00 senryuji_hino
Tweet
0 おはようございます\n\n本日の #泉龍寺 は曇りです\n最高気温4度・最低気温マイナス2度...
1 島根に住んでいる友達と\n鳥取砂丘に行きました🤍\n初鳥取観光は砂丘でした- ̗̀ ( ˶'...
2 【水木しげるロード】【境港夕凪の湯御宿野乃】【境港水産物直売センター】ゲゲゲに楽しい【鳥取境...
3 大江ノ郷自然牧場が、プロが選ぶ「観光・食事・土産物施設100選」に選ばれました✨鳥取県で唯一...
4 おはようございます\n\n本日の #泉龍寺 は雨です\n最高気温11度・最低気温3度\n現在...
</code>
</pre>
<p class="senti_analysis_body" id="p9">
The file will be saved in your directory
<br>
Now that we have our data, it is time to install Google Translate on python!
</p>
<pre>
<code>
pip install googletrans==3.1.0a0
</code>
</pre>
<p class="senti_analysis_body" id="p10">
It will take like a minute to install. <br>
⚠️Attention! For some reason the package does not work in VSCode and always gives some error, try using Google CoLab!
</p>
<p class="senti_analysis_body" id="p11">
After installing the google translate package, we now try to translate all the tweets inside the dataset
</p>
<pre>
<code>
data['English'] = data['Tweet'].apply(translator.translate, src='ja', dest='en').apply(getattr, args=('text',))
data.to_csv('tottori_tweets_translated.csv')
</code>
</pre>
<p class="senti_analysis_body" id="p12">
Checking if the tweets are translated properly
</p>
<pre>
<code>
review = pd.read_csv("tottori_tweets_translated.csv")
print(review.head())
</code>
</pre>
<p class="senti_analysis_body">
The output of the translated tweets is saved in a CSV file and will display an output in the terminal like the following:
</p>
<pre>
<code>
Unnamed: 0 Unnamed: 0.1 Date User \
0 0 0 2023-02-19 23:26:52+00:00 senryuji_hino
1 1 1 2023-02-19 17:25:52+00:00 oimo_0222
2 2 2 2023-02-19 13:16:13+00:00 hiko39115
3 3 3 2023-02-19 01:54:44+00:00 recruit_oe
4 4 4 2023-02-18 22:38:56+00:00 senryuji_hino
Tweet \
0 おはようございます\n\n本日の #泉龍寺 は曇りです\n最高気温4度・最低気温マイナス2度...
1 島根に住んでいる友達と\n鳥取砂丘に行きました🤍\n初鳥取観光は砂丘でした- ̗̀ ( ˶'...
2 【水木しげるロード】【境港夕凪の湯御宿野乃】【境港水産物直売センター】ゲゲゲに楽しい【鳥取境...
3 大江ノ郷自然牧場が、プロが選ぶ「観光・食事・土産物施設100選」に選ばれました✨鳥取県で唯一...
4 おはようございます\n\n本日の #泉龍寺 は雨です\n最高気温11度・最低気温3度\n現在...
English
0 good morning\n\n#Senryu-ji Temple is cloudy to...
1 With friends who live in Shimane\nI went to To...
2 [Mizuki Shigeru Road] [Sakaiminato Yunagi-no-Y...
3 Oenosato Natural Ranch was selected as one of ...
4 good morning\n\nIt's raining at #senryu-ji tod...
</code>
</pre>
<p class="senti_analysis_body" id="p13">
We have successfully translated all the tweets from Japanese to english and also created a new CSV file with all the translated data in the english column. ☀️It is important to note that, since we do not translate directly and use machine translation, it might lose some level of accuracy!
</p>
<p class="senti_analysis_body" id="p14">
Now we install some Natural Language processing libraries
</p>
<pre>
<code>
pip install nltk
pip install transformers
</code>
</pre>
<p class="senti_analysis_body" id="p15">
Now we add all the necessary libraries for doing senitment analysis on the dataset
</p>
<pre>
<code>
from cgitb import text
import csv
import pandas as pd
import nltk
import numpy as np
from transformers import AutoTokenizer
from transformers import AutoModelForSequenceClassification
from scipy.special import softmax
from tqdm.notebook import tqdm
from nltk.sentiment import SentimentIntensityAnalyzer
import urllib.request
</code>
</pre>
<p class="senti_analysis_body" id="p16">
Now we set up a code to output sentiment score for each tweet present in the dataset we created above
</p>
<pre>
<code>
def preprocess(example):
new_example = []
for t in text.split(" "):
t = '@user' if t.startswith('@') and len(t) > 1 else t
t = 'http' if t.startswith('http') else t
new_example.append(t)
return " ".join(new_example)
df = pd.read_csv("tottori_tweets_translated.csv")
example = df['English'][16]
MODEL = f"cardiffnlp/twitter-roberta-base-sentiment-latest"
tokenizer = AutoTokenizer.from_pretrained(MODEL)
model = AutoModelForSequenceClassification.from_pretrained(MODEL)
#Running example on ROBERTA
encoded_text = tokenizer(example, return_tensors='pt')
output = model(**encoded_text)
scores = output[0][0].detach().numpy()
scores = softmax(scores)
scores_dict = {
'Roberta_Neg' : scores[0],
'Roberta_Neu' : scores[1],
'Roberta_Pos' : scores[2]
}
def polarity_scores_roberta(example):
encoded_text = tokenizer(example, return_tensors='pt')
output = model(**encoded_text)
scores = output[0][0].detach().numpy()
scores = softmax(scores)
scores_dict = {
'roberta_neg' : scores[0],
'roberta_neu' : scores[1],
'roberta_pos' : scores[2]
}
return scores_dict
#Whole Data set on ROBERTA
res = {}
for i, row in tqdm(df.iterrows(), total=len(df)):
text = row['English']
myid = row['User']
#roberta_result = polarity_scores_roberta(text)
res[myid] = polarity_scores_roberta(text)
print(pd.DataFrame(res).T)
pd.DataFrame(res).T.to_csv('tottori_tweets_sentiment_scores.csv')
</code>
</pre>
<p class="senti_analysis_body" id="p17">The output will look like the following in terminal<br>
It is a set of probability score which tells if the tweet has the possibility of being Negative, Neutral or Positive</p>
<pre>
<code>
roberta_neg roberta_neu roberta_pos
senryuji_hino 0.003258 0.133745 0.862998
oimo_0222 0.001793 0.083986 0.914221
hiko39115 0.003020 0.187635 0.809345
recruit_oe 0.004128 0.146394 0.849479
mamacreamsoda 0.752883 0.196891 0.050227
... ... ... ...
bfziwVEEvdnhknj 0.011227 0.866529 0.122244
KiniTabi 0.003765 0.256433 0.739802
HENA_choco_Late 0.002621 0.042952 0.954427
7QWJV4BLtzussqY 0.003928 0.254124 0.741948
tera_cbr 0.130662 0.633455 0.235883
[626 rows x 3 columns]
</code>
</pre>
<p class="senti_analysis_body" id="p18">
Now aggregating all the tweets and their scores
</p>
<pre>
<code>
roberta_nu = data_1['roberta_neu'].mean()
roberta_p = data_1['roberta_pos'].mean()
print('Negative Sentiment Score:', roberta_n, 'Neutral Sentiment Score:', roberta_nu, 'Positive sentiment Score:', roberta_p)
total = roberta_n + roberta_nu + roberta_p
print('Total Score Probability:', total)
</code>
</pre>
<p class="senti_analysis_body" id="p18">The output will look like the following in the terminal:</p>
<pre>
<code>
Negative Sentiment Score: 0.06635993733833866 Neutral Sentiment Score: 0.4121005301733227 Positive sentiment Score: 0.5215395210942492
Total Score Probability: 0.9999999886059106
</code>
</pre>
<p class="senti_analysis_body" id="p19">The output looks good but it does not look visually pleasing or easy to understand for many people. <br>
We can try making a visualisation! The code for it is as follows: </p>
<pre>
<code>
import matplotlib.pyplot as plt
sentiment_score = ['Negative Sentiment', 'Neutral Sentiment', 'Positive Sentiment']
sentiment_p = [roberta_n, roberta_nu, roberta_p]
plt.bar(sentiment_score, sentiment_p)
plt.title('Sentiment Towards Tottori Tourism On Twitter')
plt.xlabel('Type of Sentiment')
plt.ylabel('Sentiment Probability')
plt.show()
</code>
</pre>
<p class="senti_analysis_body" id="p20">
The Final Visualisation for our project will look like the following:
</p>
<img src="photos/tottori_kankou_graph.png" alt="TottoriKankouGraph">
<p class="senti_analysis_body" id="p21">
<span id="conclusion">What do we learn here?</span><br>
Most of the tweets regarding Tottori's Tourism are most on the positive side. Which means that if concerend toursim boards and companies
in Tottori make more Ads to reach people on the internet (at least on twitter), there is a good chance that they will take it positively~~
</p>
<h2 id="endingphrase">Thank you so much for going through the project!</h2>
<a class="tottorikankourepo" href="https://github.com/happygoluckycodeeditor/twittersentimentanalysistottorikankou">Check Project files</a>
<!-- Footer of the page-->
<footer class="foot">
<img src="photos/logo2.png" class="logo2">
<p>©Tanmay Bagwe</p>
<p>Thank you for visiting</p>
<p>Any Questions? Contact me <a href="mailto:tanmay.bagwe.tb@gmail.com">here!</a></p>
</footer>
<!-- Adding Highlight.js Script-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.4.0/highlight.min.js"></script>
<script>hljs.highlightAll();</script>
<!-- Adding AOS Script (Global settings)-->
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
<script>
AOS.init({
once: true,
});
</script>
</body>
</html>