-
Notifications
You must be signed in to change notification settings - Fork 2
/
covid_19_sentiment_analysis.py
207 lines (156 loc) · 6.37 KB
/
covid_19_sentiment_analysis.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
# -*- coding: utf-8 -*-
"""Covid-19_Sentiment_Analysis.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1mLifHfyBov1ly-qwQwIFwhARIsKvQ3Ns
**Covid-19 Sentiment Analysis**
**Context**
I collect recent tweets about the COVID-19 vaccines used in entire world on large scale, as following:
- Pfizer/BioNTech;
- Sinopharm;
- Sinovac;
- Moderna;
- Oxford/AstraZeneca;
- Covaxin;
- Sputnik V.
**Data collection**
The data is collected using tweepy Python package to access Twitter API. For each of the vaccine I use relevant search term (most frequently used in Twitter to refer to the respective vaccine)
**Data collection frequency**
Initial data was merged from tweets about Pfizer/BioNTech vaccine. I added then tweets from Sinopharm, Sinovac (both Chinese-produced vaccines), Moderna, Oxford/Astra-Zeneca, Covaxin and Sputnik V vaccines. The collection was in the first days twice a day, until I identified approximatively the new tweets quota and then collection (for all vaccines) stabilized at once a day, during morning hours (GMT).
**Inspiration**
You can perform multiple operations on the vaccines tweets. Here are few possible suggestions:
- Study the subjects of recent tweets about the vaccine made by various producers;
- Perform various NLP tasks on this data source (topic modelling, sentiment analysis);
- Using the COVID-19 World Vaccination Progress (where we can see the progress of the vaccinations and the countries where the vaccines are administered), you can study the relationship between the vaccination progress and the discussions in social media (from the tweets) about the vaccines.
*Kaggle Dataset*
- https://www.kaggle.com/c/tweet-sentiment-extraction
- https://www.kaggle.com/gpreda/all-covid19-vaccines-tweets
---
**Load Packages**
"""
# Commented out IPython magic to ensure Python compatibility.
import numpy as np
import pandas as pd
import matplotlib
import seaborn as sns
import matplotlib.pyplot as plt
import nltk #https://www.nltk.org/
from nltk.sentiment import SentimentIntensityAnalyzer #https://www.nltk.org/api/nltk.sentiment.html
from textblob import TextBlob #https://textblob.readthedocs.io/en/dev/
from wordcloud import WordCloud, STOPWORDS #https://pypi.org/project/wordcloud/
# %matplotlib inline
import warnings
warnings.simplefilter("ignore")
"""Load the Dataset vaccination_all_tweets.csv """
from google.colab import files
up = files.upload()
tweets_df = pd.read_csv('vaccination_all_tweets.csv')
tweets_df.head(10)
print(f'The Dataset shape is:',tweets_df.shape)
"""So we have 56585 rows and 16 columns"""
tweets_df.info()
tweets_df.describe()
#Lets find out the mising data
def missing_data(data):
total = data.isnull().sum()
percent = (data.isnull().sum()/data.isnull().count()*100)
tt = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])
types = []
for col in data.columns:
dtype = str(data[col].dtype)
types.append(dtype)
tt['Types'] = types
return(np.transpose(tt))
missing_data(tweets_df)
#Unique values
def unique_values(data):
total = data.count()
tt = pd.DataFrame(total)
tt.columns = ['Total']
uniques = []
for col in data.columns:
unique = data[col].nunique()
uniques.append(unique)
tt['Uniques'] = uniques
return(np.transpose(tt))
unique_values(tweets_df)
"""Most frequent values"""
def most_frequent_values(data):
total = data.count()
tt = pd.DataFrame(total)
tt.columns = ['Total']
items = []
vals = []
for col in data.columns:
itm = data[col].value_counts().index[0]
val = data[col].value_counts().values[0]
items.append(itm)
vals.append(val)
tt['Most frequent item'] = items
tt['Frequence'] = vals
tt['Percent from total'] = np.round(vals / total * 100, 3)
return(np.transpose(tt))
most_frequent_values(tweets_df)
"""Visualize the Data Distribution """
def plot_count(feature, title, df, size=1, ordered=True):
f, ax = plt.subplots(1,1, figsize=(4*size,4))
total = float(len(df))
if ordered:
g = sns.countplot(df[feature], order = df[feature].value_counts().index[:20], palette='Set3')
else:
g = sns.countplot(df[feature], palette='Set3')
g.set_title("Number and percentage of {}".format(title))
if(size > 2):
plt.xticks(rotation=90, size=8)
for p in ax.patches:
height = p.get_height()
ax.text(p.get_x()+p.get_width()/2.,
height,
'{:1.2f}%'.format(100*height/total),
ha="center")
plt.show()
# User Name
plot_count('user_name' , "User Name" , tweets_df , 4)
# User Location
plot_count("user_location", "User location", tweets_df,4)
#Tweet Source
plot_count("source", "Source", tweets_df,4)
#Make a word Cloud from dataset
stopwords = set(STOPWORDS)
def show_wordcloud(data, title = None):
wordcloud = WordCloud(
background_color='white',
stopwords=stopwords,
max_words=50,
max_font_size=40,
scale=5,
random_state=1
).generate(str(data))
fig = plt.figure(1, figsize=(10,10))
plt.axis('off')
if title:
fig.suptitle(title, fontsize=20)
fig.subplots_adjust(top=2.3)
plt.imshow(wordcloud)
plt.show()
def show_wordcloud(data, title=""):
text = " ".join(t for t in data.dropna())
stopwords = set(STOPWORDS)
stopwords.update(["t", "co", "https", "amp", "U"])
wordcloud = WordCloud(stopwords=stopwords, scale=4, max_font_size=50, max_words=500,background_color="black").generate(text)
fig = plt.figure(1, figsize=(16,16))
plt.axis('off')
fig.suptitle(title, fontsize=20)
fig.subplots_adjust(top=2.3)
plt.imshow(wordcloud, interpolation='bilinear')
plt.show()
"""Text Word Clouds"""
show_wordcloud(tweets_df['text'] , title = 'Prevalend words in tweets')
india_df = tweets_df.loc[tweets_df.user_location=="India"]
show_wordcloud(india_df['text'], title = 'Prevalent words in tweets from India')
us_df = tweets_df.loc[tweets_df.user_location=="United States"]
show_wordcloud(us_df['text'], title = 'Prevalent words in tweets from US')
uk_df = tweets_df.loc[tweets_df.user_location=="United Kingdom"]
show_wordcloud(uk_df['text'], title = 'Prevalent words in tweets from UK')
ca_df = tweets_df.loc[tweets_df.user_location=="Canada"]
show_wordcloud(ca_df['text'], title = 'Prevalent words in tweets from Canada')