-
Notifications
You must be signed in to change notification settings - Fork 15
/
tacred2mnli.py
239 lines (208 loc) · 7.23 KB
/
tacred2mnli.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
from argparse import ArgumentParser
from dataclasses import dataclass
from collections import defaultdict, Counter
from typing import Dict
import numpy as np
import json
import sys
from pprint import pprint
import random
random.seed(0)
np.random.seed(0)
sys.path.append("./")
from a2t.relation_classification.tacred import TACRED_LABEL_TEMPLATES, TACRED_LABELS
@dataclass
class REInputFeatures:
subj: str
obj: str
context: str
pair_type: str = None
label: str = None
@dataclass
class MNLIInputFeatures:
premise: str
hypothesis: str
label: int
parser = ArgumentParser()
parser.add_argument("--input_file", type=str, default="data/tacred/dev.json")
# parser.add_argument('--model', type=str, default='microsoft/deberta-v2-xlarge-mnli')
parser.add_argument("--output_file", type=str, default="data/tacred/dev.mnli.json")
parser.add_argument("--negative_pattern", action="store_true", default=False)
parser.add_argument("--negn", type=int, default=1)
args = parser.parse_args()
templates = [
"{subj} and {obj} are not related",
"{subj} is also known as {obj}",
"{subj} was born in {obj}",
"{subj} is {obj} years old",
"{obj} is the nationality of {subj}",
"{subj} died in {obj}",
"{obj} is the cause of {subj}’s death",
"{subj} lives in {obj}",
"{subj} studied in {obj}",
"{subj} is a {obj}",
"{subj} is an employee of {obj}",
"{subj} believe in {obj}",
"{subj} is the spouse of {obj}",
"{subj} is the parent of {obj}",
"{obj} is the parent of {subj}",
"{subj} and {obj} are siblings",
"{subj} and {obj} are family",
"{subj} was convicted of {obj}",
"{subj} has political affiliation with {obj}",
"{obj} is a high level member of {subj}",
"{subj} has about {obj} employees",
"{obj} is member of {subj}",
"{subj} is member of {obj}",
"{obj} is a branch of {subj}",
"{subj} is a branch of {obj}",
"{subj} was founded by {obj}",
"{subj} was founded in {obj}",
"{subj} existed until {obj}",
"{subj} has its headquarters in {obj}",
"{obj} holds shares in {subj}",
"{obj} is the website of {subj}",
]
labels2id = {"entailment": 2, "neutral": 1, "contradiction": 0}
positive_templates: Dict[str, list] = defaultdict(list)
negative_templates: Dict[str, list] = defaultdict(list)
if not args.negative_pattern:
templates = templates[1:]
for label in TACRED_LABELS:
if not args.negative_pattern and label == "no_relation":
continue
for template in templates:
if label != "no_relation" and template == "{subj} and {obj} are not related":
continue
if template in TACRED_LABEL_TEMPLATES[label]:
positive_templates[label].append(template)
else:
negative_templates[label].append(template)
def tacred2mnli(
instance: REInputFeatures,
positive_templates,
negative_templates,
templates,
negn=1,
posn=1,
):
if instance.label == "no_relation":
template = random.choices(templates, k=negn)
return [
MNLIInputFeatures(
premise=instance.context,
hypothesis=f"{t.format(subj=instance.subj, obj=instance.obj)}.",
label=labels2id["contradiction"],
)
for t in template
]
# Generate the positive examples
mnli_instances = []
positive_template = random.choices(positive_templates[instance.label], k=posn)
mnli_instances.extend(
[
MNLIInputFeatures(
premise=instance.context,
hypothesis=f"{t.format(subj=instance.subj, obj=instance.obj)}.",
label=labels2id["entailment"],
)
for t in positive_template
]
)
# Generate the negative templates
negative_template = random.choices(negative_templates[instance.label], k=negn)
mnli_instances.extend(
[
MNLIInputFeatures(
premise=instance.context,
hypothesis=f"{t.format(subj=instance.subj, obj=instance.obj)}.",
label=labels2id["neutral"],
)
for t in negative_template
]
)
return mnli_instances
def tacred2mnli_with_negative_pattern(
instance: REInputFeatures,
positive_templates,
negative_templates,
templates,
negn=1,
posn=1,
):
mnli_instances = []
# Generate the positive examples
positive_template = random.choices(positive_templates[instance.label], k=posn)
mnli_instances.extend(
[
MNLIInputFeatures(
premise=instance.context,
hypothesis=f"{t.format(subj=instance.subj, obj=instance.obj)}.",
label=labels2id["entailment"],
)
for t in positive_template
]
)
# Generate the negative templates
negative_template = random.choices(negative_templates[instance.label], k=negn)
mnli_instances.extend(
[
MNLIInputFeatures(
premise=instance.context,
hypothesis=f"{t.format(subj=instance.subj, obj=instance.obj)}.",
label=labels2id["neutral"] if instance.label != "no_relation" else labels2id["contradiction"],
)
for t in negative_template
]
)
# Add the contradiction regarding the no_relation pattern if the relation is not no_relation
if instance.label != "no_relation":
mnli_instances.append(
MNLIInputFeatures(
premise=instance.context,
hypothesis="{subj} and {obj} are not related.".format(subj=instance.subj, obj=instance.obj),
label=labels2id["contradiction"],
)
)
return mnli_instances
tacred2mnli = tacred2mnli_with_negative_pattern if args.negative_pattern else tacred2mnli
with open(args.input_file, "rt") as f:
mnli_data = []
stats = []
for line in json.load(f):
mnli_instance = tacred2mnli(
REInputFeatures(
subj=" ".join(line["token"][line["subj_start"] : line["subj_end"] + 1])
.replace("-LRB-", "(")
.replace("-RRB-", ")")
.replace("-LSB-", "[")
.replace("-RSB-", "]"),
obj=" ".join(line["token"][line["obj_start"] : line["obj_end"] + 1])
.replace("-LRB-", "(")
.replace("-RRB-", ")")
.replace("-LSB-", "[")
.replace("-RSB-", "]"),
pair_type=f"{line['subj_type']}:{line['obj_type']}",
context=" ".join(line["token"])
.replace("-LRB-", "(")
.replace("-RRB-", ")")
.replace("-LSB-", "[")
.replace("-RSB-", "]"),
label=line["relation"],
),
positive_templates,
negative_templates,
templates,
negn=args.negn,
)
mnli_data.extend(mnli_instance)
stats.append(line["relation"] != "no_relation")
with open(args.output_file, "wt") as f:
for data in mnli_data:
f.write(f"{json.dumps(data.__dict__)}\n")
# json.dump([data.__dict__ for data in mnli_data], f, indent=2)
count = Counter([data.label for data in mnli_data])
pprint(count)
count = Counter(stats)
pprint(count)
print(len(stats))