-
Notifications
You must be signed in to change notification settings - Fork 1
/
initial.py
433 lines (355 loc) · 11.9 KB
/
initial.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
import numpy as np
import os
import codecs
from base.helper.args import get_args_parser
# embedding the position
def pos_embed(x):
if x < -60:
return 0
if -60 <= x <= 60:
return x + 61
if x > 60:
return 122
# find the index of x in y, if x not in y, return -1
def find_index(x, y):
flag = -1
for i in range(len(y)):
if x != y[i]:
continue
else:
return i
return flag
def delete_repeat(filename, filetempname):
if os.path.exists(filetempname):
os.remove(filetempname)
fin = open(filename, 'r', encoding='utf-8')
fout = codecs.open(filetempname, 'w', 'utf-8')
entity_pair = {}
while True:
content = fin.readline()
is_write = True
if content == '':
break
content = content.strip().split()
en1 = content[0]
en2 = content[1]
sentence = content[3]
sentence = sentence.strip()
tup = (en1, en2)
if tup not in entity_pair:
entity_pair[tup] = []
entity_pair[tup].append(sentence)
else:
for temp_sen in entity_pair[tup]:
temp_sen = temp_sen.strip()
if temp_sen == sentence:
is_write = False
if is_write == True:
record = str(en1) + " " + str(en2) + " " + str(content[2]) + " " + str(sentence)
fout.write(record)
fout.write('\n')
fin.close()
fout.close()
os.remove(filename)
os.rename(filetempname,filename)
# reading data
def init():
delete_repeat('./origin_data/test.txt', './origin_data/test_temp.txt')
delete_repeat('./origin_data/train.txt', './origin_data/train_temp.txt')
args = get_args_parser()
print('reading word embedding data...')
vec = []
word2id = {}
f = open('./origin_data/vec.txt', encoding='utf-8')
content = f.readline()
content = content.strip().split()
dim = int(content[1])
while True:
content = f.readline()
if content == '':
break
content = content.strip().split()
word2id[content[0]] = len(word2id)
content = content[1:]
content = [(float)(i) for i in content]
vec.append(content)
f.close()
word2id['UNK'] = len(word2id)
word2id['BLANK'] = len(word2id)
#添加UNK,BLANK对应的vector
vec.append(np.random.normal(size=dim, loc=0, scale=0.05))
vec.append(np.random.normal(size=dim, loc=0, scale=0.05))
vec = np.array(vec, dtype=np.float32)
print('reading relation to id')
relation2id = {}
f = open('./origin_data/relation2id.txt', 'r', encoding='utf-8')
while True:
content = f.readline()
if content == '':
break
content = content.strip().split()
relation2id[content[0]] = int(content[1])
f.close()
fixlen = args.max_sentence_len
# max length of position embedding is 60 (-60~+60)
maxlen = 60
train_sen = {} # {entity pair:[[[label1-sentence 1],[label1-sentence 2]...],[[label2-sentence 1],[label2-sentence 2]...]}
train_ans = {} # {entity pair:[label1,label2,...]} the label is one-hot vector
print('reading train data...')
f = open('./origin_data/train.txt', 'r', encoding='utf-8')
while True:
content = f.readline()
if content == '':
break
content = content.strip().split()
# get entity name
en1 = content[0]
en2 = content[1]
relation = 0
if content[2] not in relation2id:
relation = relation2id['NA']
else:
relation = relation2id[content[2]]
# put the same entity pair sentences into a dict
tup = (en1, en2)
label_tag = 0
if tup not in train_sen:
train_sen[tup] = []
train_sen[tup].append([])
y_id = relation
label_tag = 0
label = [0 for i in range(len(relation2id))]
label[y_id] = 1
train_ans[tup] = []
train_ans[tup].append(label)
else:
y_id = relation
label = [0 for i in range(len(relation2id))]
label[y_id] = 1
temp = find_index(label, train_ans[tup])
if temp == -1:
train_ans[tup].append(label)
label_tag = len(train_ans[tup]) - 1
train_sen[tup].append([])
else:
label_tag = temp
sentence = content[3]
# print("sentence:" + str(sentence))
en1pos = 0
en2pos = 0
#For Chinese
en1pos = sentence.find(en1)
if en1pos == -1:
en1pos = 0
en2pos = sentence.find(en2)
if en2pos == -1:
en2post = 0
entity_vec = get_entity_vec(en1, en2, args.max_entities_len, word2id)
output = []
#Embeding the position
for i in range(fixlen):
word = word2id['BLANK']
rel_e1 = pos_embed(i - en1pos)
rel_e2 = pos_embed(i - en2pos)
temp = []
temp.append(word)
temp.append(rel_e1)
temp.append(rel_e2)
temp.append(entity_vec)
output.append(temp)
for i in range(min(fixlen, len(sentence))):
word = 0
if sentence[i] not in word2id:
word = word2id['UNK']
else:
word = word2id[sentence[i]]
output[i][0] = word
train_sen[tup][label_tag].append(output)
print('reading test data ...')
test_sen = {} # {entity pair:[[sentence 1],[sentence 2]...]}
test_ans = {} # {entity pair:[labels,...]} the labels is N-hot vector (N is the number of multi-label)
f = open('./origin_data/test.txt', 'r', encoding='utf-8')
while True:
content = f.readline()
if content == '':
break
content = content.strip().split()
en1 = content[0]
en2 = content[1]
relation = 0
if content[2] not in relation2id:
relation = relation2id['NA']
else:
relation = relation2id[content[2]]
tup = (en1, en2)
if tup not in test_sen:
test_sen[tup] = []
y_id = relation
label_tag = 0
label = [0 for i in range(len(relation2id))]
label[y_id] = 1
test_ans[tup] = label
else:
y_id = relation
test_ans[tup][y_id] = 1
sentence = content[3]
en1pos = 0
en2pos = 0
#For Chinese
en1pos = sentence.find(en1)
if en1pos == -1:
en1pos = 0
en2pos = sentence.find(en2)
if en2pos == -1:
en2post = 0
entity_vec = get_entity_vec(en1, en2, args.max_entities_len, word2id)
output = []
for i in range(fixlen):
word = word2id['BLANK']
rel_e1 = pos_embed(i - en1pos)
rel_e2 = pos_embed(i - en2pos)
temp = []
temp.append(word)
temp.append(rel_e1)
temp.append(rel_e2)
temp.append(entity_vec)
output.append(temp)
for i in range(min(fixlen, len(sentence))):
word = 0
if sentence[i] not in word2id:
word = word2id['UNK']
else:
word = word2id[sentence[i]]
output[i][0] = word
test_sen[tup].append(output)
train_x = []
train_y = []
test_x = []
test_y = []
print('organizing train data')
f = open('./data/train_q&a.txt', 'w', encoding='utf-8')
temp = 0
for i in train_sen:
if len(train_ans[i]) != len(train_sen[i]):
print('ERROR')
lenth = len(train_ans[i])
for j in range(lenth):
train_x.append(train_sen[i][j])
train_y.append(train_ans[i][j])
# print("train_y:" + str(train_y))
f.write(str(temp) + '\t' + i[0] + '\t' + i[1] + '\t' + str(np.argmax(train_ans[i][j])) + '\n')
temp += 1
f.close()
# print("train_x:" + str(train_x))
print('organizing test data')
f = open('./data/test_q&a.txt', 'w', encoding='utf-8')
temp = 0
for i in test_sen:
test_x.append(test_sen[i])
test_y.append(test_ans[i])
tempstr = ''
for j in range(len(test_ans[i])):
if test_ans[i][j] != 0:
tempstr = tempstr + str(j) + '\t'
f.write(str(temp) + '\t' + i[0] + '\t' + i[1] + '\t' + tempstr + '\n')
temp += 1
f.close()
train_x = np.array(train_x)
train_y = np.array(train_y)
test_x = np.array(test_x)
test_y = np.array(test_y)
np.save('./data/vec.npy', vec)
np.save('./data/train_x.npy', train_x)
np.save('./data/train_y.npy', train_y)
np.save('./data/testall_x.npy', test_x)
np.save('./data/testall_y.npy', test_y)
def seperate():
print('reading training data')
print('seperating train all data')
train_entities, train_pos1, train_pos2, train_word = get_seperate_info('./data/train_x.npy')
np.save('./data/train_word.npy', train_word)
np.save('./data/train_pos1.npy', train_pos1)
np.save('./data/train_pos2.npy', train_pos2)
np.save('./data/train_entities.npy', train_entities)
print('seperating test all data')
test_entities, test_pos1, test_pos2, test_word = get_seperate_info('./data/testall_x.npy')
np.save('./data/testall_word.npy', test_word)
np.save('./data/testall_pos1.npy', test_pos1)
np.save('./data/testall_pos2.npy', test_pos2)
np.save('./data/test_entities.npy', test_entities)
def get_seperate_info(file):
x_train = np.load(file, allow_pickle=True)
seperate_word = []
seperate_pos1 = []
seperate_pos2 = []
seperate_entities = []
for i in range(len(x_train)):
word = []
pos1 = []
pos2 = []
entities = []
for j in x_train[i]:
temp_word = []
temp_pos1 = []
temp_pos2 = []
temp_entities = []
for k in j:
temp_word.append(k[0])
temp_pos1.append(k[1])
temp_pos2.append(k[2])
temp_entities = k[3]
word.append(temp_word)
pos1.append(temp_pos1)
pos2.append(temp_pos2)
entities.append(temp_entities)
seperate_word.append(word)
seperate_pos1.append(pos1)
seperate_pos2.append(pos2)
seperate_entities.append(entities)
seperate_word = np.array(seperate_word)
seperate_pos1 = np.array(seperate_pos1)
seperate_pos2 = np.array(seperate_pos2)
seperate_entities = np.array(seperate_entities)
return seperate_entities, seperate_pos1, seperate_pos2, seperate_word
# get answer metric for PR curve evaluation
def getans():
test_y = np.load('./data/testall_y.npy',allow_pickle=True)
# print("test_y:" + str(test_y))
eval_y = []
for i in test_y:
# print("i[1:]:" + str(i[1:]))
eval_y.append(i[1:])
allans = np.reshape(eval_y, (-1))
# print("allans:" + str(allans))
np.save('./data/allans.npy', allans)
def get_metadata():
fwrite = open('./data/metadata.tsv', 'w', encoding='utf-8')
f = open('./origin_data/vec.txt', encoding='utf-8')
f.readline()
while True:
content = f.readline().strip()
if content == '':
break
name = content.split()[0]
fwrite.write(name + '\n')
f.close()
fwrite.close()
def get_entity_vec(entity_h, entity_t, length, word2id):
entitis = str(entity_h) + " " + str(entity_t)
standard_entitis = []
for i in range(length):
word = word2id['BLANK']
standard_entitis.append(word)
for i in range(min(length, len(entitis))):
word = 0
if entitis[i] not in word2id:
word = word2id['UNK']
else:
word = word2id[entitis[i]]
standard_entitis[i] = word
return standard_entitis
init()
seperate()
getans()
get_metadata()
print("Sucess!!!")