-
Notifications
You must be signed in to change notification settings - Fork 0
/
hypothesis_testing.py
314 lines (273 loc) · 11.9 KB
/
hypothesis_testing.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
#!/usr/bin/env python
# Statistical Hypothesis Testing: Bootstrap Resampling
# Author: Morteza Mirbostani
# Github: https://github.com/mirbostani
from collections import Counter
from tqdm import tqdm
import string
import re
import argparse
import json
import sys
import random
import math
import time
import statistics as stats
import numpy as np
import matplotlib.pyplot as plt
class StatsHypothesisTest():
def __init__(self,
dataset,
baseline_predictions,
experimental_predictions,
test_repetition: int,
sample_size: int,
significance_level: float,
resampling_repetition: int,
display_not_found: bool = False):
self.dataset = dataset
self.baseline_predictions = baseline_predictions
self.experimental_predictions = experimental_predictions
self.test_repetition = test_repetition
self.k = sample_size
self.alpha = significance_level
self.B = resampling_repetition
self.display_not_found = display_not_found
pval = 0
for i in tqdm(range(self.test_repetition)):
(self.baseline_scores,
self.experimental_scores) = self.generate_scores(
dataset=self.dataset,
k=self.k,
baseline_predictions=self.baseline_predictions,
experimental_predictions=self.experimental_predictions,
display_not_found=self.display_not_found)
(self.sample,
self.means,
self.p_value,
self.n_score) = self.bootstrap_resampling(
baseline_scores=self.baseline_scores,
experimental_scores=self.experimental_scores,
B=self.B)
pval += self.p_value
self.avg_p_value = pval / self.test_repetition
def results(self):
return {
"resampling_repetition": self.B,
"significance_level": self.alpha,
"last_baseline_size": len(self.baseline_scores),
"last_baseline_score_1": sum(self.baseline_scores),
"last_baseline_score_0": len(self.baseline_scores) - sum(self.baseline_scores),
"last_baseline_exact_match": 100 * sum(self.baseline_scores) / len(self.baseline_scores),
"last_experimental_size": len(self.experimental_scores),
"last_experimental_score_1": sum(self.experimental_scores),
"last_experimental_score_0": len(self.experimental_scores) - sum(self.experimental_scores),
"last_experimental_exact_match": 100 * sum(self.experimental_scores) / len(self.baseline_scores),
"last_sample_size": len(self.sample),
"last_sample_score_1": sum([1 for i, v in enumerate(self.sample) if v == 1]),
"last_sample_score_0": sum([1 for i, v in enumerate(self.sample) if v == 0]),
"last_sample_score_-1": sum([1 for i, v in enumerate(self.sample) if v == -1]),
"last_means_size": len(self.means),
"last_n_score": self.n_score, # wrong answers of total B questions
"last_p_value": self.p_value,
"last_null_hypothesis_rejected": self.p_value < self.alpha,
"average_p_value": self.avg_p_value,
"null_hypothesis_rejected": self.avg_p_value < self.alpha,
}
def generate_scores(self,
dataset,
k, # sample size
baseline_predictions,
experimental_predictions,
display_not_found: bool = False):
baseline_scores = []
experimental_scores = []
question_ids = []
# Randomly select `sample_size` samples from dataset
for article in dataset:
for paragraph in article["paragraphs"]:
for qa in paragraph["qas"]:
question_ids.append(qa["id"])
if k in [-1, None]:
k = len(question_ids)
if k < len(question_ids):
random.seed(time.time())
sample_question_ids = random.sample(question_ids, k=k)
else:
sample_question_ids = question_ids
# Geenrate scores
for article in dataset:
for paragraph in article["paragraphs"]:
for qa in paragraph["qas"]:
# ignore not selected questions
if qa["id"] not in sample_question_ids:
continue
# correct answers
ground_truths = list(
map(lambda x: x["text"], qa["answers"]))
# baseline score
if qa["id"] in baseline_predictions:
baseline_prediction = baseline_predictions[qa["id"]]
exact_match = self.metric_max_over_ground_truths(
metric_fn=self.exact_match_score,
prediction=baseline_prediction,
ground_truths=ground_truths)
baseline_scores.append(1 if exact_match else 0)
else:
if display_not_found:
print("Baseline prediction not found for id '{}'".format(
qa["id"]), file=sys.stderr)
baseline_scores.append(0)
# experimental score
if qa["id"] in experimental_predictions:
experimental_prediction = experimental_predictions[qa["id"]]
exact_match = self.metric_max_over_ground_truths(
metric_fn=self.exact_match_score,
prediction=experimental_prediction,
ground_truths=ground_truths)
experimental_scores.append(1 if exact_match else 0)
else:
if display_not_found:
print("Experimental prediction not found for id '{}'".format(qa["id"]),
file=sys.stderr)
experimental_scores.append(0)
return (baseline_scores, experimental_scores)
def bootstrap_resampling(self,
baseline_scores,
experimental_scores,
B):
baseline_scores_np = np.array(baseline_scores)
experimental_scores_np = np.array(experimental_scores)
if baseline_scores_np.size != experimental_scores_np.size:
print("Sizes are not equal!", file=sys.stderr)
return (None, None, None)
# Compute sample based on score difference
sample = experimental_scores_np - baseline_scores_np
# Resample `B` times and compute the statistic (i.e., mean)
means = [np.random.choice(sample, size=sample.size).mean()
for _ in range(B)]
# Compute p-value
n_score = 0
for i in range(B):
if (means[i] <= 0):
n_score += 1
p_value = n_score / B
return (sample.tolist(), means, p_value, n_score)
def normalize_answer(self, s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(text):
return re.sub(r'\b(a|an|the)\b', ' ', text)
def white_space_fix(text):
return ' '.join(text.split())
def remove_punc(text):
exclude = set(string.punctuation)
return ''.join(ch for ch in text if ch not in exclude)
def lower(text):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(s))))
# not used
def f1_score(self, prediction, ground_truth):
prediction_tokens = self.normalize_answer(prediction).split()
ground_truth_tokens = self.normalize_answer(ground_truth).split()
common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
num_same = sum(common.values())
if num_same == 0:
return 0
precision = 1.0 * num_same / len(prediction_tokens)
recall = 1.0 * num_same / len(ground_truth_tokens)
f1 = (2 * precision * recall) / (precision + recall)
return f1
def exact_match_score(self,
prediction,
ground_truth):
return (self.normalize_answer(prediction) ==
self.normalize_answer(ground_truth))
def metric_max_over_ground_truths(self,
metric_fn,
prediction,
ground_truths):
scores_for_ground_truths = []
for ground_truth in ground_truths:
score = metric_fn(prediction, ground_truth)
scores_for_ground_truths.append(score)
return max(scores_for_ground_truths)
def main():
expected_version = "1.1"
parser = argparse.ArgumentParser(
description="Statistical Hypothesis Testing for QA models on SQuAD \
v{} dataset".format(expected_version))
parser.add_argument(
"-d",
"--dataset_file",
type=str,
required=True,
help="SQuAD v{} dataset file, e.g., dev-v{}.json".format(
expected_version, expected_version))
parser.add_argument(
"-b",
"--baseline_prediction_file",
type=str,
required=True,
help="Baseline model's prediction file on the input dataset")
parser.add_argument(
"-e",
"--experimental_prediction_file",
type=str,
required=True,
help="Experimental model's prediction file on the input dataset")
parser.add_argument(
"-z",
"--sample_size",
type=int,
default=-1,
help="If sample size (k) is less than the size of the input dataset, \
k number of samples will be chosen randomly among dataset examples.")
parser.add_argument(
"-t",
"--test_repetition",
type=int,
default=1,
help="Hypothesis testing repetition")
parser.add_argument(
"-a",
"--significance_level",
type=float,
default=0.05, # 5%
help="Hypothesis testing significance level (alpha)")
parser.add_argument(
"-r",
"--resampling_repetition",
type=int,
default=10000,
help="Bootstrap resampling repetition")
parser.add_argument(
"-n",
"--display_not_found",
action="store_true",
default=False,
help="Display question Ids that have no prediction")
args = parser.parse_args()
with open(args.dataset_file) as dataset_file:
dataset_json = json.load(dataset_file)
if (dataset_json["version"] != expected_version):
print("Expected dataset file version is v{}, but got v{}"
.format(expected_version, dataset_json["version"]),
file=sys.stderr)
dataset = dataset_json["data"]
with open(args.baseline_prediction_file) as baseline_prediction_file:
baseline_predictions = json.load(baseline_prediction_file)
with open(args.experimental_prediction_file) as experimental_prediction_file:
experimental_predictions = json.load(experimental_prediction_file)
test = StatsHypothesisTest(dataset=dataset,
baseline_predictions=baseline_predictions,
experimental_predictions=experimental_predictions,
test_repetition=args.test_repetition,
sample_size=args.sample_size,
significance_level=args.significance_level,
resampling_repetition=args.resampling_repetition,
display_not_found=args.display_not_found)
print(json.dumps(test.results(), indent=4))
# plt.hist(test.means)
# plt.show()
if __name__ == '__main__':
main()