-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathsts.py
274 lines (217 loc) · 9.28 KB
/
sts.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
from pathlib import Path
from typing import Callable, Dict, List, Union
import torch
from scipy.stats import spearmanr
from sklearn.metrics.pairwise import paired_cosine_distances
from torch import Tensor
from tqdm import tqdm
# each STS dataset have different format, so we need to handle them separately
# each STS dataset have subsets, and they are saved in different files
# this module provides a unified interface to access the datasets
class STSEvaluatorBase:
def __init__(
self,
sentences1: List[str],
sentences2: List[str],
scores: List[float],
):
self.sentences1 = sentences1
self.sentences2 = sentences2
self.scores = scores
assert len(self.sentences1) == len(self.sentences2) == len(self.scores)
def __call__(self, encode: Callable[[List[str]], Tensor]) -> float:
embeddings1 = encode(self.sentences1)
embeddings2 = encode(self.sentences2)
# you can use any similarity function you want ↓
cosine_scores = 1 - paired_cosine_distances(embeddings1, embeddings2)
spearman = float(spearmanr(self.scores, cosine_scores)[0]) * 100
return spearman
class SICKEvaluator(STSEvaluatorBase):
# Title: A SICK cure for the evaluation of compositional distributional semantic models
# URL: https://aclanthology.org/L14-1314/
def __init__(self, sts_dir: Path):
sentences1, sentences2, scores = [], [], []
with (sts_dir / "sick/SICK_test_annotated.txt").open() as f:
_ = next(f)
for line in f:
_, sentence1, sentence2, score, *_ = line.strip().split("\t")
sentences1.append(sentence1)
sentences2.append(sentence2)
scores.append(float(score))
super().__init__(sentences1, sentences2, scores)
class STSBDevEvaluator(STSEvaluatorBase):
def __init__(self, sts_dir: Path):
sentences1, sentences2, scores = [], [], []
with (sts_dir / "stsb/sts-dev.csv").open() as f:
for line in f:
_, _, _, _, score, sentence1, sentence2, *_ = line.strip().split("\t")
sentences1.append(sentence1)
sentences2.append(sentence2)
scores.append(float(score))
super().__init__(sentences1, sentences2, scores)
class STSBEvaluator(STSEvaluatorBase):
# Title: SemEval-2017 Task 1: Semantic Textual Similarity Multilingual and Crosslingual Focused Evaluation
# URL: https://aclanthology.org/S17-2001/
def __init__(self, sts_dir: Path):
sentences1, sentences2, scores = [], [], []
with (sts_dir / "stsb/sts-test.csv").open() as f:
for line in f:
_, _, _, _, score, sentence1, sentence2, *_ = line.strip().split("\t")
sentences1.append(sentence1)
sentences2.append(sentence2)
scores.append(float(score))
super().__init__(sentences1, sentences2, scores)
class STS16Evaluator(STSEvaluatorBase):
# Title: SemEval-2016 Task 1: Semantic Textual Similarity, Monolingual and Cross-Lingual Evaluation
# URL: https://aclanthology.org/S16-1081/
SUBSETS = [
"answer-answer",
"headlines",
"plagiarism",
"postediting",
"question-question",
]
def __init__(self, sts_dir: Path):
sentences1, sentences2, scores = [], [], []
for subset in self.SUBSETS:
with (sts_dir / f"sts16/STS2016.gs.{subset}.txt").open() as gs, (
sts_dir / f"sts16/STS2016.input.{subset}.txt"
).open() as f:
for line_input, line_gs in zip(f, gs):
sentence1, sentence2, *_ = line_input.strip().split("\t")
if line_gs.strip() == "":
continue
sentences1.append(sentence1)
sentences2.append(sentence2)
scores.append(float(line_gs.strip()))
super().__init__(sentences1, sentences2, scores)
class STS15Evaluator(STSEvaluatorBase):
# Title: SemEval-2015 Task 2: Semantic Textual Similarity, English, Spanish and Pilot on Interpretability
# URL: https://aclanthology.org/S15-2045/
SUBSETS = [
"answers-forums",
"answers-students",
"belief",
"headlines",
"images",
]
def __init__(self, sts_dir: Path):
sentences1, sentences2, scores = [], [], []
for subset in self.SUBSETS:
with (sts_dir / f"sts15/STS.gs.{subset}.txt").open() as gs, (
sts_dir / f"sts15/STS.input.{subset}.txt"
).open() as f:
for line_input, line_gs in zip(f, gs):
sentence1, sentence2, *_ = line_input.strip().split("\t")
if line_gs.strip() == "":
continue
sentences1.append(sentence1)
sentences2.append(sentence2)
scores.append(float(line_gs.strip()))
super().__init__(sentences1, sentences2, scores)
class STS14Evaluator(STSEvaluatorBase):
# Title: SemEval-2014 Task 10: Multilingual Semantic Textual Similarity
# URL: https://aclanthology.org/S14-2010/
SUBSETS = [
"deft-forum",
"deft-news",
"headlines",
"images",
"OnWN",
"tweet-news",
]
def __init__(self, sts_dir: Path):
sentences1, sentences2, scores = [], [], []
for subset in self.SUBSETS:
with (sts_dir / f"sts14/STS.gs.{subset}.txt").open() as gs, (
sts_dir / f"sts14/STS.input.{subset}.txt"
).open() as f:
for line_input, line_gs in zip(f, gs):
sentence1, sentence2, *_ = line_input.strip().split("\t")
if line_gs.strip() == "":
continue
sentences1.append(sentence1)
sentences2.append(sentence2)
scores.append(float(line_gs.strip()))
super().__init__(sentences1, sentences2, scores)
class STS13Evaluator(STSEvaluatorBase):
# Title: *SEM 2013 shared task: Semantic Textual Similarity
# URL: https://aclanthology.org/S13-1004/
SUBSETS = ["FNWN", "headlines", "OnWN"]
# STS13 here does not contain the "SMT" subtask due to LICENSE issue
def __init__(self, sts_dir: Path):
sentences1, sentences2, scores = [], [], []
for subset in self.SUBSETS:
with (sts_dir / f"sts13/STS.gs.{subset}.txt").open() as gs, (
sts_dir / f"sts13/STS.input.{subset}.txt"
).open() as f:
for line_input, line_gs, *_ in zip(f, gs):
sentence1, sentence2 = line_input.strip().split("\t")
if line_gs.strip() == "":
continue
sentences1.append(sentence1)
sentences2.append(sentence2)
scores.append(float(line_gs.strip()))
super().__init__(sentences1, sentences2, scores)
class STS12Evaluator(STSEvaluatorBase):
# Title: SemEval-2012 Task 6: A Pilot on Semantic Textual Similarity
# URL: https://aclanthology.org/S12-1051/
SUBSETS = [
"MSRpar",
"MSRvid",
"SMTeuroparl",
"surprise.OnWN",
"surprise.SMTnews",
]
def __init__(self, sts_dir: Path):
sentences1, sentences2, scores = [], [], []
for subset in self.SUBSETS:
with (sts_dir / f"sts12/STS.gs.{subset}.txt").open() as gs, (
sts_dir / f"sts12/STS.input.{subset}.txt"
).open() as f:
for line_input, line_gs in zip(f, gs):
sentence1, sentence2, *_ = line_input.strip().split("\t")
if line_gs.strip() == "":
continue
sentences1.append(sentence1)
sentences2.append(sentence2)
scores.append(float(line_gs.strip()))
super().__init__(sentences1, sentences2, scores)
class STSEvaluation:
def __init__(self, sts_dir: Union[str, Path]):
sts_dir = Path(sts_dir)
self.sts_evaluators = {
"sts12": STS12Evaluator(sts_dir=sts_dir),
"sts13": STS13Evaluator(sts_dir=sts_dir),
"sts14": STS14Evaluator(sts_dir=sts_dir),
"sts15": STS15Evaluator(sts_dir=sts_dir),
"sts16": STS16Evaluator(sts_dir=sts_dir),
"stsb": STSBEvaluator(sts_dir=sts_dir),
"sick": SICKEvaluator(sts_dir=sts_dir),
}
self.dev_evaluator = STSBDevEvaluator(sts_dir=sts_dir)
@torch.inference_mode()
def __call__(
self,
encode: Callable[[List[str]], Tensor],
progress_bar: bool = True,
) -> Dict[str, float]:
results = {}
if progress_bar:
iterator = tqdm(
list(self.sts_evaluators.items()),
dynamic_ncols=True,
leave=False,
)
else:
iterator = list(self.sts_evaluators.items())
for name, evaluator in iterator:
results[name] = evaluator(encode=encode)
results["avg"] = sum(results.values()) / len(results)
return results
@torch.inference_mode()
def dev(
self,
encode: Callable[[List[str]], Tensor],
) -> float:
return self.dev_evaluator(encode=encode)