-
Notifications
You must be signed in to change notification settings - Fork 12
/
create_embeddings.py
347 lines (265 loc) · 9.32 KB
/
create_embeddings.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
import gensim
import sys
import os
import codecs
import json
from preprocess import preprocess
import nltk.data
import multiprocessing
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
file_path = sys.argv[1]+"/all-parsed-papers-category.txt"
itr_no = 0
class LabeledLineSentence(object):
def __init__(self, filename):
self.filename = filename
def __iter__(self):
global itr_no
train = codecs.open(self.filename,'r','utf-8')
papers=[]
paper_no = 0
itr_no += 1
for line in train:
line = line.replace("###FORMULA###","||FORMULA||")
line = line.replace("###TABLE###","||TABLE||")
line = line.replace("###FIGURE###","||FIGURE||")
map=line.split('\t')
paper=dict()
paper['id']=map[0]
paper['name']=map[1]
try:
paper['info']=json.loads(map[2])
except:
continue
paper['sum']=map[3]
if (len(paper['sum'])>=10):
papers.append(paper)
print("Paper ", len(papers))
for paper in papers:
paper_no += 1
print(itr_no,"art",paper_no,paper['id'])
paper['sum']=paper['sum'].encode('utf-8')
paper_data=""
for key in paper['info']:
for item in paper['info'][key]:
if isinstance(item,str):
paper_data+=item+" "
elif isinstance(item,bytes):
paper_data+=item+" "
elif isinstance(item,dict):
for innerKey in item:
for innerItem in item[innerKey]:
if (isinstance(innerItem,str)):
paper_data+=innerItem+" "
elif (isinstance(innerItem,bytes)):
paper_data+=innerItem+" "
elif isinstance(innerItem,dict):
for in_innerKey in innerItem:
for in_innerItem in innerItem[in_innerKey]:
if (isinstance(in_innerItem,str)):
paper_data+=in_innerItem+" "
elif (isinstance(in_innerItem,bytes)):
paper_data+=in_innerItem+" "
lines = tokenizer.tokenize(paper_data)
for uid, line_1 in enumerate(lines):
yield gensim.models.doc2vec.LabeledSentence(words=preprocess(line_1), tags=[str(paper['id']) + '_' + str(uid)])
train = codecs.open(self.filename,'r','utf-8')
papers=[]
abs_no = 0
for line in train:
line = line.replace("###FORMULA###","||FORMULA||")
line = line.replace("###TABLE###","||TABLE||")
line = line.replace("###FIGURE###","||FIGURE||")
abs_no += 1
print(itr_no,"abs",abs_no,paper['id'])
map=line.split('\t')
paper_id = map[0]
summary=map[3]
print(paper_id)
lines = tokenizer.tokenize(summary)
for uid, line_1 in enumerate(lines):
yield gensim.models.doc2vec.LabeledSentence(words=preprocess(line_1), tags=['ABS_'+str(paper_id)+'_'+str(uid)])
class LabeledParagraph(object):
def __init__(self, filename):
self.filename = filename
def __iter__(self):
global itr_no
train = codecs.open(self.filename,'r','utf-8')
papers=[]
itr_no += 1
for line in train:
line = line.replace("###FORMULA###","||FORMULA||")
line = line.replace("###TABLE###","||TABLE||")
line = line.replace("###FIGURE###","||FIGURE||")
map=line.split('\t')
paper=dict()
paper['id']=map[0]
paper['name']=map[1]
try:
paper['info']=json.loads(map[2])
except:
continue
paper['sum']=map[3]
if (len(paper['sum'])>=10):
papers.append(paper)
paper_no =0
for paper in papers:
paper_no += 1
print(itr_no,"art",paper_no,paper['id'])
paper['sum']=paper['sum'].encode('utf-8')
for key in paper['info']:
paper_data=""
for item in paper['info'][key]:
if isinstance(item,str):
paper_data+=item+" "
elif isinstance(item,bytes):
paper_data+=item+" "
elif isinstance(item,dict):
for innerKey in item:
for innerItem in item[innerKey]:
if (isinstance(innerItem,str)):
paper_data+=innerItem+" "
elif (isinstance(innerItem,bytes)):
paper_data+=innerItem+" "
elif isinstance(innerItem,dict):
for in_innerKey in innerItem:
for in_innerItem in innerItem[in_innerKey]:
if (isinstance(in_innerItem,str)):
paper_data+=in_innerItem+" "
elif (isinstance(in_innerItem,bytes)):
paper_data+=in_innerItem+" "
yield gensim.models.doc2vec.LabeledSentence(words=preprocess(paper_data), tags=[str(paper['id']) + '_' + str(key)])
train = codecs.open(self.filename,'r','utf-8')
abs_no = 0
for line in train:
line = line.replace("###FORMULA###","||FORMULA||")
line = line.replace("###TABLE###","||TABLE||")
line = line.replace("###FIGURE###","||FIGURE||")
abs_no += 1
map=line.split('\t')
paper_id = map[0]
print(itr_no,"abs",abs_no,paper['id'])
summary=map[3]
yield gensim.models.doc2vec.LabeledSentence(words=preprocess(summary), tags=['ABS_'+str(paper_id)])
class LabeledAbstractSentence(object):
def __init__(self, filename):
self.filename = filename
def __iter__(self):
train = codecs.open(self.filename,'r','utf-8')
papers=[]
for line in train:
line = line.replace("###FORMULA###","||FORMULA||")
line = line.replace("###TABLE###","||TABLE||")
line = line.replace("###FIGURE###","||FIGURE||")
map=line.split('\t')
paper_id = map[0]
summary=map[3]
print(paper_id)
lines = tokenizer.tokenize(summary)
for uid, line in enumerate(lines):
yield gensim.models.doc2vec.LabeledSentence(words=preprocess(summary), tags=['ABS_'+str(paper_id)+'_'+str(uid)])
class LabeledAbstractParagraph(object):
def __init__(self, filename):
self.filename = filename
def __iter__(self):
train = codecs.open(self.filename,'r','utf-8')
for line in train:
line = line.replace("###FORMULA###","||FORMULA||")
line = line.replace("###TABLE###","||TABLE||")
line = line.replace("###FIGURE###","||FIGURE||")
map=line.split('\t')
paper_id = map[0]
print(paper_id)
summary=map[3]
yield gensim.models.doc2vec.LabeledSentence(words=preprocess(summary), tags=['ABS_'+str(paper_id)])
def train_sentences(algo = "DM"):
sentences = LabeledLineSentence(file_path)
if algo == "DM":
model_DM = gensim.models.doc2vec.Doc2Vec(sentences, size = 300, window = 8, min_count=1, workers=multiprocessing.cpu_count(), iter = 10, dm = 1, negative=10)
print("Model sentences_DM Trained")
model_DM.save("Para2Vec_Models/sentences_DM.doc2vec")
print("Model sentences_DM saved")
elif algo == "DBOW":
model_DBOW = gensim.models.doc2vec.Doc2Vec(sentences, size = 300, window = 8, min_count=1, workers=multiprocessing.cpu_count(), iter = 10, dm = 0, negative=10)
print("Model sentences_DBOW Trained")
model_DBOW.save("Para2Vec_Models/sentences_DBOW.doc2vec")
print("Model sentences_DBOW saved")
def train_paragraph(algo = "DM"):
paragraphs = LabeledParagraph(file_path)
if algo == "DM":
model_DM = gensim.models.doc2vec.Doc2Vec(paragraphs, size = 400, window = 10, min_count=1, workers=multiprocessing.cpu_count(), iter = 10, dm = 1, negative=10)
print("Model paragraphs_DM Trained")
model_DM.save("Para2Vec_Models/paragraph_DM.doc2vec")
print("Model paragraphs_DM saved")
elif algo == "DBOW":
model_DBOW = gensim.models.doc2vec.Doc2Vec(paragraphs, size = 400, window = 10, min_count=1, workers=multiprocessing.cpu_count(), iter = 10, dm = 0, negative=10)
print("Model paragraph_DBOW Trained")
model_DBOW.save("Para2Vec_Models/paragraph_DBOW.doc2vec")
print("Model paragraphs_DBOW saved")
def train_abstract(para = False, algo = "DM"):
if para == True:
abs_paras = LabeledAbstractParagraph(file_path)
if algo == "DM":
fname = "Para2Vec_Models/paragraph_"+algo+".doc2vec"
model_DM = gensim.models.doc2vec.Doc2Vec.load(fname)
print("abs para DM loaded")
model_DM.train(abs_paras)
print("abs para DM trained")
model_DM.save(fname)
print("abs para DM saved")
elif algo == "DBOW":
fname = "Para2Vec_Models/paragraph_"+algo+".doc2vec"
model_DBOW = gensim.models.doc2vec.Doc2Vec.load(fname)
print("abs para DBOW loaded")
model_DBOW.train(abs_paras)
print("abs para DBOW trained")
model_DBOW.save(fname)
print("abs para DBOW saved")
elif para == False:
abs_sentences = LabeledAbstractSentence(file_path)
if algo == "DM":
fname = "Para2Vec_Models/sentences_"+algo+".doc2vec"
model_DM = gensim.models.doc2vec.Doc2Vec.load(fname)
print("abs sentences DM loaded")
model_DM.train(abs_sentences)
print("abs sentences DM trained")
model_DM.save(fname)
print("abs sentences DM saved")
elif algo == "DBOW":
fname = "Para2Vec_Models/sentences_"+algo+".doc2vec"
model_DBOW = gensim.models.doc2vec.Doc2Vec.load(fname)
print("abs sentences DBOW saved")
model_DBOW.train(abs_sentences)
print("abs sentences DBOW saved")
model_DBOW.save(fname)
print("abs sentences DBOW saved")
def main():
abs_or_article = sys.argv[2]
s_or_p = "p"
DM_or_DBOW = sys.argv[2]
if abs_or_article == "abs":
if s_or_p == "s":
if DM_or_DBOW == "DM":
train_abstract(False,"DM")
elif DM_or_DBOW == "DBOW":
train_abstract(False,"DBOW")
elif s_or_p == "p":
if DM_or_DBOW == "DM":
train_abstract(True,"DM")
elif DM_or_DBOW == "DBOW":
train_abstract(True,"DBOW")
else:
print("Invalid Option")
elif abs_or_article == "art":
if s_or_p == "s":
if DM_or_DBOW == "DM":
train_sentences("DM")
elif DM_or_DBOW == "DBOW":
train_sentences("DBOW")
elif s_or_p == "p":
if DM_or_DBOW == "DM":
train_paragraph("DM")
elif DM_or_DBOW == "DBOW":
train_paragraph("DBOW")
else:
print("Invalid Option")
if __name__ == "__main__":main()