forked from wcmac/sippycup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
experiment.py
334 lines (313 loc) · 13.2 KB
/
experiment.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
__author__ = "Bill MacCartney"
__copyright__ = "Copyright 2015, Bill MacCartney"
__credits__ = []
__license__ = "GNU General Public License, version 2.0"
__version__ = "0.9"
__maintainer__ = "Bill MacCartney"
__email__ = "See the author's website"
from collections import defaultdict
import random
from metrics import SemanticsAccuracyMetric, NumParsesMetric, standard_metrics
from example import Example
from learning import latent_sgd
from parsing import is_cat, parse_to_pretty_string, print_grammar
from scoring import Model, rule_features
# TODO: comment
def print_sample_outcomes(model=None,
examples=[],
name=None,
metric=None,
metric_test=None,
k=10):
candidates = []
for example in examples:
parses = model.parse_input(example.input)
metric_value = metric.evaluate(example, parses)
if metric_test(metric_value):
candidates.append(example)
k = min(k, len(candidates))
samples = random.sample(candidates, k)
print('%d of %d %s on %s:\n' % (k, len(candidates), name, metric.name()))
inputs = [example.input for example in samples]
for input in sorted(inputs):
print(' ', input)
print()
return samples
# TODO: comment
def sample_wins_and_losses(domain=None,
model=None,
metric=None,
seed=None):
if seed:
random.seed(seed)
metric = metric or domain.training_metric()
model = model or domain.model()
train_examples=domain.train_examples()
evaluate_model(model=model,
examples=train_examples,
metrics=domain.metrics(),
print_examples=False)
def my_print_sample_outcomes(name=None, metric_test=None, k=10):
examples = print_sample_outcomes(model=model,
examples=train_examples,
name=name,
metric=metric,
metric_test=metric_test,
k=k)
my_print_sample_outcomes(name='wins', metric_test=(lambda n: n > 0), k=5)
my_print_sample_outcomes(name='losses', metric_test=(lambda n: n == 0), k=10)
# TODO: comment
def print_parses(example,
parses,
metrics=[NumParsesMetric()],
max_parses=10000,
show_syntax=False):
print('%-34s %s' % ('input', example.input))
if example.semantics != None:
print('%-34s %s' % ('target semantics', str(example.semantics)))
if example.denotation != None:
print('%-34s %s' % ('target denotation', str(example.denotation)))
print()
for metric in metrics:
metric_value = metric.evaluate(example, parses)
print('%-34s %.3g' % (metric.name(), metric_value))
print()
for idx, parse in enumerate(parses[:max_parses]):
def outcome_marker(target, prediction):
return ('+' if prediction == target else '-') if target != None else ' '
parse_outcome = outcome_marker(example.parse, parse)
semantics_outcome = outcome_marker(example.semantics, parse.semantics)
if example.denotation != None:
denotation_outcome = outcome_marker(example.denotation, parse.denotation)
else:
denotation_outcome = ' '
lines = []
if show_syntax:
lines.append('%-15s %s \n%s' % ('parse', parse_outcome, parse_to_pretty_string(parse)))
lines.append('%-15s %s %s' % ('semantics', semantics_outcome, parse.semantics))
if example.denotation != None or parse.denotation != None:
lines.append('%-15s %s %s' % ('denotation', denotation_outcome, parse.denotation))
for l, line in enumerate(lines):
if l == 0:
print('%-3s %8.3f %s' % (idx, parse.score, line))
else:
print('%-3s %8s %s' % ('', '', line))
if len(parses) > max_parses:
print('(additional parses truncated)')
print('\n' + '-' * 80)
# TODO: comment
def evaluate_model(model=None,
examples=[],
examples_label=None,
metrics=standard_metrics(),
print_examples=True):
print('=' * 80)
print('Evaluating on %d %sexamples\n' % (
len(examples), examples_label + ' ' if examples_label else ''))
print('-' * 80)
metric_values = defaultdict(int)
for example in examples:
parses = model.parse_input(example.input)
for metric in metrics:
metric_value = metric.evaluate(example, parses)
metric_values[metric.name()] += metric_value
if print_examples:
print_parses(example, parses, metrics=metrics)
print('Over %d examples:' % len(examples))
print()
for metric in metrics:
print('%-34s %.3f' % (metric.name(), 1.0 * metric_values[metric.name()] / len(examples)))
print()
# TODO: comment
def evaluate_grammar(grammar=None,
executor=None,
examples=[],
examples_label=None,
metrics=standard_metrics(),
print_examples=True):
evaluate_model(model=Model(grammar=grammar, executor=executor),
examples=examples,
metrics=metrics,
print_examples=print_examples)
def test_executor(domain):
print('=' * 80)
print('Test Executor\n')
for example in domain.examples():
print('%-24s %s' % ('semantics', example.semantics))
print('%-24s %s' % ('target denotation', example.denotation))
actual_denotation = domain.execute(example.semantics)
match = (actual_denotation == example.denotation)
print('%-24s %s' % ('actual denotation', '[match]' if match else actual_denotation))
print()
def evaluate_for_domain(domain, print_examples=True):
print('#' * 80)
print('Standard evaluation for domain: %s\n' % domain.__class__.__name__)
# grammar = domain.grammar()
# print_grammar(grammar)
# print
model = domain.model()
evaluate_model(model=model,
examples=domain.train_examples(),
examples_label='train',
metrics=domain.metrics(),
print_examples=print_examples)
evaluate_model(model=model,
examples=domain.test_examples(),
examples_label='test',
metrics=domain.metrics(),
print_examples=print_examples)
def evaluate_dev_examples_for_domain(domain):
evaluate_model(model=domain.model(),
examples=domain.dev_examples(),
examples_label='dev',
metrics=domain.metrics(),
print_examples=True)
def train_test(model=None,
train_examples=[],
test_examples=[],
metrics=standard_metrics(),
training_metric=SemanticsAccuracyMetric(),
seed=None,
print_examples=False):
# print_grammar(model.grammar)
# print
print('%d training examples, %d test examples' % (len(train_examples), len(test_examples)))
# 'Before' test
model.weights = defaultdict(float) # no weights
evaluate_model(model=model,
examples=train_examples,
examples_label='train',
metrics=metrics,
print_examples=print_examples)
evaluate_model(model=model,
examples=test_examples,
examples_label='test',
metrics=metrics,
print_examples=print_examples)
# Train
model = latent_sgd(model, train_examples, training_metric=training_metric, seed=seed)
# 'After' test
evaluate_model(model=model,
examples=train_examples,
examples_label='train',
metrics=metrics,
print_examples=print_examples)
evaluate_model(model=model,
examples=test_examples,
examples_label='test',
metrics=metrics,
print_examples=print_examples)
def train_test_for_domain(domain, seed=None, print_examples=False):
print('#' * 80)
print('Train/test experiment for domain: %s\n' % domain.__class__.__name__)
train_test(model=domain.model(),
train_examples=domain.train_examples(),
test_examples=domain.test_examples(),
metrics=domain.metrics(),
training_metric=domain.training_metric(),
seed=seed,
print_examples=print_examples)
def cartesian_product_of_lexical_rules(rules, restrict_by_lhs=True):
"""
Expands the given collection of rules by iterating through all possible
pairs of existing lexical rules and adding a new rule which combines the RHS
of the first rule with the semantics of the second. If restrict_by_lhs is
true, we only consider pairs which have the same LHS, which helps to avoid
constructing malformed semantics.
"""
from itertools import product
from parsing import Rule, is_lexical
lexical_rules = [rule for rule in rules if is_lexical(rule)]
expanded_rules = [rule for rule in rules if not is_lexical(rule)]
# Partition rules by lhs.
lexical_rules_by_lhs = defaultdict(list)
for rule in lexical_rules:
lhs = rule.lhs if restrict_by_lhs else 'dummy'
lexical_rules_by_lhs[lhs].append(rule)
# In each partition, iterate through Cartesian product of lexical rules.
for lhs, rules in list(lexical_rules_by_lhs.items()):
sems = set([rule.sem for rule in rules])
for rule, sem in product(rules, sems):
expanded_rules.append(Rule(rule.lhs, rule.rhs, sem))
return expanded_rules
def learn_lexical_semantics(domain, seed=None):
from parsing import Grammar
print('#' * 80)
print('Learn lexical semantics experiment for domain: %s\n' % domain.__class__.__name__)
original_grammar = domain.grammar()
expanded_rules = cartesian_product_of_lexical_rules(domain.rules())
grammar = Grammar(rules=expanded_rules,
annotators=original_grammar.annotators,
start_symbol=original_grammar.start_symbol)
model = Model(grammar=grammar,
feature_fn=domain.features,
weights=domain.weights,
executor=domain.execute)
train_test(model=model,
train_examples=domain.train_examples(),
test_examples=domain.test_examples(),
metrics=domain.metrics(),
training_metric=domain.training_metric(),
seed=seed,
print_examples=False)
def interact(domain, example_input=None, T=10):
import readline
model = domain.model()
model = latent_sgd(model=model,
examples=domain.train_examples(),
training_metric=domain.training_metric(),
T=T)
print('\nHello! Enter a query%s:' % (', such as "%s"' % example_input if example_input else ''))
while True:
try:
query = input('>>> ')
except EOFError:
print('\nBye!')
return
example = Example(input=query)
parses = model.parse_input(query)
if parses:
print_parses(example, parses)
else:
print('No parse!')
def generate(rules, start_symbol='$ROOT', n=100, min_tokens=3, max_tokens=10):
rules_by_lhs = defaultdict(list)
for rule in rules:
rules_by_lhs[rule.lhs].append(rule)
def sample_phrase(label):
if label.startswith('?'):
label = label[1:]
if not is_cat(label):
return label
if label not in rules_by_lhs:
return label
rule = random.choice(rules_by_lhs[label])
phrases = [sample_phrase(label) for label in rule.rhs]
return ' '.join(phrases)
inputs = set()
while len(inputs) < n:
input = sample_phrase(start_symbol)
print(input)
num_tokens = len(input.split())
if num_tokens >= min_tokens and num_tokens <= max_tokens:
inputs.add(input)
print('-' * 80)
for input in inputs:
print(input)
def find_best_rules(domain):
model = domain.model()
examples = domain.train_examples()
metric = domain.training_metric()
rule_counts = defaultdict(int)
for example in examples:
parses = model.parse_input(example.input)
good_parses = [p for p in parses if metric.evaluate(example, [p])]
if good_parses:
best_parse = good_parses[0]
features = rule_features(best_parse)
for rule, count in list(features.items()):
rule_counts[rule] = rule_counts[rule] + count
counts = [(count, rule) for rule, count in list(rule_counts.items())]
counts = sorted(counts, reverse=True)
for count, rule in counts:
print('%d\t%s' % (count, rule))