-
Notifications
You must be signed in to change notification settings - Fork 0
/
classes.py
368 lines (273 loc) · 10.8 KB
/
classes.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
import os
class Annotation(object):
def __init__(self, file_name=None, root="root"):
self.doc_id = ''
self.sys_id = ''
self.text = None
self.root = root
self.ner = []
self.indexes = []
self.verbose = False
if file_name:
self.sys_id = os.path.basename(os.path.dirname(file_name))
self.doc_id = os.path.splitext(os.path.basename(file_name))[0]
else:
self.doc_id = None
@property
def id(self):
return self.doc_id
class BratAnnotation(Annotation):
def __init__(self, file_name=None, root="root"):
self.doc_id = ''
self.sys_id = ''
self.root = root
self.ner = []
self.verbose = False
if file_name:
self.sys_id = os.path.basename(os.path.dirname(file_name))
self.doc_id = os.path.splitext(os.path.basename(file_name))[0]
self.parse_tags(file_name)
self.file_name = file_name
else:
self.doc_id = None
def get_ner(self):
return self.ner
def parse_tags(self, file_name=None):
if file_name is not None:
for row in open(file_name, 'r'):
line = row.strip()
if line.startswith("T"): # Lines is a Brat TAG
try:
label = line.split("\t")[1].split()
tag = label[0]
start = int(label[1])
end = int(label[2])
self.ner.append((tag, start, end))
except IndexError:
print("ERROR! Index error while splitting sentence '" +
line + "' in document '" + file_name + "'!")
else: # Line is a Brat comment
if self.verbose:
print("\tSkipping line (comment):\t" + line)
class IndexingAnnotation(Annotation):
""" This class models the PharmaCoNER TSV annotation format."""
def __init__(self, file_name=None, root="root"):
self.doc_id = ''
self.sys_id = ''
self.root = root
self.indexes = []
self.verbose = False
if file_name:
self.sys_id = os.path.basename(os.path.dirname(file_name))
self.doc_id = os.path.splitext(os.path.basename(file_name))[0]
self.parse_indexes(file_name)
self.file_name = file_name
else:
self.doc_id = None
def get_index(self):
return self.indexes
def parse_indexes(self, file_name=None):
if file_name is not None:
for row in open(file_name, 'r'):
line = row.strip()
sys_id = line.split("\t")[0]
sys_code = line.split("\t")[1]
if sys_id == self.doc_id:
self.indexes.append(sys_code)
else:
self.indexes.append(sys_code)
print("WARNING: Filename '" + self.doc_id + "' and File ID '" + sys_id +"' does not match")
class Evaluate(object):
"""Base class with all methods to evaluate the different subtracks."""
def __init__(self, sys_ann, gs_ann):
self.tp = []
self.fp = []
self.fn = []
self.doc_ids = []
self.verbose = False
self.sys_id = sys_ann[list(sys_ann.keys())[0]].sys_id
@staticmethod
def get_tagset_ner(annotation):
return annotation.get_ner()
@staticmethod
def get_tagset_indexes(annotation):
return annotation.get_index()
@staticmethod
def recall(tp, fn):
try:
return len(tp) / float(len(fn) + len(tp))
except ZeroDivisionError:
return 0.0
@staticmethod
def precision(tp, fp):
try:
return len(tp) / float(len(fp) + len(tp))
except ZeroDivisionError:
return 0.0
@staticmethod
def F_beta(p, r, beta=1):
try:
return (1 + beta**2) * ((p * r) / (p + r))
except ZeroDivisionError:
return 0.0
def micro_recall(self):
try:
return sum([len(t) for t in self.tp]) / \
float(sum([len(t) for t in self.tp]) +
sum([len(t) for t in self.fn]))
except ZeroDivisionError:
return 0.0
def micro_precision(self):
try:
return sum([len(t) for t in self.tp]) / \
float(sum([len(t) for t in self.tp]) +
sum([len(t) for t in self.fp]))
except ZeroDivisionError:
return 0.0
def _print_docs(self):
for i, doc_id in enumerate(self.doc_ids):
mp = Evaluate.precision(self.tp[i], self.fp[i])
mr = Evaluate.recall(self.tp[i], self.fn[i])
str_fmt = "{:<35}{:<15}{:<20}"
print(str_fmt.format(doc_id,
"Precision",
"{:.4}".format(mp)))
print(str_fmt.format("",
"Recall",
"{:.4}".format(mr)))
print(str_fmt.format("",
"F1",
"{:.4}".format(Evaluate.F_beta(mp, mr))))
print("{:-<60}".format(""))
def _print_summary(self):
mp = self.micro_precision()
mr = self.micro_recall()
str_fmt = "{:<35}{:<15}{:<20}"
print(str_fmt.format("", "", ""))
print("Report (" + self.sys_id + "):")
print("{:-<60}".format(""))
print(str_fmt.format(self.label,
"Measure", "Micro"))
print("{:-<60}".format(""))
print(str_fmt.format("Total ({} docs)".format(len(self.doc_ids)),
"Precision",
"{:.4}".format(mp)))
print(str_fmt.format("",
"Recall",
"{:.4}".format(mr)))
print(str_fmt.format("",
"F1",
"{:.4}".format(Evaluate.F_beta(mr, mp))))
print("{:-<60}".format(""))
print("\n")
def print_docs(self):
print("\n")
print("Report ({}):".format(self.sys_id))
print("{:-<60}".format(""))
print("{:<35}{:<15}{:<20}".format("Document ID", "Measure", "Micro"))
print("{:-<60}".format(""))
self._print_docs()
def print_report(self, verbose=False):
self.verbose = verbose
if verbose:
self.print_docs()
self._print_summary()
class EvaluateSubtrack1(Evaluate):
"""Class for running the NER evaluation."""
def __init__(self, sys_sas, gs_sas):
self.tp = []
self.fp = []
self.fn = []
# self.num_sentences = []
self.doc_ids = []
self.verbose = False
self.sys_id = sys_sas[list(sys_sas.keys())[0]].sys_id
self.label = "Subtrack 1 [NER]"
for doc_id in sorted(list(set(sys_sas.keys()) & set(gs_sas.keys()))):
gold = set(self.get_tagset_ner(gs_sas[doc_id]))
sys = set(self.get_tagset_ner(sys_sas[doc_id]))
self.tp.append(gold.intersection(sys))
self.fp.append(sys - gold)
self.fn.append(gold - sys)
self.doc_ids.append(doc_id)
def _print_docs(self):
for i, doc_id in enumerate(self.doc_ids):
mp = EvaluateSubtrack1.precision(self.tp[i], self.fp[i])
mr = EvaluateSubtrack1.recall(self.tp[i], self.fn[i])
str_fmt = "{:<35}{:<15}{:<20}"
print(str_fmt.format("",
"Precision",
"{:.4}".format(mp)))
print(str_fmt.format("",
"Recall",
"{:.4}".format(mr)))
print(str_fmt.format("",
"F1",
"{:.4}".format(Evaluate.F_beta(mp, mr))))
print("{:-<60}".format(""))
def _print_summary(self):
mp = self.micro_precision()
mr = self.micro_recall()
# ml = self.micro_leak()
str_fmt = "{:<35}{:<15}{:<20}"
print(str_fmt.format("", "", ""))
print("Report (" + self.sys_id + "):")
print("{:-<60}".format(""))
print(str_fmt.format(self.label,
"Measure", "Micro"))
print("{:-<60}".format(""))
print(str_fmt.format("Total ({} docs)".format(len(self.doc_ids)),
"Precision",
"{:.4}".format(mp)))
print(str_fmt.format("",
"Recall",
"{:.4}".format(mr)))
print(str_fmt.format("",
"F1",
"{:.4}".format(Evaluate.F_beta(mr, mp))))
print("{:-<60}".format(""))
print("\n")
class EvaluateSubtrack2(Evaluate):
"""Class for running the Concept Indexing evaluation."""
def __init__(self, sys_sas, gs_sas):
self.tp = []
self.fp = []
self.fn = []
self.doc_ids = []
self.verbose = False
self.sys_id = sys_sas[list(sys_sas.keys())[0]].sys_id
self.label = "Subtrack 2 [Indexing]"
for doc_id in sorted(list(set(sys_sas.keys()) & set(gs_sas.keys()))):
gold = set(self.get_tagset_indexes(gs_sas[doc_id]))
sys = set(self.get_tagset_indexes(sys_sas[doc_id]))
self.tp.append(gold.intersection(sys))
self.fp.append(sys - gold)
self.fn.append(gold - sys)
self.doc_ids.append(doc_id)
class PharmaconerEvaluation(object):
"""Base class for running the evaluations."""
def __init__(self):
self.evaluations = []
def add_eval(self, e, label=""):
e.sys_id = "SYSTEM: " + e.sys_id
e.label = label
self.evaluations.append(e)
def print_docs(self):
for e in self.evaluations:
e.print_docs()
def print_report(self, verbose=False):
for e in self.evaluations:
e.print_report(verbose=verbose)
class NER_Evaluation(PharmaconerEvaluation):
"""Class for running the NER evaluation (Subtrack 1)."""
def __init__(self, annotator_cas, gold_cas, **kwargs):
self.evaluations = []
# Basic Evaluation
self.add_eval(EvaluateSubtrack1(annotator_cas, gold_cas, **kwargs),
label="SubTrack 1 [NER]")
class Indexing_Evaluation(PharmaconerEvaluation):
"""Class for running the Concept Indexing evaluation (Subtrack 2)."""
def __init__(self, annotator_cas, gold_cas, **kwargs):
self.evaluations = []
self.add_eval(EvaluateSubtrack2(annotator_cas, gold_cas, **kwargs),
label="SubTrack 2 [Indexing]")