blob: 0dffc20e1a3a2a27eba37816220b578ed9a61a63 [file] [log] [blame]
dazaff42f632020-10-08 14:46:32 +02001from lib.CoNLL_Annotation import *
2from collections import Counter
3import pandas as pd
4import numpy as np
5from sklearn.metrics import precision_recall_fscore_support as eval_f1
6from tabulate import tabulate
7import logging, argparse, sys
8from datetime import datetime
9
10
11def eval_lemma(sys, gld):
12 match, err, symbol = 0, 0, []
13 mistakes = []
14 for i, gld_tok in enumerate(gld.tokens):
15 if gld_tok.lemma == sys.tokens[i].lemma:
16 match += 1
17 elif not sys.tokens[i].lemma.isalnum(): # This was added because Turku does not lemmatize symbols (it only copies them) => ERR ((',', '--', ','), 43642)
18 symbol.append(sys.tokens[i].lemma)
19 if sys.tokens[i].word == sys.tokens[i].lemma:
20 match += 1
21 else:
22 err += 1
23 else:
24 err += 1
25 mistakes.append((gld_tok.word, gld_tok.lemma, sys.tokens[i].lemma))
26 return match, err, symbol, mistakes
27
28
29def eval_pos(sys, gld):
30 match, mistakes = 0, []
31 y_gld, y_pred = [], []
32 for i, gld_tok in enumerate(gld.tokens):
33 y_gld.append(gld_tok.pos_tag)
34 y_pred.append(sys.tokens[i].pos_tag)
35 all_pos_labels.add(gld_tok.pos_tag)
36 if gld_tok.pos_tag == sys.tokens[i].pos_tag:
37 match += 1
38 else:
39 mistakes.append((gld_tok.word, gld_tok.pos_tag, sys.tokens[i].pos_tag))
40 return y_gld, y_pred, match, mistakes
41
42
43
44if __name__ == "__main__":
45 """
46 EVALUATIONS:
47 python TIGER/evaluate.py -t Turku\
48 --sys_file /home/daza/datasets/TIGER_conll/tiger_turku_parsed.conllu \
49 --gld_file /home/daza/datasets/TIGER_conll/tiger_release_aug07.corrected.16012013.conll09
50
51 python TIGER/evaluate.py -t SpaCy\
52 --sys_file /home/daza/datasets/TIGER_conll/tiger_spacy_parsed.conllu \
53 --gld_file /home/daza/datasets/TIGER_conll/tiger_release_aug07.corrected.16012013.conll09
54
55 python TIGER/evaluate.py -t RNNTagger\
56 --sys_file /home/daza/datasets/TIGER_conll/tiger_all.parsed.RNNTagger.conll \
57 --gld_file /home/daza/datasets/TIGER_conll/tiger_release_aug07.corrected.16012013.conll09
58
59 python TIGER/evaluate.py -t TreeTagger\
60 --sys_file /home/daza/datasets/TIGER_conll/tiger_all.parsed.TreeTagger.conll \
61 --gld_file /home/daza/datasets/TIGER_conll/tiger_release_aug07.corrected.16012013.conll09
62 """
63
64 # =====================================================================================
65 # INPUT PARAMS
66 # =====================================================================================
67 parser = argparse.ArgumentParser()
68 parser.add_argument("-s", "--sys_file", help="System output in CoNLL-U Format", required=True)
69 parser.add_argument("-g", "--gld_file", help="Gold Labels to evaluate in CoNLL-U Format", required=True)
70 parser.add_argument("-t", "--type_sys", help="Which system produced the outputs", default="system")
71 args = parser.parse_args()
72
73 # =====================================================================================
74 # LOGGING INFO ...
75 # =====================================================================================
76 logger = logging.getLogger(__name__)
77 console_hdlr = logging.StreamHandler(sys.stdout)
78 file_hdlr = logging.FileHandler(filename=f"logs/Eval_Tiger.{args.type_sys}.log")
79 logging.basicConfig(level=logging.INFO, handlers=[console_hdlr, file_hdlr])
80 now_is = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
81 logger.info(f"\n\nEvaluating TIGER Corpus {now_is}")
82
83 # Read the Original TiGeR Annotations
84 gld_generator = read_conll_generator(args.gld_file, token_class=CoNLL09_Token)
85 # Read the Annotations Generated by the Automatic Parser [Turku, SpaCy, RNNTagger]
86 if args.type_sys == "RNNTagger":
87 sys_generator = read_conll_generator(args.sys_file, token_class=RNNTagger_Token)
88 elif args.type_sys == "TreeTagger":
89 sys_generator = read_conll_generator(args.sys_file, token_class=RNNTagger_Token, sent_sep="</S>")
90 else:
91 sys_generator = read_conll_generator(args.sys_file, token_class=CoNLLUP_Token)
92
93 lemma_all_match, lemma_all_err, lemma_all_mistakes = 0, 0, []
94 lemma_all_symbols = []
95 pos_all_match, pos_all_err, pos_all_mistakes = 0, 0, []
96 pos_all_pred, pos_all_gld = [], []
97 all_pos_labels = set()
98
99 for i, (s,g) in enumerate(zip(sys_generator, gld_generator)):
100 # print([x.word for x in s.tokens])
101 # print([x.word for x in g.tokens])
102 assert len(s.tokens) == len(g.tokens), f"Token Mismatch! S={len(s.tokens)} G={len(g.tokens)} IX={i+1}"
103 # Lemmas ...
104 lemma_match, lemma_err, lemma_sym, mistakes = eval_lemma(s,g)
105 lemma_all_match += lemma_match
106 lemma_all_err += lemma_err
107 lemma_all_mistakes += mistakes
108 lemma_all_symbols += lemma_sym
109 # POS Tags ...
110 pos_gld, pos_pred, pos_match, pos_mistakes = eval_pos(s, g)
111 pos_all_pred += pos_pred
112 pos_all_gld += pos_gld
113 pos_all_match += pos_match
114 pos_all_err += len(pos_mistakes)
115 pos_all_mistakes += pos_mistakes
116
117 # Lemmas ...
118 logger.info(f"Lemma Matches = {lemma_all_match} || Errors = {lemma_all_err} || Symbol Chars = {len(lemma_all_symbols)}")
119 logger.info(f"Lemma Accuracy = {(lemma_all_match*100/(lemma_all_match + lemma_all_err)):.2f}%\n")
120 lemma_miss_df = pd.DataFrame(lemma_all_mistakes, columns =['Gold_Word', 'Gold_Lemma', 'Sys_Lemma']).value_counts()
121 lemma_miss_df.to_csv(path_or_buf=f"outputs/LemmaErrors.{args.type_sys}.tsv", sep="\t")
122
123 # POS Tags ...
124 logger.info(f"POS Matches = {pos_all_match} || Errors = {pos_all_err}")
125 logger.info(f"POS Tagging Accuracy = {(pos_all_match*100/(pos_all_match + pos_all_err)):.2f}%\n")
126 pos_miss_df = pd.DataFrame(pos_all_mistakes, columns =['Gold_Word', 'Gold_POS', 'Sys_POS']).value_counts()
127 pos_miss_df.to_csv(path_or_buf=f"outputs/POS-Errors.{args.type_sys}.tsv", sep="\t")
128
129 ordered_labels = sorted(all_pos_labels)
130 p_labels, r_labels, f_labels, support = eval_f1(y_true=pos_all_gld, y_pred=pos_all_pred, labels=ordered_labels , average=None)
131 scores_per_label = zip(ordered_labels, [x*100 for x in p_labels], [x*100 for x in r_labels], [x*100 for x in f_labels])
132 logger.info("\n\n")
133 logger.info(tabulate(scores_per_label, headers=["POS Tag","Precision", "Recall", "F1"], floatfmt=".2f"))
134 p_labels, r_labels, f_labels, support = eval_f1(y_true=np.array(pos_all_gld), y_pred=np.array(pos_all_pred), average='micro', zero_division=0)
135 logger.info(f"Total Prec = {p_labels*100}\tRec = {r_labels*100}\tF1 = {f_labels*100}")
136
137