-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
295 lines (262 loc) · 10.4 KB
/
utils.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
import io
import numpy as np
from nltk.corpus import stopwords
import collections
from twokenize import tokenize
import numpy as np
from gensim.models import word2vec
KEYWORDS = {'clinton': ['hillary', 'clinton'],
'trump': ['donald trump', 'trump', 'donald'],
'climate': ['climate'],
'feminism': ['feminism', 'feminist'],
'abortion': ['abortion', 'aborting'],
'atheism': ['atheism', 'atheist']
}
TOPICS_LONG = {'clinton': 'Hillary Clinton',
'trump': 'Donald Trump',
'climate': 'Climate Change is a Real Concern',
'feminism': 'Feminist Movement',
'abortion': 'Legalization of Abortion',
'atheism': 'Atheism'
}
TOPICS_LONG_REVERSE = dict(zip(TOPICS_LONG.values(), TOPICS_LONG.keys()))
def readTweetsOfficial(tweetfile, encoding='windows-1252', tweetcolumn=2, topic="all"):
"""
Read tweets from official files
:param topic: which topic to use, if topic="all", data for all topics is read
:param encoding: which encoding to use, official stance data is windows-1252 encoded
:param tweetcolumn: which column contains the tweets
:return: list of tweets, list of targets, list of labels
"""
tweets = []
targets = []
labels = []
ids = []
for line in io.open(tweetfile, encoding=encoding, mode='r'):
if line.startswith('ID\t'): # empty line
continue
if topic == "all":
tweets.append(line.split("\t")[tweetcolumn])
targets.append(line.split("\t")[tweetcolumn - 1])
lid = line.split("\t")[0]
v = np.zeros(1)
v[0] = lid
ids.append(v)
if tweetcolumn > 1:
labels.append(line.split("\t")[tweetcolumn + 1].strip("\n"))
else:
labels.append("UNKNOWN")
elif topic in line.split("\t")[tweetcolumn - 1].lower():
tweets.append(line.split("\t")[tweetcolumn])
targets.append(line.split("\t")[tweetcolumn - 1])
lid = line.split("\t")[0]
v = np.zeros(1)
v[0] = lid
ids.append(v)
if tweetcolumn > 1:
labels.append(line.split("\t")[tweetcolumn + 1].strip("\n"))
else:
labels.append("UNKNOWN")
return tweets, targets, labels, ids
def istargetInTweet(devdata, target_list):
"""
Check if target is contained in tweet
:param devdata: development data as a dictionary (keys: targets, values: tweets)
:param target_short: short version of target, e.g. 'trump', 'clinton'
:param id: tweet number
:return: true if target contained in tweet, false if not
"""
cntr = 0
ret_dict = {}
for id in devdata.keys():
tweet = devdata.get(id)
target_keywords = KEYWORDS.get(TOPICS_LONG_REVERSE.get(target_list[0]))
target_in_tweet = False
for key in target_keywords:
if key.lower() in tweet.lower():
target_in_tweet = True
break
ret_dict[id] = target_in_tweet
cntr += 1
return ret_dict
def istargetInTweetSing(devdata, target_short):
"""
Check if target is contained in tweet
:param devdata: development data as a dictionary (keys: targets, values: tweets)
:param target_short: short version of target, e.g. 'trump', 'clinton'
:param id: tweet number
:return: true if target contained in tweet, false if not
"""
ret_dict = {}
for id in devdata.keys():
tweet = devdata.get(id)
target_keywords = KEYWORDS.get(target_short)
target_in_tweet = False
for key in target_keywords:
if key.lower() in tweet.lower():
target_in_tweet = True
break
ret_dict[id] = target_in_tweet
return ret_dict
def filterStopwords(tokenised_tweet, filter="all"):
"""
Remove stopwords from tokenised tweet
:param tokenised_tweet: tokenised tweet
:return: tweet tokens without stopwords
"""
if filter == "all":
stops = stopwords.words("english")
stops.extend(["\"", "#", "$", "%", "&", "\\", "'", "(", ")", "*", ",", "-", ".", "/", ":",
";", "<", ">", "@", "[", "]", "^", "_", "`", "{", "|", "}", "~", "=", "+", "!", "?"])
stops.extend(["rt", "#semst", "...", "thats", "im", "'s", "via"])
elif filter == "most":
stops = []
stops.extend(["\"", "#", "$", "%", "&", "\\", "'", "(", ")", "*", ",", "-", ".", "/", ":",
";", "<", ">", "@", "[", "]", "^", "_", "`", "{", "|", "}", "~", "=", "+", "!", "?"])
stops.extend(["rt", "#semst", "...", "thats", "im", "'s", "via"])
elif filter == "punctonly":
stops = []
# extended with string.punctuation and rt and #semst, removing links further down
stops.extend(["\"", "#", "$", "%", "&", "\\", "'", "(", ")", "*", ",", "-", ".", "/", ":",
";", "<", ">", "@", "[", "]", "^", "_", "`", "{", "|", "}", "~"]) # "=", "+", "!", "?"
stops.extend(["rt", "#semst", "..."]) # "thats", "im", "'s", "via"])
else:
stops = ["rt", "#semst", "..."]
stops = set(stops)
return [w for w in tokenised_tweet if (not w in stops and not w.startswith("http"))]
def build_dataset(words, vocabulary_size=5000000, min_count=5):
"""
Build vocabulary, code based on tensorflow/examples/tutorials/word2vec/word2vec_basic.py
:param words: list of words in corpus
:param vocabulary_size: max vocabulary size
:param min_count: min count for words to be considered
:return: counts, dictionary mapping words to indeces, reverse dictionary
"""
count = [['UNK', -1]]
count.extend(collections.Counter(words).most_common(vocabulary_size - 1))
dictionary = dict()
for word, _ in count:
if _ >= min_count: # or _ == -1: # that's UNK only
dictionary[word] = len(dictionary)
reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))
print("Final vocab size:", len(dictionary))
return count, dictionary, reverse_dictionary
def transform_tweet_nopadding(dictionary, words):
data = list()
unk_count = 0
for word in words:
if word in dictionary:
index = dictionary[word]
else:
index = 0 # dictionary['UNK']
unk_count += 1
data.append(index)
return data
def transform_tweet(w2vmodel, words, maxlen=20):
"""
Transform list of tokens with word2vec model, add padding to maxlen
:param w2vmodel: word2vec model
:param words: list of tokens
:param maxlen: maximum length
:return: transformed tweet, as numpy array
"""
data = list()
for i in range(0, maxlen - 1): # range(0, len(words)-1):
if i < len(words):
word = words[i]
if word in w2vmodel.vocab:
index = w2vmodel.vocab[word].index
else:
index = w2vmodel.vocab["unk"].index
else:
index = w2vmodel.vocab["unk"].index
data.append(index)
return np.asarray(data)
def transform_tweet_dict(dictionary, words, maxlen=20):
"""
Transform list of tokens, add padding to maxlen
:param dictionary: dict which maps tokens to integer indices
:param words: list of tokens
:param maxlen: maximum length
:return: transformed tweet, as numpy array
"""
data = list()
for i in range(0, maxlen - 1): # range(0, len(words)-1):
if i < len(words):
word = words[i]
if word in dictionary:
index = dictionary[word]
else:
index = dictionary['unk']
else:
index = 0
data.append(index)
return np.asarray(data)
def tokenise_tweets(tweets, stopwords="all"):
return [filterStopwords(tokenize(tweet.lower()), stopwords) for tweet in tweets]
def transform_targets(targets):
ret = []
for target in targets:
if target == "Atheism":
ret.append("#atheism")
elif target == "Climate Change is a Real Concern":
ret.append("#climatechange")
elif target == "Feminist Movement":
ret.append("#feminism")
elif target == "Hillary Clinton":
ret.append("#hillaryclinton")
elif target == "Legalization of Abortion":
ret.append("#prochoice")
elif target == "Donald Trump":
ret.append("#donaldtrump")
return ret
def transform_labels(labels, dim=3):
labels_t = []
for lab in labels:
v = np.zeros(dim)
if dim == 3:
if lab == 'NONE':
ix = 0
elif lab == 'AGAINST':
ix = 1
elif lab == 'FAVOR':
ix = 2
else:
if lab == 'AGAINST':
ix = 0
elif lab == 'FAVOR':
ix = 1
v[ix] = 1
labels_t.append(v)
return labels_t
def transform_labels_stage(labels, stage):
labels_t = []
if stage == 1:
for lab in labels:
if lab == 'NONE':
labels_t.append(np.array([1., 0.]))
elif lab == 'AGAINST':
labels_t.append(np.array([0., 1.]))
elif lab == 'FAVOR':
labels_t.append(np.array([0., 1.]))
elif stage == 2:
for lab in labels:
if lab == 'AGAINST':
labels_t.append(np.array([1., 0.]))
elif lab == 'FAVOR':
labels_t.append(np.array([0., 1.]))
return labels_t
if __name__ == '__main__':
tweets, targets, labels, ids = readTweetsOfficial("trump_autolabelled.txt",
encoding='utf-8')
tweet_tokens = tokenise_tweets(tweets)
target_tokens = tokenise_tweets(targets)
w2vmodel = word2vec.Word2Vec.load("skip_nostop_single_100features_5minwords_5context_big")
# count, dictionary, reverse_dictionary = build_dataset([token for senttoks in tweet_tokens+target_tokens for token in senttoks]) #flatten tweets for vocab construction
transformed_tweets = [transform_tweet(w2vmodel, senttoks) for senttoks in tweet_tokens]
transformed_targets = [transform_tweet(w2vmodel, senttoks) for senttoks in target_tokens]
transformed_labels = transform_labels(labels)
print('Longest tweet', len(max(transformed_tweets, key=len)))
print('Longest target', len(max(transformed_targets, key=len)))
# print('Most common words (+UNK)', count[:5])
# print('Sample data', data[:10])