-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmetric.py
340 lines (253 loc) · 10.7 KB
/
metric.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
from sklearn.metrics import f1_score, precision_score, recall_score
import pdb
class TripletMetric:
def __init__(self):
self.pred = []
self.true = []
self.cnt = 0
def update_state(self, batch_preds, batch_trues, batch_id2label):
batch_size = len(batch_id2label)
_, seq_len = batch_trues.shape
batch_preds = batch_preds.view(batch_size, -1, seq_len)
batch_trues = batch_trues.view(batch_size, -1, seq_len)
batch_preds = batch_preds.cpu().tolist()
batch_trues = batch_trues.cpu().tolist()
for preds, trues, id2label in zip(batch_preds, batch_trues, batch_id2label):
preds = self.decode(preds, id2label)
trues = self.decode(trues, id2label)
pred_triplet = self.extract(preds)
true_triplet = self.extract(trues)
self.pred.extend(pred_triplet)
self.true.extend(true_triplet)
self.cnt += 1
def result(self):
return self.score(self.pred, self.true)
def reset(self):
self.pred = []
self.true = []
self.cnt = 0
def decode(self, ids, id2label):
labels = []
for ins in ids:
ins_labels = list(map(lambda x: id2label[x], ins))
labels.append(ins_labels)
return labels
def extract(self, label_sequences):
results = []
for i, instance_label in enumerate(label_sequences):
spans = self.get_span(instance_label)
result = []
relations = {}
for span in spans:
relation, entity_type = span[0].split(":")
if relation not in relations:
relations[relation] = {"HEAD": [], "TAIL": []}
relations[relation][entity_type].append(span)
for relation, entities in relations.items():
heads = entities["HEAD"]
tails = entities["TAIL"]
for head in heads:
for tail in tails:
triplet = (self.cnt, i, head, tail)
result.append(triplet)
results.extend(result)
return results
def score(self, pred_tags, true_tags):
true_triplets = set(self.pred)
pred_triplets = set(self.true)
pred_correct = len(true_triplets & pred_triplets)
pred_all = len(pred_triplets)
true_all = len(true_triplets)
p = pred_correct / pred_all if pred_all > 0 else 0
r = pred_correct / true_all if true_all > 0 else 0
f1 = 2 * p * r / (p + r) if p + r > 0 else 0
return p, r, f1
def get_span(self, seq):
if any(isinstance(s, list) for s in seq):
seq = [item for sublist in seq for item in sublist + ['O']]
prev_tag = 'O'
prev_type = ''
begin_offset = 0
chunks = []
for i, chunk in enumerate(seq + ['O']):
tag = chunk[0]
type_ = chunk.split('-')[-1]
if self.end_of_span(prev_tag, tag, prev_type, type_):
chunks.append((prev_type, begin_offset, i-1))
if self.start_of_span(prev_tag, tag, prev_type, type_):
begin_offset = i
prev_tag = tag
prev_type = type_
return chunks
def start_of_span(self, prev_tag, tag, prev_type, type_):
chunk_start = False
if tag == 'B': chunk_start = True
if tag == 'S': chunk_start = True
if prev_tag == 'E' and tag == 'E': chunk_start = True
if prev_tag == 'E' and tag == 'I': chunk_start = True
if prev_tag == 'S' and tag == 'E': chunk_start = True
if prev_tag == 'S' and tag == 'I': chunk_start = True
if prev_tag == 'O' and tag == 'E': chunk_start = True
if prev_tag == 'O' and tag == 'I': chunk_start = True
if tag != 'O' and tag != '.' and prev_type != type_:
chunk_start = True
return chunk_start
def end_of_span(self, prev_tag, tag, prev_type, type_):
chunk_end = False
if prev_tag == 'E': chunk_end = True
if prev_tag == 'S': chunk_end = True
if prev_tag == 'B' and tag == 'B': chunk_end = True
if prev_tag == 'B' and tag == 'S': chunk_end = True
if prev_tag == 'B' and tag == 'O': chunk_end = True
if prev_tag == 'I' and tag == 'B': chunk_end = True
if prev_tag == 'I' and tag == 'S': chunk_end = True
if prev_tag == 'I' and tag == 'O': chunk_end = True
if prev_tag != 'O' and prev_tag != '.' and prev_type != type_:
chunk_end = True
return chunk_end
class EntityMetric:
def __init__(self):
self.pred = []
self.true = []
def update_state(self, batch_preds, batch_trues, batch_id2label):
batch_size = len(batch_id2label)
_, seq_len = batch_trues.shape
batch_preds = batch_preds.view(batch_size, -1, seq_len)
batch_trues = batch_trues.view(batch_size, -1, seq_len)
batch_preds = batch_preds.cpu().tolist()
batch_trues = batch_trues.cpu().tolist()
for preds, trues, id2label in zip(batch_preds, batch_trues, batch_id2label):
preds = self.decode(preds, id2label)
trues = self.decode(trues, id2label)
self.pred.extend(preds)
self.true.extend(trues)
def result(self):
return self.score(self.pred, self.true)
def reset(self):
self.pred = []
self.true = []
def decode(self, ids, id2label):
labels = []
for ins in ids:
ins_labels = list(map(lambda x: id2label[x], ins))
labels.append(ins_labels)
return labels
def score(self, pred_tags, true_tags):
true_spans = set(self.get_span(true_tags))
pred_spans = set(self.get_span(pred_tags))
pred_correct = len(true_spans & pred_spans)
pred_all = len(pred_spans)
true_all = len(true_spans)
p = pred_correct / pred_all if pred_all > 0 else 0
r = pred_correct / true_all if true_all > 0 else 0
f1 = 2 * p * r / (p + r) if p + r > 0 else 0
return p, r, f1
def get_span(self, seq):
if any(isinstance(s, list) for s in seq):
seq = [item for sublist in seq for item in sublist + ['O']]
prev_tag = 'O'
prev_type = ''
begin_offset = 0
chunks = []
for i, chunk in enumerate(seq + ['O']):
tag = chunk[0]
type_ = chunk.split(':')[-1]
if self.end_of_span(prev_tag, tag, prev_type, type_):
chunks.append((prev_type, begin_offset, i-1))
if self.start_of_span(prev_tag, tag, prev_type, type_):
begin_offset = i
prev_tag = tag
prev_type = type_
return chunks
def start_of_span(self, prev_tag, tag, prev_type, type_):
chunk_start = False
if tag == 'B': chunk_start = True
if tag == 'S': chunk_start = True
if prev_tag == 'E' and tag == 'E': chunk_start = True
if prev_tag == 'E' and tag == 'I': chunk_start = True
if prev_tag == 'S' and tag == 'E': chunk_start = True
if prev_tag == 'S' and tag == 'I': chunk_start = True
if prev_tag == 'O' and tag == 'E': chunk_start = True
if prev_tag == 'O' and tag == 'I': chunk_start = True
if tag != 'O' and tag != '.' and prev_type != type_:
chunk_start = True
return chunk_start
def end_of_span(self, prev_tag, tag, prev_type, type_):
chunk_end = False
if prev_tag == 'E': chunk_end = True
if prev_tag == 'S': chunk_end = True
if prev_tag == 'B' and tag == 'B': chunk_end = True
if prev_tag == 'B' and tag == 'S': chunk_end = True
if prev_tag == 'B' and tag == 'O': chunk_end = True
if prev_tag == 'I' and tag == 'B': chunk_end = True
if prev_tag == 'I' and tag == 'S': chunk_end = True
if prev_tag == 'I' and tag == 'O': chunk_end = True
if prev_tag != 'O' and prev_tag != '.' and prev_type != type_:
chunk_end = True
return chunk_end
class HeadMetric(EntityMetric):
def decode(self, ids, id2label):
t_id2label = {i: (j if "TAIL" not in j else "O") for i, j in id2label.items()}
labels = []
for ins in ids:
ins_labels = list(map(lambda x: t_id2label[x], ins))
labels.append(ins_labels)
return labels
class TailMetric(EntityMetric):
def decode(self, ids, id2label):
t_id2label = {i: (j if "HEAD" not in j else "O") for i, j in id2label.items()}
labels = []
for ins in ids:
ins_labels = list(map(lambda x: t_id2label[x], ins))
labels.append(ins_labels)
return labels
class RelationMetricV1:
def __init__(self):
self.pred = []
self.true = []
def update_state(self, batch_preds, batch_trues):
batch_preds = batch_preds.cpu().numpy()
batch_trues = batch_trues.cpu().numpy()
self.pred.append(batch_preds)
self.true.append(batch_trues)
def result(self):
return self.score()
def reset(self):
self.pred = []
self.true = []
def score(self):
pred = np.concatenate(self.pred)
true = np.concatenate(self.true)
p = precision_score(true, pred, average="macro")
r = recall_score(true, pred, average="macro")
f1 = f1_score(true, pred, average="macro")
return p, r, f1
class RelationMetricV2:
def __init__(self):
self.p = []
self.r = []
self.f1 = []
def update_state(self, batch_preds, batch_trues):
batch_preds = batch_preds.cpu().numpy()
batch_trues = batch_trues.cpu().numpy()
p = precision_score(batch_trues, batch_preds, average="macro")
r = recall_score(batch_trues, batch_preds, average="macro")
f1 = f1_score(batch_trues, batch_preds, average="macro")
self.p.append(p)
self.r.append(r)
self.f1.append(f1)
def result(self):
return self.score()
def reset(self):
self.p = []
self.r = []
self.f1 = []
def score(self):
p = sum(self.p) / len(self.p)
r = sum(self.r) / len(self.r)
f1 = sum(self.f1) / len(self.f1)
return p, r, f1
RelationMetric = RelationMetricV2