-
Notifications
You must be signed in to change notification settings - Fork 3
/
util.py
262 lines (221 loc) · 8.01 KB
/
util.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
import numpy as np
from dataclasses import dataclass
from typing import Union, List
import functools
import scipy.stats as stats
def build_prefix_tree(items):
elems = {}
for (item, item_prob) in items:
try:
prefix = item[0]
except IndexError:
prefix = None
try:
elem = elems[prefix]
except KeyError:
elem = []
elems[prefix] = elem
elem.append((item[1:], item_prob))
all_probs = sum(x[1] for x in items)
tree = {}
for (k, v) in elems.items():
suffixes, probs = zip(*v)
sp = sum(probs) / all_probs
if k is None:
tree[k] = (None, sp)
else:
tree[k] = (build_prefix_tree(v), sp)
return tree
@dataclass
class Terminal:
text: str
@dataclass
class Nonterminal:
lhs: str
rhs: List[Union[str, Terminal]]
prob: float
class Pcfg:
def __init__(self, nonterminals, start_key, separator):
self.nonterminals = {}
self.start_key = start_key
self.separator = separator
for nt in nonterminals:
if nt.lhs not in self.nonterminals:
self.nonterminals[nt.lhs] = []
self.nonterminals[nt.lhs].append(nt)
assert self.start_key in self.nonterminals
for (k, vs) in self.nonterminals.items():
assert np.allclose(sum(x.prob for x in vs), 1)
for v in vs:
for r in v.rhs:
if isinstance(r, str):
assert r in self.nonterminals
else:
assert isinstance(r, Terminal)
def pretty_print(self):
res = []
printed = set()
to_print = set([self.start_key])
q = [self.nonterminals[self.start_key]]
while q:
nts = q.pop(0)
printed.add(nts[0].lhs)
res.append('{} -> {}'.format(
nts[0].lhs,
' | '.join(
'{} [{}]'.format(
' '.join(
r if isinstance(r, str) else '"{}"'.format(r.text)
for r in v.rhs
),
v.prob,
)
for v in nts)))
for v in nts:
for r in v.rhs:
if isinstance(r, str):
nnt = self.nonterminals[r]
if nnt[0].lhs not in (printed | to_print):
q.append(nnt)
to_print.add(nnt[0].lhs)
return '\n'.join(res)
@functools.lru_cache()
def enumerate_with_probability(self, start_key=None):
if start_key is None:
start_key = self.start_key
nts = self.nonterminals[start_key]
res = []
for nt in nts:
strings = []
for x in nt.rhs:
if isinstance(x, str):
sub_strings = self.enumerate_with_probability(x)
else:
sub_strings = [([x.text], 0.0)]
if len(strings) == 0:
new_strings = sub_strings
else:
new_strings = []
for (s1, p1) in strings:
for (s2, p2) in sub_strings:
new_strings.append((s1 + s2, p1 + p2))
strings[:] = new_strings
strings = [(s, p + np.log(nt.prob)) for (s, p) in strings]
res.extend(strings)
return res
def sample(self, n, start_key=None, seed=None, rand=None):
assert seed is None or rand is None
if seed is not None:
rand = np.random.RandomState(seed)
if rand is None:
rand = np.random.RandomState()
if start_key is None:
start_key = self.start_key
res = []
for i in range(n):
nts = self.nonterminals[start_key]
prod = rand.choice(nts, p=[x.prob for x in nts])
m_res = []
for x in prod.rhs:
if isinstance(x, str):
m_res.extend(self.sample(1, start_key=x, rand=rand))
else:
m_res.append(x.text)
res.append(self.separator.join(m_res))
return res
# use normal distribution for numbers
class NormalPcfg(Pcfg):
def __init__(self, nonterminals, start_key, separator):
self.nonterminals = {}
self.start_key = start_key
self.separator = separator
for nt in nonterminals:
if nt.lhs not in self.nonterminals:
self.nonterminals[nt.lhs] = []
self.nonterminals[nt.lhs].append(nt)
assert self.start_key in self.nonterminals
for (k, vs) in self.nonterminals.items():
# assert np.allclose(sum(x.prob for x in vs), 1)
for v in vs:
for r in v.rhs:
if isinstance(r, str):
assert r in self.nonterminals
else:
assert isinstance(r, Terminal)
def sample(self, n, start_key=None, seed=None, rand=None):
assert seed is None or rand is None
if seed is not None:
rand = np.random.RandomState(seed)
if rand is None:
rand = np.random.RandomState()
elements = np.linspace(0.00, .99, 100)
sigma = np.std(elements)
mu = .50
res = []
for i in range(n):
probs = stats.norm.pdf(elements, loc=mu, scale=sigma)
ch = np.random.choice(elements, p=probs / probs.sum())
ch = round(ch, 2)
res.append(str(ch))
return res
@functools.lru_cache()
def enumerate_with_probability(self):
elements = np.linspace(0.00, .99, 100)
sigma = np.std(elements)
mu = .50
probs = stats.norm.pdf(elements, loc=mu, scale=sigma)
probs = probs / probs.sum()
res = []
for i in range(len(elements)):
res.append(([str(round(elements[i], 2))], np.log(probs[i])))
return res
catdog_pcfg = Pcfg([
Nonterminal('S', ['NP', 'VP'], 1.0),
Nonterminal('NP', ['Det', 'N'], 0.6),
Nonterminal('NP', ['N'], 0.4),
Nonterminal('VP', ['V', 'NP'], 0.8),
Nonterminal('VP', ['V'], 0.2),
Nonterminal('Det', [Terminal('the')], 0.7),
Nonterminal('Det', [Terminal('a')], 0.3),
Nonterminal('N', [Terminal('cat')], 0.4),
Nonterminal('N', [Terminal('dog')], 0.3),
Nonterminal('N', [Terminal('mouse')], 0.2),
Nonterminal('N', [Terminal('book')], 0.1),
Nonterminal('V', [Terminal('liked')], 0.5),
Nonterminal('V', [Terminal('ate')], 0.3),
Nonterminal('V', [Terminal('read')], 0.2),
], 'S', ' ')
number_pcfg = Pcfg([
Nonterminal('S', [Terminal('0.'), 'N', 'N'], 1.0),
Nonterminal('N', [Terminal('0')], 0.1),
Nonterminal('N', [Terminal('1')], 0.1),
Nonterminal('N', [Terminal('2')], 0.1),
Nonterminal('N', [Terminal('3')], 0.1),
Nonterminal('N', [Terminal('4')], 0.1),
Nonterminal('N', [Terminal('5')], 0.1),
Nonterminal('N', [Terminal('6')], 0.1),
Nonterminal('N', [Terminal('7')], 0.1),
Nonterminal('N', [Terminal('8')], 0.1),
Nonterminal('N', [Terminal('9')], 0.1)
], 'S', '')
number_normal_pcfg = NormalPcfg([
Nonterminal('S', [Terminal('0.'), 'N', 'N'], 1.0),
Nonterminal('N', [Terminal('0')], 0.0001),
Nonterminal('N', [Terminal('1')], 0.0015),
Nonterminal('N', [Terminal('2')], 0.0235),
Nonterminal('N', [Terminal('3')], 0.135),
Nonterminal('N', [Terminal('4')], 0.34),
Nonterminal('N', [Terminal('5')], 0.34),
Nonterminal('N', [Terminal('6')], 0.135),
Nonterminal('N', [Terminal('7')], 0.0235),
Nonterminal('N', [Terminal('8')], 0.0015),
Nonterminal('N', [Terminal('9')], 0.0001),
], 'S', '')
bits_uniform_pcfg = Pcfg([
Nonterminal('S', [Terminal('0')], 0.5),
Nonterminal('S', [Terminal('1')], 0.5),
], 'S', '')
bits_nonuniform_pcfg = Pcfg([
Nonterminal('S', [Terminal('0')], 0.75),
Nonterminal('S', [Terminal('1')], 0.25),
], 'S', '')