KGraph commited on
Commit
688f764
·
1 Parent(s): dbfc522

Update FB15k-237.py

Browse files
Files changed (1) hide show
  1. FB15k-237.py +54 -118
FB15k-237.py CHANGED
@@ -56,11 +56,6 @@ _URLS = {
56
  "long": "https://raw.githubusercontent.com/pp413/Knowledge_embedding_benchmark_datasets/main/LongText.zip",
57
  }
58
 
59
- def write_str2id(data, save_path, sep='\t'):
60
- with open(save_path, 'w') as f:
61
- f.write("%d\n" % len(data))
62
- for i in data:
63
- f.write("%s%s%d\n" % (i, sep, data[i]))
64
 
65
  def load_triple_original_file(path_file, sep='\t'):
66
  data = []
@@ -70,101 +65,41 @@ def load_triple_original_file(path_file, sep='\t'):
70
  data.append(line[:3])
71
  return data
72
 
73
- def write_triple_from_original_data(original_data, path_file, str2id, sep='\t'):
74
 
75
- with open(path_file, 'w') as f:
76
- num = len(original_data)
77
- f.write("%d\n" %num)
78
- for l in original_data:
79
- f.write("%d%s%d%s%d\n"%(
80
- str2id[0][l[0]],
81
- sep,
82
- str2id[1][l[1]],
83
- sep,
84
- str2id[0][l[2]]))
85
 
86
- def get_str2id(path_data, sep="\t", no_sort=True):
87
- relation2id = dict()
88
- id2relation = dict()
89
- entity2id = dict()
90
- id2entity = dict()
91
- entity_num = 0
92
- relation_num = 0
93
-
94
- element2id = ["relation2id.txt", "entity2id.txt"]
95
-
96
- for f in element2id:
97
- with open(os.path.join(path_data, f), "r") as f:
98
- for l in f.readlines():
99
- line = l.strip().split(sep)
100
- if f == "relation2id.txt":
101
- if len(line) == 1:
102
- relation_num = int(line[0])
103
- continue
104
- relation2id[line[0]] = int(line[1])
105
- id2relation[int(line[1])] = line[0]
106
- else:
107
- if len(line) == 1:
108
- entity_num = int(line[0])
109
- continue
110
- entity2id[line[0]] = int(line[1])
111
- id2entity[int(line[1])] = line[0]
112
- return (entity2id, id2entity), (relation2id, id2relation) (entity_num, relation_num)
113
-
114
-
115
- def generateTripleIdFile(from_original_data_dir, to_dir, sep='\t'):
116
- orignal_triple_files = ['train.txt', 'valid.txt', 'test.txt']
117
- to_id_files = [os.path.join(to_dir, x) for x in ['train2id.txt', 'valid2id.txt', 'test2id.txt']]
118
 
119
- entity2id_file_name = 'entity2id.txt'
120
- relation2id_file_name = 'relation2id.txt'
121
 
122
- if os.path.exists(os.path.join(from_original_data_dir, entity2id_file_name)):
123
- (ent2id, _), (rel2id, _), (entTotal, relTotal) = get_str2id(
124
- from_original_data_dir, sep=sep, no_sort=no_sort)
125
- else:
126
- data = []
127
- for file_name in orignal_triple_files:
128
- file_name = os.path.join(from_original_data_dir, file_name)
129
- data += load_triple_original_file(file_name, sep=sep)
130
-
131
- entities = []
132
- relations = []
133
- entities_set = set()
134
- relations_set = set()
135
-
136
- ent2id = {}
137
- rel2id = {}
138
- num_ent = 0
139
- num_rel = 0
140
- for element in data:
141
- if element[0] not in entities_set:
142
- entities_set.add(element[0])
143
- entities.append(element[0])
144
- ent2id[element[0]] = num_ent
145
- num_ent += 1
146
-
147
- if element[2] not in entities_set:
148
- entities_set.add(element[2])
149
- entities.append(element[2])
150
- ent2id[element[2]] = num_ent
151
- num_ent += 1
152
-
153
- if element[1] not in relations_set:
154
- relations_set.add(element[1])
155
- relations.append(element[1])
156
- rel2id[element[1]] = num_rel
157
- num_rel += 1
158
- entTotal = len(entities)
159
- relTotal = len(relations)
160
- write_str2id(ent2id, os.path.join(from_original_data_dir, entity2id_file_name))
161
- write_str2id(rel2id, os.path.join(from_original_data_dir, relation2id_file_name))
162
- del data, entities, relations
163
-
164
- for i, file_name in enumerate(orignal_triple_files):
165
- file_name = os.path.join(from_original_data_dir, file_name)
166
- data = load_triple_original_file(file_name, sep=sep)
167
- write_triple_from_original_data(data, to_id_files[i], (ent2id, rel2id), sep=sep)
168
 
169
 
170
  # TODO: Name of the dataset usually matches the script name with CamelCase instead of snake_case
@@ -191,6 +126,11 @@ class FB15k237(datasets.GeneratorBasedBuilder):
191
  ]
192
 
193
  DEFAULT_CONFIG_NAME = "kgraph" # It's not mandatory to have a default configuration. Just use one if it make sense.
 
 
 
 
 
194
 
195
  def _info(self):
196
  # TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
@@ -260,16 +200,15 @@ class FB15k237(datasets.GeneratorBasedBuilder):
260
  urls = _URLS["kgraph"]
261
  data_dir = dl_manager.download_and_extract(urls)
262
 
263
- if not os.path.exists(os.path.join(data_dir, 'train2id.txt')):
264
- generateTripleIdFile(data_dir, data_dir, sep='\t')
265
 
266
  return [
267
  datasets.SplitGenerator(
268
  name=datasets.Split.TRAIN,
269
  # These kwargs will be passed to _generate_examples
270
  gen_kwargs={
271
- "filepath": {"text": os.path.join(data_dir, "train.txt"),
272
- "id": os.path.join(data_dir, "train2id.txt")},
273
  "split": "train",
274
  },
275
  ),
@@ -277,8 +216,7 @@ class FB15k237(datasets.GeneratorBasedBuilder):
277
  name=datasets.Split.VALIDATION,
278
  # These kwargs will be passed to _generate_examples
279
  gen_kwargs={
280
- "filepath": {"text": os.path.join(data_dir, "valid.txt"),
281
- "id": os.path.join(data_dir, "valid2id.txt")},
282
  "split": "valid",
283
  },
284
  ),
@@ -286,9 +224,8 @@ class FB15k237(datasets.GeneratorBasedBuilder):
286
  name=datasets.Split.TEST,
287
  # These kwargs will be passed to _generate_examples
288
  gen_kwargs={
289
- "filepath": {"text": os.path.join(data_dir, "test.txt"),
290
- "id": os.path.join(data_dir, "test2id.txt")},
291
- "split": "test"
292
  },
293
  ),
294
  ]
@@ -325,43 +262,42 @@ class FB15k237(datasets.GeneratorBasedBuilder):
325
  line = line.strip().split('\t')
326
  description[line[0]] = line[1]
327
 
328
- with open(filepath['id'], encoding="utf-8") as f_id, open(filepath['text'], encoding="utf-8") as f_text:
329
- num = f_id.readline()
330
 
331
- for key in range(num):
332
- triple_id = [int(x) for x in f_id.readline().strip().split('\t')]
333
- triple_text = f_text.readline().strip().split('\t')
334
 
335
  if self.config.name == 'long':
336
  yield key, {
337
  "head": {
338
  "description": description[triple_text[0]],
339
- "id": triple_id[0],
340
- "text": triple_text,
341
  },
342
  "relation": {
343
  "description": triple_text[1].replace(sep, " ").replace("_", " ").strip(),
344
- "id": triple_id[1],
345
  "text": triple_text[1],
346
  },
347
  "tail": {
348
  "description": description[triple_text[2]],
349
- "id": triple_id[2],
350
  "text": triple_text[2],
351
  }
352
  }
353
  else:
354
  yield key, {
355
  "head": {
356
- "id": triple_id[0],
357
- "text": triple_text,
358
  },
359
  "relation": {
360
- "id": triple_id[1],
361
  "text": triple_text[1],
362
  },
363
  "tail": {
364
- "id": triple_id[2],
365
  "text": triple_text[2],
366
  }
367
  }
 
56
  "long": "https://raw.githubusercontent.com/pp413/Knowledge_embedding_benchmark_datasets/main/LongText.zip",
57
  }
58
 
 
 
 
 
 
59
 
60
  def load_triple_original_file(path_file, sep='\t'):
61
  data = []
 
65
  data.append(line[:3])
66
  return data
67
 
 
68
 
69
+ def generate_dit(from_original_data_dir, sep='\t'):
70
+ original_triple_files = ['train.txt', 'valid.txt', 'test.txt']
 
 
 
 
 
 
 
 
71
 
72
+ data = []
73
+ for file_name in original_triple_files:
74
+ file_name = os.path.join(from_original_data_dir, file_name)
75
+ data += load_triple_original_file(file_name, sep=sep)
76
+
77
+ entities_set = set()
78
+ relations_set = set()
79
+
80
+ ent2id = {}
81
+ rel2id = {}
82
+ num_ent = 0
83
+ num_rel = 0
84
+ for element in data:
85
+ if element[0] not in entities_set:
86
+ entities_set.add(element[0])
87
+ ent2id[element[0]] = num_ent
88
+ num_ent += 1
89
+
90
+ if element[2] not in entities_set:
91
+ entities_set.add(element[2])
92
+ ent2id[element[2]] = num_ent
93
+ num_ent += 1
94
+
95
+ if element[1] not in relations_set:
96
+ relations_set.add(element[1])
97
+ rel2id[element[1]] = num_rel
98
+ num_rel += 1
 
 
 
 
 
99
 
100
+ del data
 
101
 
102
+ return ent2id, rel2id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
 
105
  # TODO: Name of the dataset usually matches the script name with CamelCase instead of snake_case
 
126
  ]
127
 
128
  DEFAULT_CONFIG_NAME = "kgraph" # It's not mandatory to have a default configuration. Just use one if it make sense.
129
+
130
+ def __init__(self, *arg, writer_batch_size=None, **kwargs):
131
+ super().__init__(*arg, writer_batch_size=writer_batch_size, **kwargs)
132
+ self.ent2id = None
133
+ self.rel2id = None
134
 
135
  def _info(self):
136
  # TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
 
200
  urls = _URLS["kgraph"]
201
  data_dir = dl_manager.download_and_extract(urls)
202
 
203
+ if self.ent2id is None and self.rel2id is None:
204
+ self.ent2id, self.rel2id = generate_dit(data_dir)
205
 
206
  return [
207
  datasets.SplitGenerator(
208
  name=datasets.Split.TRAIN,
209
  # These kwargs will be passed to _generate_examples
210
  gen_kwargs={
211
+ "filepath": os.path.join(data_dir, "train.txt"),
 
212
  "split": "train",
213
  },
214
  ),
 
216
  name=datasets.Split.VALIDATION,
217
  # These kwargs will be passed to _generate_examples
218
  gen_kwargs={
219
+ "filepath": os.path.join(data_dir, "valid.txt"),
 
220
  "split": "valid",
221
  },
222
  ),
 
224
  name=datasets.Split.TEST,
225
  # These kwargs will be passed to _generate_examples
226
  gen_kwargs={
227
+ "filepath": os.path.join(data_dir, "test.txt"),
228
+ "split": "test",
 
229
  },
230
  ),
231
  ]
 
262
  line = line.strip().split('\t')
263
  description[line[0]] = line[1]
264
 
265
+ with open(filepath, encoding="utf-8") as f:
266
+ key = 0
267
 
268
+ for line in f.readlines():
269
+ triple_text = line.strip().split('\t')
 
270
 
271
  if self.config.name == 'long':
272
  yield key, {
273
  "head": {
274
  "description": description[triple_text[0]],
275
+ "id": self.ent2id[triple_text[0]],
276
+ "text": triple_text[0],
277
  },
278
  "relation": {
279
  "description": triple_text[1].replace(sep, " ").replace("_", " ").strip(),
280
+ "id": self.rel2id[triple_text[1]],
281
  "text": triple_text[1],
282
  },
283
  "tail": {
284
  "description": description[triple_text[2]],
285
+ "id": self.ent2id[triple_text[2]],
286
  "text": triple_text[2],
287
  }
288
  }
289
  else:
290
  yield key, {
291
  "head": {
292
+ "id": self.ent2id[triple_text[0]],
293
+ "text": triple_text[0],
294
  },
295
  "relation": {
296
+ "id": self.rel2id[triple_text[1]],
297
  "text": triple_text[1],
298
  },
299
  "tail": {
300
+ "id": self.ent2id[triple_text[2]],
301
  "text": triple_text[2],
302
  }
303
  }