-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathPreprocess.py
More file actions
217 lines (180 loc) · 7.52 KB
/
Preprocess.py
File metadata and controls
217 lines (180 loc) · 7.52 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
##Performs preprocessing for twitter-training data
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from sklearn.preprocessing import LabelEncoder
import numpy as np
import gzip
from representation import parseJsonLine, Place, extractPreprocessUrl
from collections import Counter
import pickle
import gc
import string
import json
import os
#Load configuration from file
if os.path.isfile('config.json'):
print("Loading configutation from configuration file {config.json}")
with open('config.json') as json_file:
config = json.load(json_file)
trainingFile = config['trainingFile']
placesFile = config['placesFile']
binaryPath = config['binaryPath']
else:
print("Configuration file {config.json} not found")
trainingFile = "data/train/training.twitter.json.gz" # File with all ~9 Million training tweets
placesFile = 'data/train/training.json.gz' # Place annotation provided by task organisers
binaryPath = 'data/binaries/' # Place to store the results
#Parser Twitter-JSON; loads all tweets into RAM (not very memory efficient!)
tweetToTextMapping= {} # Map<Twitter-ID; tweet>
with gzip.open(trainingFile,'rb') as file:
for line in file:
instance = parseJsonLine(line.decode('utf-8'))
tweetToTextMapping[instance.id] = instance
#Parse and add gold-label for tweets
with gzip.open(placesFile,'rb') as file:
for line in file:
parsed_json = json.loads(line.decode('utf-8'))
tweetId=int(parsed_json["tweet_id"])
if(tweetId in tweetToTextMapping):
place = Place(name=parsed_json["tweet_city"], lat=parsed_json["tweet_latitude"], lon=parsed_json["tweet_longitude"])
tweetToTextMapping[tweetId].place = place
print(str(len(tweetToTextMapping.keys())) + " tweets for training are found")
###########Find the mean location for each of the ~3000 classes
placeSummary = {}
for place in list(map(lambda x : x.place, tweetToTextMapping.values())):
if place._name not in placeSummary:
placeSummary[place._name] = []
placeSummary[place._name].append(place)
#Calculate the mean lon/lat location for each city as city center
placeMedian = {}
for key in placeSummary.keys():
lat = np.mean(list(map(lambda x: float(x._lat), placeSummary[key])))
lon = np.mean(list(map(lambda x: float(x._lon), placeSummary[key])))
placeMedian[key] = (lat,lon)
del(placeSummary)
###Extract relevant parts and store in list...
trainLabels = [] # list of label ids
trainDescription=[]
trainLinks=[]
trainLocation=[]
trainSource=[]
trainTexts = []
trainUserName=[]
trainTZ=[]
trainUtc=[]
trainUserLang =[]
trainSinTime = []
trainCosTime = []
for key in tweetToTextMapping:
trainLabels.append(tweetToTextMapping[key].place._name)
trainDescription.append(str(tweetToTextMapping[key].description))
trainLinks.append(extractPreprocessUrl(tweetToTextMapping[key].urls))
trainLocation.append(str(tweetToTextMapping[key].location))
trainSource.append(str(tweetToTextMapping[key].source))
trainTexts.append(tweetToTextMapping[key].text)
trainUserName.append(str(tweetToTextMapping[key].name))
trainTZ.append(str(tweetToTextMapping[key].timezone))
trainUtc.append(str(tweetToTextMapping[key].utcOffset))
trainUserLang.append(str(tweetToTextMapping[key].userLanguage))
t = tweetToTextMapping[key].createdAt.hour * 60 * 60 + tweetToTextMapping[key].createdAt.minute * 60 + tweetToTextMapping[key].createdAt.second
t = 2*np.pi*t/(24*60*60)
trainSinTime.append(np.sin(t))
trainCosTime.append(np.cos(t))
trainCreatedAt = np.column_stack((trainSinTime, trainCosTime))
del(trainSinTime)
del(trainCosTime)
#Delete tweets and run gc
del(tweetToTextMapping)
gc.collect()
#########Preprocessing of data
#1.) Binarize > 3000 target classes into one hot encoding
print(str(len(set(trainLabels))) +" different places known") #Number of different classes
classEncoder = LabelEncoder()
classEncoder.fit(trainLabels)
classes = classEncoder.transform(trainLabels)
#Map class int representation to
colnames = [None]*len(set(classes))
for i in range(len(classes)):
colnames[classes[i]] = trainLabels[i]
#2.) Tokenize texts
def my_filter():
f = string.punctuation
f += '\t\n\r…”'
return f
#User-Description
print("User Description")
descriptionTokenizer = Tokenizer(num_words=100000, filters=my_filter()) #Keep only top-N words
descriptionTokenizer.fit_on_texts(trainDescription)
trainDescription = descriptionTokenizer.texts_to_sequences(trainDescription)
trainDescription = np.asarray(trainDescription) #Convert to ndArraytop
trainDescription = pad_sequences(trainDescription)
#Link-Mentions
print("Links")
trainDomain = list(map(lambda x : x[0], trainLinks)) #URL-Domain
count = Counter(trainDomain)
for i in range(len(trainDomain)):
if count[trainDomain[i]] < 50:
trainDomain[i] = ''
domainEncoder = LabelEncoder()
domainEncoder.fit(trainDomain)
trainDomain = domainEncoder.transform(trainDomain)
trainTld = list(map(lambda x : x[1], trainLinks)) #Url suffix; top level domain
count = Counter(trainTld)
for i in range(len(trainTld)):
if count[trainTld[i]] < 50:
trainTld[i] = ''
tldEncoder = LabelEncoder()
tldEncoder.fit(trainTld)
trainTld = tldEncoder.transform(trainTld)
#Location
print("User Location")
locationTokenizer = Tokenizer(num_words=80000, filters=my_filter()) #Keep only top-N words
locationTokenizer.fit_on_texts(trainLocation)
trainLocation = locationTokenizer.texts_to_sequences(trainLocation)
trainLocation = np.asarray(trainLocation) #Convert to ndArraytop
trainLocation = pad_sequences(trainLocation)
#Source
print("Device source")
sourceEncoder = LabelEncoder()
sourceEncoder.fit(trainSource)
trainSource = sourceEncoder.transform(trainSource)
#Text
print("Tweet Text")
textTokenizer = Tokenizer(num_words=100000, filters=my_filter()) #Keep only top-N words
textTokenizer.fit_on_texts(trainTexts)
trainTexts = textTokenizer.texts_to_sequences(trainTexts)
trainTexts = np.asarray(trainTexts) #Convert to ndArraytop
trainTexts = pad_sequences(trainTexts)
#Username
print("Username")
nameTokenizer = Tokenizer(num_words=20000, filters=my_filter()) #Keep only top-N words
nameTokenizer.fit_on_texts(trainUserName)
trainUserName = nameTokenizer.texts_to_sequences(trainUserName)
trainUserName = np.asarray(trainUserName) #Convert to ndArraytop
trainUserName = pad_sequences(trainUserName)
#TimeZone
print("TimeZone")
timeZoneTokenizer = Tokenizer(num_words=300) #Keep only top-N words
timeZoneTokenizer.fit_on_texts(trainTZ)
trainTZ = timeZoneTokenizer.texts_to_sequences(trainTZ)
trainTZ = np.asarray(trainTZ) #Convert to ndArraytop
trainTZ = pad_sequences(trainTZ)
#UTC
print("UTC")
utcEncoder = LabelEncoder()
utcEncoder.fit(trainUtc)
trainUtc = utcEncoder.transform(trainUtc)
#User-Language (63 languages)
print("User Language")
langEncoder = LabelEncoder()
langEncoder.fit(trainUserLang)
trainUserLang = langEncoder.transform(trainUserLang)
#####Save result of preprocessing
#1.) Save relevant processing data
filehandler = open(binaryPath + "processors.obj", "wb")
pickle.dump((descriptionTokenizer, domainEncoder, tldEncoder, locationTokenizer, sourceEncoder, textTokenizer, nameTokenizer, timeZoneTokenizer, utcEncoder, langEncoder, placeMedian, colnames, classEncoder ), filehandler)
filehandler.close()
#2.) Save converted training data
filehandler = open(binaryPath + "data.obj", "wb")
pickle.dump((trainDescription, trainLocation, trainDomain, trainTld, trainSource, trainTexts, trainUserName, trainTZ, trainUtc, trainUserLang, trainCreatedAt, classes), filehandler, protocol=4)
filehandler.close()