-
Notifications
You must be signed in to change notification settings - Fork 1
/
NEReval.py
72 lines (54 loc) · 2.32 KB
/
NEReval.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
#!/usr/bin/python
# call from unix shell as
# eval.py goldstandardfile.txt yoursystemoutput.txt
#
import sys
def eval(keys, predictions):
""" Given a stream of goldstandard word, tag pairs and a stream of system pairs. Figure out the the recall, precision and F1 """
goldStandardEntities = findEntities(taggedData(keys)) # get the entities in the gold standard
systemEntities = findEntities(taggedData(predictions)) # and the entities in the system output
numEntities = len(goldStandardEntities) # number of entities there should be
numReturned = len(systemEntities) # number actually tagged by system
numTruePositives = len(set.intersection(goldStandardEntities,systemEntities)) # number of those that were right
precision = float(numTruePositives)/numReturned
recall = float(numTruePositives)/numEntities
f1 = 2 * (precision * recall)/(precision + recall)
print numEntities, " entities in gold standard."
print numReturned, " total entities found."
print numTruePositives, " of which were correct."
print "Precision: ", precision, "Recall: ", recall, "F1-measure: ", f1
def findEntities(data):
""" Find all the IOB delimited entities in the data. Return as a set of (begin, end) tuples. Data is sequence of word, tag pairs. """
entities = set()
entityStart = 0
entityEnd = 0
currentState = "Q0"
count = 0
for word, tag in data:
count = count + 1
if currentState == "Q0":
if tag == 'B':
currentState = "Q1"
entityStart = count
elif currentState == "Q1":
if tag == "B":
entityEnd = count - 1
entities.add((entityStart, entityEnd))
entityStart = count
if tag == "O":
entityEnd = count - 1
entities.add((entityStart, entityEnd))
currentState = "Q0"
if currentState == "Q1":
entities.add((entityStart, entityEnd))
return entities
def taggedData(file):
for line in file:
if line == '\n':
yield(['</s>', 'O'])
else:
yield line.strip().split()
if __name__ == "__main__":
keys = open(sys.argv[1])
predictions = open(sys.argv[2])
eval(keys, predictions)