-
Notifications
You must be signed in to change notification settings - Fork 7
/
glove_loader.py
446 lines (334 loc) · 14.1 KB
/
glove_loader.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
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
__author__ = "Andrea Galassi"
__copyright__ = "Copyright 2018-2020 Andrea Galassi"
__license__ = "BSD 3-clause"
__version__ = "0.2.0"
__email__ = "[email protected]"
import pandas
import os
import numpy as np
import re
import argparse
DIM = 300
SEPARATORS = ['(', ')', '[', ']', '{', '}', '...', '_', '--', '|',
';', ':',
"±", "·", "≥", "≤", "≈", '=', "<", ">", "£", "$", "€",
'!!!', '???', '?!?', '!?!', '?!', '!?', '??', '!!',
'!', '?',
'/', '"', '%', '$', '*', '#', '+',
',', '.',
"'s", "'ve", "'ll", "'re", "'d",
'-', "'",
"∂", "∆", "∇"]
REPLACINGS = {"’": "'",
"‘": "'",
"“": '"',
"”": '"',
"''": '"',
"—": '-',
"−": '-',
"–": '-',
"⁄": '/'}
STOPWORDS = ['.', ',', ':', ';']
def load_glove(vocabulary_source_path):
print("Loading Glove")
f = open(vocabulary_source_path, 'r', encoding="utf-8")
model = {}
for line in f:
splits = line.split(' ')
n_splits = len(splits)
word = ""
n = 0
while (n_splits - n) > DIM:
word += " " + splits[n]
n += 1
word = word[1:]
# embedding = np.array([float(val) for val in splitLine[1:]])
# model[word] = embedding
model[word] = line
print("Glove loaded")
return model
def vocabulary_creator(model, vocabulary_destination_path, dataframe_path):
df = pandas.read_pickle(dataframe_path)
propositions = df['source_proposition'].drop_duplicates()
print(len(propositions))
documents = []
# replace different versions of the same character
for proposition in propositions:
for old in REPLACINGS.keys():
proposition = proposition.replace(old, REPLACINGS[old])
documents.append(proposition)
if not os.path.exists(vocabulary_destination_path):
os.makedirs(vocabulary_destination_path)
orphans_path = os.path.join(vocabulary_destination_path, 'glove.orphans.txt')
embeddings_path = os.path.join(vocabulary_destination_path, 'glove.embeddings.txt')
npz_path = os.path.join(vocabulary_destination_path, 'glove.embeddings.npz')
vocabulary_path = os.path.join(vocabulary_destination_path, 'glove.vocabulary.txt')
logfile_path = os.path.join(vocabulary_destination_path, 'glove.log.txt')
logfile = open(logfile_path, 'w')
logfile.write('Sep\tVoc_size\tOrphans\n')
print("Splitting")
vocabulary, orphans = document_tokenizer_and_embedder(documents, model, logfile)
logfile.close()
if '' in orphans:
orphans.remove('')
# print vocabulary file
vocabulary_file = open(vocabulary_path, 'w')
for word in sorted(vocabulary.keys()):
vocabulary_file.write(word)
vocabulary_file.write('\n')
vocabulary_file.close()
# print orphans file
orphans_file = open(orphans_path, 'w')
for word in sorted(orphans):
orphans_file.write(word)
orphans_file.write("\n")
orphans_file.close()
print("handling orphans")
# create random embeddings for orphans
for word in sorted(orphans):
embedding = np.random.rand(DIM) - 0.5
line = word + " "
for value in embedding:
line += ("%.5g " % value) + " "
line += '\n'
vocabulary[word] = line
print("Saving")
# save embeddings
embeddings = []
vocabulary_list = []
embeddings_file = open(embeddings_path, 'w')
for word in sorted(vocabulary.keys()):
line = vocabulary[word]
embeddings_file.write(line)
splits = line.split()
embedding = splits[-DIM:]
embedding = np.array(embedding, dtype=np.float32)
embeddings.append(embedding)
vocabulary_list.append(word)
embeddings_file.close()
print(vocabulary_list[0])
np.savez(npz_path, vocab=vocabulary_list, embeds=embeddings)
print('Finished')
def print_vocabulary_and_orphans(vocabulary, vocabulary_path, orphans, orphans_path):
voc_file = open(vocabulary_path,'w')
for word in sorted(vocabulary.keys()):
voc_file.write(vocabulary[word])
voc_file.close()
orphans_file = open(orphans_path, 'w')
for word in sorted(orphans):
orphans_file.write(word)
orphans_file.write("\n")
orphans_file.close()
def document_tokenizer_and_embedder(documents, model,
logfile=None, vocabulary={}, separators=None, not_vocab_separators=None):
"""
Split the documents in tokens.
The splitting is progressive using a series of separators,
when a token match a key in model, it is inserted in the vocabulary.
At the end of the process, the token that still do not match the model are returned as "orphans".
Parameters
----------
documents : an iterable object composed by str
A list or a set of documents to be splitted.
model : dict
A dictionary with all the possible tokens as key
logfile : file, optional
File where to print the log of the tokenization process
vocabulary : dict, optional
The dictionary to be filled with the tokens found in the document splitting.
If it is not provided, a empty dictionary is initialized.
separators : list of str
String to be used as splitting tokens.
They will be inserted in the vocabulary if they are not in the next param
not_vocab_separators : list of str
Separators that will not be added to the vocabulary.
Returns
----------
orphans : list of str
Token that do not match the model
vocabulary : dict
The keys are the tokens found during the splitting, the values come from the model
"""
# punctuation and other special espressions
if separators == None:
separators = SEPARATORS
# tried but not present in glove: '\'t', 'e-'
orphans = set()
for composed_word in documents:
words = composed_word.split()
#words = filter(None, re.split("[" + separator + "]+", composed_word))
# remove stop symbols at the end of the tokens
for word in words:
if len(word) > 1 and word[-1] in STOPWORDS:
word2 = word[:-1]
if word2 in model.keys():
word = word2
if word in model.keys():
vocabulary[word] = model[word]
# print("Found word: " + word)
else:
orphans.add(word)
# print("Word not found: " + word)
if not logfile == None:
logfile.write("Tab, space, newline" + '\t' +
str(len(vocabulary.keys())) + '\t' +
str(len(orphans)) + '\n')
for separator in separators:
# print("Separator: " + separator)
orphans, vocabulary = regular_split(orphans, vocabulary, model, separator)
if separator not in model.keys():
orphans.add(separator)
else:
vocabulary[separator] = model[separator]
# print("Orphans: " + str(len(orphans)))
if not logfile == None:
logfile.write(separator + '\t' +
str(len(vocabulary.keys())) + '\t' +
str(len(orphans)) + '\n')
return vocabulary, orphans
def regular_split(old_orphans, vocabulary, model, separator):
orphans = set()
for composed_word in old_orphans:
words = composed_word.split(separator)
#words = filter(None, re.split("[" + separator + "]+", composed_word))
for word in words:
if word in model.keys():
vocabulary[word] = model[word]
# print("Found word: " + word)
else:
orphans.add(word)
# print("Word not found: " + word)
return orphans, vocabulary
def DrInventor_routine():
if size == 300:
vocabulary_source_path = os.path.join(os.getcwd(), "resources", 'glove.840B.300d.txt')
embed_name = "glove300"
elif size == 25:
vocabulary_source_path = os.path.join(os.getcwd(), "resources", 'glove.twitter.27B.25d.txt')
embed_name = "glove25"
else:
raise Exception("Wrong embedding size")
global DIM
DIM = size
dataset_name = 'DrInventor'
dataset_version = 'arg10'
dataset_path = os.path.join(os.getcwd(), 'Datasets', dataset_name)
pickles_path = os.path.join(os.path.join(dataset_path, 'pickles', dataset_version))
dataframe_path = os.path.join(pickles_path, 'total.pkl')
glove_path = os.path.join(dataset_path, "resources", embed_name)
model = load_glove(vocabulary_source_path)
m1 = model.copy()
vocabulary_creator(m1, glove_path, dataframe_path)
def ECHR_routine():
vocabulary_source_path = os.path.join(os.getcwd(), 'glove.840B.300d.txt')
dataset_name = 'ECHR2018'
dataset_version = 'arg0'
dataset_path = os.path.join(os.getcwd(), 'Datasets', dataset_name)
pickles_path = os.path.join(os.path.join(dataset_path, 'pickles', dataset_version))
dataframe_path = os.path.join(pickles_path, 'total.pkl')
glove_path = os.path.join(dataset_path, 'glove')
model = load_glove(vocabulary_source_path)
m1 = model.copy()
vocabulary_creator(m1, glove_path, dataframe_path)
def scidtb_routine(size):
if size == 300:
vocabulary_source_path = os.path.join(os.getcwd(), "resources", 'glove.840B.300d.txt')
embed_name = "glove300"
elif size == 25:
vocabulary_source_path = os.path.join(os.getcwd(), "resources", 'glove.twitter.27B.25d.txt')
embed_name = "glove25"
else:
raise Exception("Wrong embedding size")
global DIM
DIM = size
dataset_name = 'scidtb_argmin_annotations'
dataset_version = 'only_arg_v1'
dataset_path = os.path.join(os.getcwd(), 'Datasets', dataset_name)
pickles_path = os.path.join(os.path.join(dataset_path, 'pickles', dataset_version))
dataframe_path = os.path.join(pickles_path, 'total.pkl')
glove_path = os.path.join(dataset_path, "resources", embed_name)
model = load_glove(vocabulary_source_path)
m1 = model.copy()
vocabulary_creator(m1, glove_path, dataframe_path)
def RCT_routine(size):
if size == 300:
vocabulary_source_path = os.path.join(os.getcwd(), "resources", 'glove.840B.300d.txt')
embed_name = "glove300"
elif size == 25:
vocabulary_source_path = os.path.join(os.getcwd(), "resources", 'glove.twitter.27B.25d.txt')
embed_name = "glove25"
else:
raise Exception("Wrong embedding size")
global DIM
DIM = size
dataset_name = 'RCT'
dataset_path = os.path.join(os.getcwd(), 'Datasets', dataset_name)
pickles_path = os.path.join(os.path.join(dataset_path, 'pickles'))
dataframe_path = os.path.join(pickles_path, 'total.pkl')
glove_path = os.path.join(dataset_path, "resources", embed_name)
model = load_glove(vocabulary_source_path)
m1 = model.copy()
vocabulary_creator(m1, glove_path, dataframe_path)
def cdcp_routine():
if size == 300:
vocabulary_source_path = os.path.join(os.getcwd(), "resources", 'glove.840B.300d.txt')
embed_name = "glove300"
elif size == 25:
vocabulary_source_path = os.path.join(os.getcwd(), "resources", 'glove.twitter.27B.25d.txt')
embed_name = "glove25"
else:
raise Exception("Wrong embedding size")
global DIM
DIM = size
dataset_name = 'cdcp_ACL17'
dataset_version = 'new_3'
dataset_path = os.path.join(os.getcwd(), 'Datasets', dataset_name)
pickles_path = os.path.join(os.path.join(dataset_path, 'pickles', dataset_version))
dataframe_path = os.path.join(pickles_path, 'total.pkl')
glove_path = os.path.join(dataset_path, "resources", embed_name)
model = load_glove(vocabulary_source_path)
m1 = model.copy()
vocabulary_creator(m1, glove_path, dataframe_path)
def UKP_routine():
if size == 300:
vocabulary_source_path = os.path.join(os.getcwd(), "resources", 'glove.840B.300d.txt')
embed_name = "glove300"
elif size == 25:
vocabulary_source_path = os.path.join(os.getcwd(), "resources", 'glove.twitter.27B.25d.txt')
embed_name = "glove25"
else:
raise Exception("Wrong embedding size")
global DIM
DIM = size
dataset_name = 'AAEC_v2'
dataset_version = 'new_2R'
dataset_path = os.path.join(os.getcwd(), 'Datasets', dataset_name)
pickles_path = os.path.join(os.path.join(dataset_path, 'pickles', dataset_version))
dataframe_path = os.path.join(pickles_path, 'total.pkl')
glove_path = os.path.join(dataset_path, "resources", embed_name)
model = load_glove(vocabulary_source_path)
m1 = model.copy()
vocabulary_creator(m1, glove_path, dataframe_path)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Loads glove embeddings related to the dataset")
parser.add_argument('-c', '--corpus',
choices=["rct", "drinv", "cdcp", "echr", "ukp", "scidtb"],
help="Corpus", default="cdcp")
parser.add_argument('-s', '--size', help="embedding size",
choices=[25, 300],
type=int, default=300)
args = parser.parse_args()
corpus = args.corpus
size = args.size
if corpus.lower() == "rct":
RCT_routine(size)
elif corpus.lower() == "cdcp":
cdcp_routine(size)
elif corpus.lower() == "drinv":
DrInventor_routine(size)
elif corpus.lower() == "ukp":
UKP_routine(size)
elif corpus.lower() == "scidtb":
scidtb_routine(size)
else:
print("Datset not yet supported")