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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
# TODO: Address all TODOs and remove all explanatory comments
|
15 |
+
"""TODO: A open dataset for Knowledge Representation, Link Prediction, and Triple Classification tasks in knowledge graph research."""
|
16 |
+
|
17 |
+
|
18 |
+
|
19 |
+
|
20 |
+
|
21 |
+
|
22 |
+
# import csv
|
23 |
+
# import json
|
24 |
+
import os
|
25 |
+
import numpy as np
|
26 |
+
|
27 |
+
import datasets
|
28 |
+
from kgraph.utils.tools import generateTripleIdFile
|
29 |
+
|
30 |
+
|
31 |
+
# TODO: Add BibTeX citation
|
32 |
+
# Find for instance the citation on arxiv or on the dataset repo/website
|
33 |
+
_CITATION = """\
|
34 |
+
@inproceedings{schlichtkrull2018modeling,
|
35 |
+
title={Modeling relational data with graph convolutional networks},
|
36 |
+
author={Schlichtkrull, Michael and Kipf, Thomas N and Bloem, Peter and Berg, Rianne van den and Titov, Ivan and Welling, Max},
|
37 |
+
booktitle={European semantic web conference},
|
38 |
+
pages={593--607},
|
39 |
+
year={2018},
|
40 |
+
organization={Springer}
|
41 |
+
}
|
42 |
+
"""
|
43 |
+
|
44 |
+
# TODO: Add description of the dataset here
|
45 |
+
# You can copy an official description
|
46 |
+
_DESCRIPTION = """\
|
47 |
+
FB15k-237 is a link prediction dataset created from FB15k. While FB15k consists of 1,345 relations, 14,951 entities, and 592,213 triples, many triples are inverses that cause leakage from the training to testing and validation splits. FB15k-237 was created by Toutanova and Chen (2015) to ensure that the testing and evaluation datasets do not have inverse relation test leakage. In summary, FB15k-237 dataset contains 310,079 triples with 14,505 entities and 237 relation types.
|
48 |
+
"""
|
49 |
+
|
50 |
+
# TODO: Add a link to an official homepage for the dataset here
|
51 |
+
# https://download.microsoft.com/download/8/7/0/8700516A-AB3D-4850-B4BB-805C515AECE1/FB15K-237.2.zip
|
52 |
+
_HOMEPAGE = "https://deepai.org/dataset/fb15k-237"
|
53 |
+
|
54 |
+
# TODO: Add the licence for the dataset here if you can find it
|
55 |
+
_LICENSE = "CC-BY"
|
56 |
+
|
57 |
+
# TODO: Add link to the official dataset URLs here
|
58 |
+
# The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
|
59 |
+
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
|
60 |
+
_URLS = {
|
61 |
+
# "original": "https://data.deepai.org/FB15K-237.2.zip",
|
62 |
+
"kgraph": "https://raw.githubusercontent.com/pp413/Knowledge_embedding_benchmark_datasets/main/FB15k-237.zip",
|
63 |
+
"long": "https://raw.githubusercontent.com/pp413/Knowledge_embedding_benchmark_datasets/main/LongText.zip",
|
64 |
+
}
|
65 |
+
|
66 |
+
|
67 |
+
# TODO: Name of the dataset usually matches the script name with CamelCase instead of snake_case
|
68 |
+
class FB15k237(datasets.GeneratorBasedBuilder):
|
69 |
+
"""TODO: A open dataset for Knowledge Representation, Link Prediction, and Triple Classification tasks in knowledge graph research."""
|
70 |
+
|
71 |
+
VERSION = datasets.Version("1.1.0")
|
72 |
+
|
73 |
+
# This is an example of a dataset with multiple configurations.
|
74 |
+
# If you don't want/need to define several sub-sets in your dataset,
|
75 |
+
# just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
|
76 |
+
|
77 |
+
# If you need to make complex sub-parts in the datasets with configurable options
|
78 |
+
# You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
|
79 |
+
# BUILDER_CONFIG_CLASS = MyBuilderConfig
|
80 |
+
|
81 |
+
# You will be able to load one or the other configurations in the following list with
|
82 |
+
# data = datasets.load_dataset('my_dataset', 'first_domain')
|
83 |
+
# data = datasets.load_dataset('my_dataset', 'second_domain')
|
84 |
+
BUILDER_CONFIGS = [
|
85 |
+
# datasets.BuilderConfig(name="original", version=VERSION, description="This original dataset"),
|
86 |
+
datasets.BuilderConfig(name="kgraph", version=VERSION, description="This basic dataset from kgraph"),
|
87 |
+
datasets.BuilderConfig(name="long", version=VERSION, description="This dataset with descriptions from kgraph"),
|
88 |
+
]
|
89 |
+
|
90 |
+
DEFAULT_CONFIG_NAME = "kgraph" # It's not mandatory to have a default configuration. Just use one if it make sense.
|
91 |
+
|
92 |
+
def _info(self):
|
93 |
+
# TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
|
94 |
+
# if self.config.name == "kgraph" or self.config.name == "original": # This is the name of the configuration selected in BUILDER_CONFIGS above
|
95 |
+
if self.config.name == "kgraph":
|
96 |
+
features = datasets.Features(
|
97 |
+
{
|
98 |
+
"head": datasets.features.Sequence({
|
99 |
+
"id": datasets.Value("int32"),
|
100 |
+
"text": datasets.Value("string"),
|
101 |
+
}),
|
102 |
+
"relation": datasets.features.Sequence({
|
103 |
+
"id": datasets.Value("int32"),
|
104 |
+
"text": datasets.Value("string"),
|
105 |
+
}),
|
106 |
+
"tail": datasets.features.Sequence({
|
107 |
+
"id": datasets.Value("int32"),
|
108 |
+
"text": datasets.Value("string"),
|
109 |
+
}),
|
110 |
+
# These are the features of your dataset like images, labels ...
|
111 |
+
}
|
112 |
+
)
|
113 |
+
else: # This is an example to show how to have different features for "first_domain" and "second_domain"
|
114 |
+
features = datasets.Features(
|
115 |
+
{
|
116 |
+
"head": datasets.features.Sequence({
|
117 |
+
"description": datasets.Value("string"),
|
118 |
+
"id": datasets.Value("int32"),
|
119 |
+
"text": datasets.Value("string"),
|
120 |
+
}),
|
121 |
+
"relation": datasets.features.Sequence({
|
122 |
+
"description": datasets.Value("string"),
|
123 |
+
"id": datasets.Value("int32"),
|
124 |
+
"text": datasets.Value("string"),
|
125 |
+
}),
|
126 |
+
"tail": datasets.features.Sequence({
|
127 |
+
"description": datasets.Value("string"),
|
128 |
+
"id": datasets.Value("int32"),
|
129 |
+
"text": datasets.Value("string"),
|
130 |
+
}),
|
131 |
+
# These are the features of your dataset like images, labels ...
|
132 |
+
}
|
133 |
+
)
|
134 |
+
return datasets.DatasetInfo(
|
135 |
+
# This is the description that will appear on the datasets page.
|
136 |
+
description=_DESCRIPTION,
|
137 |
+
# This defines the different columns of the dataset and their types
|
138 |
+
features=features, # Here we define them above because they are different between the two configurations
|
139 |
+
# If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
|
140 |
+
# specify them. They'll be used if as_supervised=True in builder.as_dataset.
|
141 |
+
# supervised_keys=("sentence", "label"),
|
142 |
+
# Homepage of the dataset for documentation
|
143 |
+
homepage=_HOMEPAGE,
|
144 |
+
# License for the dataset if available
|
145 |
+
license=_LICENSE,
|
146 |
+
# Citation for the dataset
|
147 |
+
citation=_CITATION,
|
148 |
+
)
|
149 |
+
|
150 |
+
def _split_generators(self, dl_manager):
|
151 |
+
# TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
|
152 |
+
# If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
|
153 |
+
|
154 |
+
# dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
|
155 |
+
# It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
|
156 |
+
# By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
|
157 |
+
urls = _URLS["kgraph"]
|
158 |
+
data_dir = dl_manager.download_and_extract(urls)
|
159 |
+
|
160 |
+
if not os.path.exists(os.path.join(data_dir, 'train2id.txt')):
|
161 |
+
generateTripleIdFile(data_dir, data_dir, sep='\t', no_sort=True)
|
162 |
+
|
163 |
+
return [
|
164 |
+
datasets.SplitGenerator(
|
165 |
+
name=datasets.Split.TRAIN,
|
166 |
+
# These kwargs will be passed to _generate_examples
|
167 |
+
gen_kwargs={
|
168 |
+
"filepath": {"text": os.path.join(data_dir, "train.txt"),
|
169 |
+
"id": os.path.join(data_dir, "train2id.txt")},
|
170 |
+
"split": "train",
|
171 |
+
},
|
172 |
+
),
|
173 |
+
datasets.SplitGenerator(
|
174 |
+
name=datasets.Split.VALIDATION,
|
175 |
+
# These kwargs will be passed to _generate_examples
|
176 |
+
gen_kwargs={
|
177 |
+
"filepath": {"text": os.path.join(data_dir, "valid.txt"),
|
178 |
+
"id": os.path.join(data_dir, "valid2id.txt")},
|
179 |
+
"split": "valid",
|
180 |
+
},
|
181 |
+
),
|
182 |
+
datasets.SplitGenerator(
|
183 |
+
name=datasets.Split.TEST,
|
184 |
+
# These kwargs will be passed to _generate_examples
|
185 |
+
gen_kwargs={
|
186 |
+
"filepath": {"text": os.path.join(data_dir, "test.txt"),
|
187 |
+
"id": os.path.join(data_dir, "test2id.txt")},
|
188 |
+
"split": "test"
|
189 |
+
},
|
190 |
+
),
|
191 |
+
]
|
192 |
+
|
193 |
+
# method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
|
194 |
+
def _generate_examples(self, filepath, split):
|
195 |
+
# TODO: This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
|
196 |
+
# The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
|
197 |
+
|
198 |
+
if self.config.name == "long":
|
199 |
+
urls = _URLS["long"]
|
200 |
+
data_dir = dl_manager.download_and_extract(urls)
|
201 |
+
|
202 |
+
data_name = self.__class__.__name__
|
203 |
+
sep = '_'
|
204 |
+
|
205 |
+
if data_name in ['FB15k-237', 'FB15k', 'FB13']:
|
206 |
+
long_description_file = 'FB15k_mid2description.txt'
|
207 |
+
sep = "/"
|
208 |
+
elif data_name in ['WN18', 'WN18RR', 'WN11']:
|
209 |
+
long_description_file = 'wn-entity2text-new.txt'
|
210 |
+
else:
|
211 |
+
long_description_file = None
|
212 |
+
|
213 |
+
assert long_description_file is not None, "There isn't a description file for this dataset."
|
214 |
+
|
215 |
+
long_description_file = os.path.join(data_dir, long_description_file)
|
216 |
+
|
217 |
+
description = {}
|
218 |
+
|
219 |
+
with open(long_description_file, encoding="utf-8") as f:
|
220 |
+
|
221 |
+
for line in f.readlines():
|
222 |
+
line = line.strip().split('\t')
|
223 |
+
description[line[0]] = line[1]
|
224 |
+
|
225 |
+
with open(filepath['id'], encoding="utf-8") as f_id, open(filepath['text'], encoding="utf-8") as f_text:
|
226 |
+
num = f_id.readline()
|
227 |
+
|
228 |
+
for key in range(num):
|
229 |
+
triple_id = [int(x) for x in f_id.readline().strip().split('\t')]
|
230 |
+
triple_text = f_text.readline().strip().split('\t')
|
231 |
+
|
232 |
+
if self.config.name == 'long':
|
233 |
+
yield key, {
|
234 |
+
"head": {
|
235 |
+
"description": description[triple_text[0]],
|
236 |
+
"id": triple_id[0],
|
237 |
+
"text": triple_text,
|
238 |
+
},
|
239 |
+
"relation": {
|
240 |
+
"description": triple_text[1].replace(sep, " ").replace("_", " ").strip(),
|
241 |
+
"id": triple_id[1],
|
242 |
+
"text": triple_text[1],
|
243 |
+
},
|
244 |
+
"tail": {
|
245 |
+
"description": description[triple_text[2]],
|
246 |
+
"id": triple_id[2],
|
247 |
+
"text": triple_text[2],
|
248 |
+
}
|
249 |
+
}
|
250 |
+
else:
|
251 |
+
yield key, {
|
252 |
+
"head": {
|
253 |
+
"id": triple_id[0],
|
254 |
+
"text": triple_text,
|
255 |
+
},
|
256 |
+
"relation": {
|
257 |
+
"id": triple_id[1],
|
258 |
+
"text": triple_text[1],
|
259 |
+
},
|
260 |
+
"tail": {
|
261 |
+
"id": triple_id[2],
|
262 |
+
"text": triple_text[2],
|
263 |
+
}
|
264 |
+
}
|