-
Notifications
You must be signed in to change notification settings - Fork 220
/
get_wmt18_seg_results.py
175 lines (150 loc) · 5.59 KB
/
get_wmt18_seg_results.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
import argparse
import os
import pickle as pkl
from collections import defaultdict
import numpy as np
import pandas as pd
import torch
from scipy.stats import pearsonr
from tqdm.auto import tqdm, trange
import bert_score
wmt18_sys_to_lang_pairs = [
"cs-en",
"de-en",
"et-en",
"fi-en",
"ru-en",
"tr-en",
"zh-en",
]
wmt18_sys_from_lang_pairs = [
"en-cs",
"en-de",
"en-et",
"en-fi",
"en-ru",
"en-tr",
"en-zh",
]
wmt18_sys_lang_pairs = wmt18_sys_to_lang_pairs + wmt18_sys_from_lang_pairs
import argparse
def get_wmt18_seg_data(lang_pair):
src, tgt = lang_pair.split("-")
RRdata = pd.read_csv(
"wmt18/wmt18-metrics-task-package/manual-evaluation/RR-seglevel.csv", sep=" "
)
# RRdata_lang = RRdata[RRdata['LP'] == lang_pair] # there is a typo in this data. One column name is missing in the header
RRdata_lang = RRdata[RRdata.index == lang_pair]
systems = set(RRdata_lang["BETTER"])
systems.update(list(set(RRdata_lang["WORSE"])))
systems = list(systems)
sentences = {}
for system in systems:
with open(
"wmt18/wmt18-metrics-task-package/input/wmt18-metrics-task-nohybrids/system-outputs/newstest2018/{}/newstest2018.{}.{}".format(
lang_pair, system, lang_pair
)
) as f:
sentences[system] = f.read().split("\n")
with open(
"wmt18/wmt18-metrics-task-package/input/wmt18-metrics-task-nohybrids/"
"references/{}".format("newstest2018-{}{}-ref.{}".format(src, tgt, tgt))
) as f:
references = f.read().split("\n")
ref = []
cand_better = []
cand_worse = []
for index, row in RRdata_lang.iterrows():
cand_better += [sentences[row["BETTER"]][row["SID"] - 1]]
cand_worse += [sentences[row["WORSE"]][row["SID"] - 1]]
ref += [references[row["SID"] - 1]]
return ref, cand_better, cand_worse
def kendell_score(scores_better, scores_worse):
total = len(scores_better)
correct = torch.sum(scores_better > scores_worse).item()
incorrect = total - correct
return (correct - incorrect) / total
def get_wmt18_seg_bert_score(
lang_pair, scorer, cache=False, from_en=True, batch_size=64
):
filename = ""
if from_en:
if scorer.idf:
filename = "cache_score/from_en/18/{}/wmt18_seg_from_{}_{}_idf.pkl".format(
scorer.model_type, *lang_pair.split("-")
)
else:
filename = "cache_score/from_en/18/{}/wmt18_seg_from_{}_{}.pkl".format(
scorer.model_type, *lang_pair.split("-")
)
else:
if scorer.idf:
filename = "cache_score/to_en/18/{}/wmt18_seg_to_{}_{}_idf.pkl".format(
scorer.model_type, *lang_pair.split("-")
)
else:
filename = "cache_score/to_en/18/{}/wmt18_seg_to_{}_{}.pkl".format(
scorer.model_type, *lang_pair.split("-")
)
if os.path.exists(filename):
with open(filename, "rb") as f:
return pkl.load(f)
else:
refs, cand_better, cand_worse = get_wmt18_seg_data(lang_pair)
if scorer.idf:
scorer.compute_idf(refs)
scores_better = list(scorer.score(cand_better, refs, batch_size=batch_size))
scores_worse = list(scorer.score(cand_worse, refs, batch_size=batch_size))
if cache:
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "wb") as f:
pkl.dump((scores_better, scores_worse), f)
return scores_better, scores_worse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--data", default="wmt18", help="path to wmt16 data")
parser.add_argument("-m", "--model", nargs="+", help="models to tune")
parser.add_argument(
"-l", "--log_file", default="wmt18_log.csv", help="log file path"
)
parser.add_argument("--idf", action="store_true")
parser.add_argument("-b", "--batch_size", type=int, default=64)
parser.add_argument(
"--lang_pairs",
nargs="+",
default=wmt18_sys_to_lang_pairs,
help="language pairs used for tuning",
)
args = parser.parse_args()
torch.set_grad_enabled(False)
header = "model_type"
for lang_pair in args.lang_pairs + ["avg"]:
header += f",{lang_pair}"
print(header)
if not os.path.exists(args.log_file):
with open(args.log_file, "w") as f:
print(header, file=f)
print(args.model)
for model_type in args.model:
scorer = bert_score.scorer.BERTScorer(model_type=model_type, idf=args.idf)
results = defaultdict(dict)
for lang_pair in tqdm(args.lang_pairs):
scores_better, scores_worse = get_wmt18_seg_bert_score(
lang_pair, scorer, batch_size=args.batch_size, cache=True, from_en=False
)
for sb, sw, name in zip(scores_better, scores_worse, ["P", "R", "F"]):
results[lang_pair][f"{model_type} {name}"] = kendell_score(sb, sw)
for name in ["P", "R", "F"]:
temp = []
for lang_pair in args.lang_pairs:
temp.append(results[lang_pair][f"{model_type} {name}"])
results["avg"][f"{model_type} {name}"] = np.mean(temp)
msg = f"{model_type} {name} (idf)" if args.idf else f"{model_type} {name}"
for lang_pair in args.lang_pairs + ["avg"]:
msg += f",{results[lang_pair][f'{model_type} {name}']}"
print(msg)
with open(args.log_file, "a") as f:
print(msg, file=f)
del scorer
if __name__ == "__main__":
main()