Datasets:

Languages:
English
Multilinguality:
monolingual
Size Categories:
10K<n<100K
Language Creators:
found
Annotations Creators:
other
Source Datasets:
extended|other
ArXiv:
Tags:
relation extraction
License:
File size: 9,792 Bytes
643d6a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bb353a
 
 
 
643d6a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bb353a
 
 
 
 
 
 
 
 
 
643d6a8
c0f60de
 
9bb353a
c0f60de
 
 
9bb353a
 
 
 
c0f60de
 
643d6a8
 
 
 
 
 
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
# coding=utf-8
# Copyright 2022 The current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""The KBP37 dataset for English Relation Classification"""

import datasets

_CITATION = """\
@article{DBLP:journals/corr/ZhangW15a,
  author    = {Dongxu Zhang and
               Dong Wang},
  title     = {Relation Classification via Recurrent Neural Network},
  journal   = {CoRR},
  volume    = {abs/1508.01006},
  year      = {2015},
  url       = {http://arxiv.org/abs/1508.01006},
  eprinttype = {arXiv},
  eprint    = {1508.01006},
  timestamp = {Fri, 04 Nov 2022 18:37:50 +0100},
  biburl    = {https://dblp.org/rec/journals/corr/ZhangW15a.bib},
  bibsource = {dblp computer science bibliography, https://dblp.org}
}
"""

_DESCRIPTION = """\
KBP37 is a revision of MIML-RE annotation dataset, provided by Gabor Angeli et al. (2014). They use both the 2010 and 
2013 KBP official document collections, as well as a July 2013 dump of Wikipedia as the text corpus for annotation. 
There are 33811 sentences been annotated. Zhang and Wang made several refinements:
1. They add direction to the relation names, e.g. '`per:employee_of`' is split into  '`per:employee of(e1,e2)`'
and '`per:employee of(e2,e1)`'. They also replace '`org:parents`' with '`org:subsidiaries`' and replace
'`org:member of’ with '`org:member`' (by their reverse directions).
2. They discard low frequency relations such that both directions of each relation occur more than 100 times in the 
dataset.

KBP37 contains 18 directional relations and an additional '`no_relation`' relation, resulting in 37 relation classes.
"""

_HOMEPAGE = ""

_LICENSE = ""


# The HuggingFace dataset library don't host the datasets but only point to the original files
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
_URLs = {
    "train": "https://raw.githubusercontent.com/zhangdongxu/kbp37/master/train.txt",
    "validation": "https://raw.githubusercontent.com/zhangdongxu/kbp37/master/dev.txt",
    "test": "https://raw.githubusercontent.com/zhangdongxu/kbp37/master/test.txt"
}

_VERSION = datasets.Version("1.0.0")

_CLASS_LABELS = [
    "no_relation",
    "org:alternate_names(e1,e2)",
    "org:alternate_names(e2,e1)",
    "org:city_of_headquarters(e1,e2)",
    "org:city_of_headquarters(e2,e1)",
    "org:country_of_headquarters(e1,e2)",
    "org:country_of_headquarters(e2,e1)",
    "org:founded(e1,e2)",
    "org:founded(e2,e1)",
    "org:founded_by(e1,e2)",
    "org:founded_by(e2,e1)",
    "org:members(e1,e2)",
    "org:members(e2,e1)",
    "org:stateorprovince_of_headquarters(e1,e2)",
    "org:stateorprovince_of_headquarters(e2,e1)",
    "org:subsidiaries(e1,e2)",
    "org:subsidiaries(e2,e1)",
    "org:top_members/employees(e1,e2)",
    "org:top_members/employees(e2,e1)",
    "per:alternate_names(e1,e2)",
    "per:alternate_names(e2,e1)",
    "per:cities_of_residence(e1,e2)",
    "per:cities_of_residence(e2,e1)",
    "per:countries_of_residence(e1,e2)",
    "per:countries_of_residence(e2,e1)",
    "per:country_of_birth(e1,e2)",
    "per:country_of_birth(e2,e1)",
    "per:employee_of(e1,e2)",
    "per:employee_of(e2,e1)",
    "per:origin(e1,e2)",
    "per:origin(e2,e1)",
    "per:spouse(e1,e2)",
    "per:spouse(e2,e1)",
    "per:stateorprovinces_of_residence(e1,e2)",
    "per:stateorprovinces_of_residence(e2,e1)",
    "per:title(e1,e2)",
    "per:title(e2,e1)"
]


class KBP37(datasets.GeneratorBasedBuilder):
    """KBP37 is a relation extraction dataset"""

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(
            name="kbp37", version=_VERSION, description="The KBP37 dataset."
        ),
        datasets.BuilderConfig(
            name="kbp37_formatted", version=_VERSION, description="The formatted KBP37 dataset."
        )
    ]

    DEFAULT_CONFIG_NAME = "kbp37"  # type: ignore

    def _info(self):
        if self.config.name == "kbp37_formatted":
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "token": datasets.Sequence(datasets.Value("string")),
                    "e1_start": datasets.Value("int32"),
                    "e1_end": datasets.Value("int32"),
                    "e2_start": datasets.Value("int32"),
                    "e2_end": datasets.Value("int32"),
                    "relation": datasets.ClassLabel(names=_CLASS_LABELS),
                }
            )
        else:
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "sentence": datasets.Value("string"),
                    "relation": datasets.ClassLabel(names=_CLASS_LABELS),
                }
            )

        return datasets.DatasetInfo(
            # This is the description that will appear on the datasets page.
            description=_DESCRIPTION,
            # This defines the different columns of the dataset and their types
            features=features,  # Here we define them above because they are different between the two configurations
            # If there's a common (input, target) tuple from the features,
            # specify them here. They'll be used if as_supervised=True in
            # builder.as_dataset.
            supervised_keys=None,
            # Homepage of the dataset for documentation
            homepage=_HOMEPAGE,
            # License for the dataset if available
            license=_LICENSE,
            # Citation for the dataset
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name

        # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLs
        # 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.
        # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive

        downloaded_files = dl_manager.download_and_extract(_URLs)

        return [datasets.SplitGenerator(name=i, gen_kwargs={"filepath": downloaded_files[str(i)]})
                for i in [datasets.Split.TRAIN, datasets.Split.VALIDATION, datasets.Split.TEST]]

    def _generate_examples(self, filepath):
        """Yields examples."""
        # This method will receive as arguments the `gen_kwargs` defined in the previous `_split_generators` method.
        # It is in charge of opening the given file and yielding (key, example) tuples from the dataset
        # The key is not important, it's more here for legacy reason (legacy from tfds)

        with open(filepath, encoding="utf-8") as f:
            data = []
            example_line = None
            for idx, line in enumerate(f.readlines()):
                line_no = idx % 4  # first line contains example, second line relation, third and fourth lines are \n
                if line_no == 0:
                    example_line = line.strip().split("\t")
                elif line_no == 1:
                    data.append({"example": example_line, "relation": line.strip()})
            for example in data:
                id_ = example["example"][0]
                text = example["example"][1]
                assert text[:2] == "\" " and text[-2:] == " \""
                text = text[2:-2]
                relation = example["relation"]

                if self.config.name == "kbp37_formatted":
                    text = text.replace("<e1>", " <e1> ")
                    text = text.replace("<e2>", " <e2> ")
                    text = text.replace("</e1>", " </e1> ")
                    text = text.replace("</e2>", " </e2> ")
                    text = text.strip().replace(r"\s\s+", r"\s")
                    tokens = text.split()
                    e1_start = tokens.index("<e1>")
                    e2_start = tokens.index("<e2>")
                    if e1_start < e2_start:
                        tokens.pop(e1_start)
                        e1_end = tokens.index("</e1>")
                        tokens.pop(e1_end)
                        e2_start = tokens.index("<e2>")
                        tokens.pop(e2_start)
                        e2_end = tokens.index("</e2>")
                        tokens.pop(e2_end)

                    # some examples, like train/1276 are invalid (empty head/tail), and
                    # yield non-sensical examples without this check
                    if e1_end > e1_start and e2_end > e2_start:
                        yield int(id_), {
                            "id": id_,
                            "token": tokens,
                            "e1_start": e1_start,
                            "e1_end": e1_end,
                            "e2_start": e2_start,
                            "e2_end": e2_end,
                            "relation": relation,
                        }
                else:
                    yield int(id_), {
                        "id": id_,
                        "sentence": text,
                        "relation": relation,
                    }