-
Notifications
You must be signed in to change notification settings - Fork 1
/
evaluate.py
354 lines (301 loc) · 11.6 KB
/
evaluate.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
from typing import List
import re
from label_names import name2label, label2name
import os
from seqeval.metrics import classification_report, f1_score
from tqdm.auto import tqdm
import argparse
import json
from dataset import get_task_labels
def split_sentence(
tag_regex,
sentence: str,
recursion_limit: int = 100,
) -> List[str]:
sentence = sentence.strip().split()
if recursion_limit == 0:
return sentence
new_sentence: List[str] = []
for word in sentence:
search_result = tag_regex.search(word)
if search_result:
span = search_result.span()
l = word[: span[0]].strip()
r = word[span[1] :].strip()
t = word[span[0] : span[1]].strip()
if l:
new_sentence.extend(split_sentence(tag_regex, l, recursion_limit - 1))
new_sentence.append(t)
if r:
new_sentence.extend(split_sentence(tag_regex, r, recursion_limit - 1))
else:
new_sentence.append(word)
return new_sentence
def get_label_type(label: str) -> (str, bool):
label = label.strip()
is_start = not label.startswith("</")
if is_start:
label_type = name2label(label[1:-1])
else:
label_type = name2label(label[2:-1])
return label_type, is_start
def get_iob(html_sentence: str, possible_labels: List[str]) -> (List[str], List[str]):
"""
Input
<Person> Obama </Person> went to <Location> New York </Location> .
Output
["B-PER","O","O","B-LOC","I-LOC","O"]
"""
inside_tag: bool = False
current_label_type: str = ""
tag_regex = re.compile(
f"</?({'|'.join([label2name(p) for p in possible_labels])})>"
)
html_words = split_sentence(
tag_regex, html_sentence, recursion_limit=max(len(html_sentence) * 8, 999)
)
labels = []
words = []
first = True
for word in html_words:
result = tag_regex.match(word)
if result:
label_type, is_start = get_label_type(word)
if is_start:
inside_tag = True
current_label_type = label_type
first = True
else:
inside_tag = False
else:
if inside_tag:
if first:
labels.append(f"B-{current_label_type}")
first = False
else:
labels.append(f"I-{current_label_type}")
else:
labels.append("O")
words.append(word)
assert len(words) == len(labels), (
f"Len of words and labels are not equal: {len(words)} != {len(labels)}\n"
f"Words: {words}\n"
f"Labels: {labels}"
)
return words, labels
def evaluate_most_probable(
predictions: List[List[str]],
gold: List[str],
output_name: str,
task_labels: List[str],
):
output_name = os.path.abspath(output_name)
os.makedirs(os.path.dirname(output_name), exist_ok=True)
predicted_labels = []
gold_labels = []
with open(f"{output_name}.tsv", "w", encoding="utf8") as output_file:
for predicted_sentence, gold_sentence in zip(
tqdm(predictions, desc="Evaluate Top1"), gold
):
sentence_predicted_words, sentence_predicted_labels = get_iob(
html_sentence=predicted_sentence[0],
possible_labels=task_labels,
)
sentence_gold_words, sentence_gold_labels = get_iob(
html_sentence=gold_sentence,
possible_labels=task_labels,
)
if len(sentence_predicted_words) > len(sentence_gold_words):
# print(
# f"Warning. Predicted sentence is longer than gold sentence. "
# f"We will truncate the predicted sentence\n"
# f"Predicted: {sentence_predicted_words}\n"
# f"Gold: {sentence_gold_words}\n"
# )
sentence_predicted_words = sentence_predicted_words[
: len(sentence_gold_words)
]
sentence_predicted_labels = sentence_predicted_labels[
: len(sentence_gold_words)
]
elif len(sentence_predicted_words) < len(sentence_gold_words):
# print(
# f"Warning. Predicted sentence is shorter than gold sentence."
# f"We will extend the predicted labels with O's\n"
# f"Predicted: {sentence_predicted_words}\n"
# f"Gold: {sentence_gold_words}\n"
# )
sentence_predicted_labels = sentence_predicted_labels + (
["O"] * (len(sentence_gold_words) - len(sentence_predicted_words))
)
for word, tag in zip(sentence_predicted_words, sentence_predicted_labels):
print(f"{word} {tag}", file=output_file)
print(file=output_file)
predicted_labels.append(sentence_predicted_labels)
gold_labels.append(sentence_gold_labels)
with open(f"{output_name}.txt", "w", encoding="utf8") as output_file:
try:
cr = classification_report(
y_true=gold_labels, y_pred=predicted_labels, digits=4, zero_division="1"
)
except ValueError as e:
cr = str(e)
print(
cr,
file=output_file,
)
try:
micro_f1 = f1_score(
y_true=gold_labels,
y_pred=predicted_labels,
average="micro",
zero_division="1",
)
except ValueError as e:
print(f"Error calculating micro f1: {e}")
micro_f1 = 0
try:
macro_f1 = f1_score(
y_true=gold_labels,
y_pred=predicted_labels,
average="macro",
zero_division="1",
)
except ValueError as e:
print(f"Error calculating macro f1: {e}")
macro_f1 = 0
print(f"Micro F1: {micro_f1}", file=output_file)
print(f"Macro F1: {macro_f1}", file=output_file)
return micro_f1
def evaluate_best_prediction(
predictions: List[List[str]],
gold: List[str],
output_name: str,
task_labels: List[str],
):
output_name = os.path.abspath(output_name)
os.makedirs(os.path.dirname(output_name), exist_ok=True)
predicted_labels = []
gold_labels = []
with open(f"{output_name}.tsv", "w", encoding="utf8") as output_file:
for predicted_sentence, gold_sentence in zip(
tqdm(predictions, desc="Evaluate Upperbound"), gold
):
best_pred = 0
best_pred_f1 = 0
sentence_gold_words, sentence_gold_labels = get_iob(
html_sentence=gold_sentence,
possible_labels=task_labels,
)
for i in range(len(predicted_sentence)):
sentence_predicted_words, sentence_predicted_labels = get_iob(
html_sentence=predicted_sentence[i],
possible_labels=task_labels,
)
if len(sentence_predicted_words) > len(sentence_gold_words):
sentence_predicted_labels = sentence_predicted_labels[
: len(sentence_gold_words)
]
elif len(sentence_predicted_words) < len(sentence_gold_words):
sentence_predicted_labels = sentence_predicted_labels + (
["O"]
* (len(sentence_gold_words) - len(sentence_predicted_words))
)
try:
micro_f1 = f1_score(
y_true=[sentence_gold_labels],
y_pred=[sentence_predicted_labels],
average="micro",
zero_division="1",
)
except ValueError as e:
print(f"Error calculating micro f1: {e}")
micro_f1 = 0
if micro_f1 > best_pred_f1:
best_pred = i
best_pred_f1 = micro_f1
sentence_predicted_words, sentence_predicted_labels = get_iob(
html_sentence=predicted_sentence[best_pred],
possible_labels=task_labels,
)
if len(sentence_predicted_words) > len(sentence_gold_words):
sentence_predicted_words = sentence_predicted_words[
: len(sentence_gold_words)
]
sentence_predicted_labels = sentence_predicted_labels[
: len(sentence_gold_words)
]
# print(
# f"Warning. Predicted sentence is longer than gold sentence. "
# f"We will truncate the predicted sentence\n"
# f"Predicted: {sentence_predicted_words}\n"
# f"Gold: {sentence_gold_words}\n"
# )
elif len(sentence_predicted_words) < len(sentence_gold_words):
sentence_predicted_labels = sentence_predicted_labels + (
["O"] * (len(sentence_gold_words) - len(sentence_predicted_words))
)
# print(
# f"Warning. Predicted sentence is shorter than gold sentence."
# f"We will extend the predicted labels with O's\n"
# f"Predicted: {sentence_predicted_words}\n"
# f"Gold: {sentence_gold_words}\n"
# )
for word, tag in zip(sentence_predicted_words, sentence_predicted_labels):
print(f"{word} {tag}", file=output_file)
print(file=output_file)
predicted_labels.append(sentence_predicted_labels)
gold_labels.append(sentence_gold_labels)
with open(f"{output_name}.txt", "w", encoding="utf8") as output_file:
try:
cr = classification_report(
y_true=gold_labels, y_pred=predicted_labels, digits=4, zero_division="1"
)
except ValueError as e:
cr = str(e)
print(
cr,
file=output_file,
)
try:
micro_f1 = f1_score(
y_true=gold_labels,
y_pred=predicted_labels,
average="micro",
zero_division="1",
)
except ValueError as e:
print(f"Error calculating micro f1: {e}")
micro_f1 = 0
try:
macro_f1 = f1_score(
y_true=gold_labels,
y_pred=predicted_labels,
average="macro",
zero_division="1",
)
except ValueError as e:
print(f"Error calculating macro f1: {e}")
macro_f1 = 0
print(f"Micro F1: {micro_f1}", file=output_file)
print(f"Macro F1: {macro_f1}", file=output_file)
return micro_f1
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--predictions_json", type=str, required=True)
parser.add_argument("--gold_tsv", type=str, required=True)
parser.add_argument("--output_name", type=str, required=True)
args = parser.parse_args()
preds = []
gold = []
with open(args.predictions_json, "r", encoding="utf8") as f:
for line in f:
line = json.loads(line.strip())
preds.append(line["prediction"])
gold.append(line["gold"])
evaluate_most_probable(
predictions=preds,
gold=gold,
output_name=args.output_name,
task_labels=get_task_labels(args.gold_tsv),
)