stochastic.py
4.88 KB
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
"""
Constructs for annotating base graphs.
"""
from __future__ import print_function
from __future__ import division
from builtins import range
from past.utils import old_div
import sys
import numpy as np
from .base import scope, as_apply, dfs, rec_eval, clone
################################################################################
################################################################################
def ERR(msg):
print(msg, file=sys.stderr)
implicit_stochastic_symbols = set()
def implicit_stochastic(f):
implicit_stochastic_symbols.add(f.__name__)
return f
@scope.define
def rng_from_seed(seed):
return np.random.RandomState(seed)
# -- UNIFORM
@implicit_stochastic
@scope.define
def uniform(low, high, rng=None, size=()):
return rng.uniform(low, high, size=size)
@implicit_stochastic
@scope.define
def loguniform(low, high, rng=None, size=()):
draw = rng.uniform(low, high, size=size)
return np.exp(draw)
@implicit_stochastic
@scope.define
def quniform(low, high, q, rng=None, size=()):
draw = rng.uniform(low, high, size=size)
return np.round(old_div(draw, q)) * q
@implicit_stochastic
@scope.define
def qloguniform(low, high, q, rng=None, size=()):
draw = np.exp(rng.uniform(low, high, size=size))
return np.round(old_div(draw, q)) * q
# -- NORMAL
@implicit_stochastic
@scope.define
def normal(mu, sigma, rng=None, size=()):
return rng.normal(mu, sigma, size=size)
@implicit_stochastic
@scope.define
def qnormal(mu, sigma, q, rng=None, size=()):
draw = rng.normal(mu, sigma, size=size)
return np.round(old_div(draw, q)) * q
@implicit_stochastic
@scope.define
def lognormal(mu, sigma, rng=None, size=()):
draw = rng.normal(mu, sigma, size=size)
return np.exp(draw)
@implicit_stochastic
@scope.define
def qlognormal(mu, sigma, q, rng=None, size=()):
draw = np.exp(rng.normal(mu, sigma, size=size))
return np.round(old_div(draw, q)) * q
# -- CATEGORICAL
@implicit_stochastic
@scope.define
def randint(low, high=None, rng=None, size=()):
"""
See np.random.randint documentation.
rng = random number generator, typically equals np.random.mtrand.RandomState
"""
return rng.randint(low, high, size)
@implicit_stochastic
@scope.define
def randint_via_categorical(p, rng=None, size=()):
"""
Only used in tpe because of the chaotic API based on names.
# ideally we would just use randint above, but to use priors this is a wrapper of
categorical
rng = random number generator, typically equals np.random.mtrand.RandomState
"""
return scope.categorical(p, rng, size)
@implicit_stochastic
@scope.define
def categorical(p, rng=None, size=()):
"""Draws i with probability p[i]"""
if len(p) == 1 and isinstance(p[0], np.ndarray):
p = p[0]
p = np.asarray(p)
if size == ():
size = (1,)
elif isinstance(size, (int, np.number)):
size = (size,)
else:
size = tuple(size)
if size == (0,):
return np.asarray([])
assert len(size)
if p.ndim == 0:
raise NotImplementedError()
elif p.ndim == 1:
n_draws = int(np.prod(size))
sample = rng.multinomial(n=1, pvals=p, size=int(n_draws))
assert sample.shape == size + (len(p),)
rval = np.dot(sample, np.arange(len(p)))
rval.shape = size
return rval
elif p.ndim == 2:
n_draws_, n_choices = p.shape
(n_draws,) = size
assert n_draws == n_draws_
rval = [
np.where(rng.multinomial(pvals=p[ii], n=1))[0][0] for ii in range(n_draws)
]
rval = np.asarray(rval)
rval.shape = size
return rval
else:
raise NotImplementedError()
def choice(args):
return scope.one_of(*args)
scope.choice = choice
def one_of(*args):
ii = scope.randint(len(args))
return scope.switch(ii, *args)
scope.one_of = one_of
def recursive_set_rng_kwarg(expr, rng=None):
"""
Make all of the stochastic nodes in expr use the rng
uniform(0, 1) -> uniform(0, 1, rng=rng)
"""
if rng is None:
rng = np.random.RandomState()
lrng = as_apply(rng)
for node in dfs(expr):
if node.name in implicit_stochastic_symbols:
for ii, (name, arg) in enumerate(list(node.named_args)):
if name == "rng":
node.named_args[ii] = ("rng", lrng)
break
else:
node.named_args.append(("rng", lrng))
return expr
def sample(expr, rng=None, **kwargs):
"""
Parameters:
expr - a pyll expression to be evaluated
rng - a np.random.RandomState instance
default: `np.random.RandomState()`
**kwargs - optional arguments passed along to
`hyperopt.pyll.rec_eval`
"""
if rng is None:
rng = np.random.RandomState()
foo = recursive_set_rng_kwarg(clone(as_apply(expr)), as_apply(rng))
return rec_eval(foo, **kwargs)