-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
359 lines (284 loc) · 10 KB
/
utils.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# -*- coding: utf-8 -*-
import logging
from collections import OrderedDict, defaultdict
from time import sleep
import json
from filelock import FileLock
import numpy as np
import luigi
import law
from luigi import IntParameter, FloatParameter, ChoiceParameter
from skopt.space import Real, Integer, Categorical
from skopt.plots import plot_objective, plot_evaluations, plot_convergence
import matplotlib.pyplot as plt
logger = logging.getLogger(__name__)
law.contrib.load("matplotlib")
class NumpyEncoder(json.JSONEncoder):
"""Custom encoder for numpy data types"""
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, (complex, np.complexfloating)):
return {"real": obj.real, "imag": obj.imag}
elif isinstance(obj, (np.ndarray,)):
return obj.tolist()
elif isinstance(obj, (np.bool_)):
return bool(obj)
elif isinstance(obj, (np.void)):
return None
return json.JSONEncoder.default(self, obj)
class SkoptLuigiParameter(object):
"""Merges Luigi and Skopt parameters
Redundant keywords are set to the
"""
optimizable = True
def __repr__(self):
return "{}".format(self.__class__.__name__)
@property
def skopt_keys(self):
raise NotImplementedError
def divide_kwargs(self, kwargs):
skopt_kwargs = defaultdict()
for skopt_key in self.skopt_keys:
if skopt_key in kwargs.keys():
skopt_kwargs[skopt_key] = kwargs[skopt_key]
del kwargs[skopt_key]
if "description" not in kwargs:
kwargs["description"] = skopt_kwargs["name"]
return kwargs, skopt_kwargs
def freeze(self):
self.optimizable = False
return self
class SIntParameter(Integer, IntParameter, SkoptLuigiParameter):
"""Implements an integer parameter
Example:
a = SIntParameter(
0,
2,
name='min_samples_split',
default=1,
description="Number"
)
"""
skopt_keys = ["prior", "transform", "name"]
def __init__(self, *args, **kwargs):
luigi_kwargs, skopt_kwargs = self.divide_kwargs(kwargs)
IntParameter.__init__(self, **luigi_kwargs)
Integer.__init__(self, *args, **skopt_kwargs)
class SFloatParameter(Real, FloatParameter, SkoptLuigiParameter):
"""Implements a float parameter
Example:
b = SFloatParameter(
0.0,
2.0,
name='max_depth',
default=1.5,
description="Number"
)
"""
skopt_keys = ["prior", "transform", "name"]
def __init__(self, *args, **kwargs):
luigi_kwargs, skopt_kwargs = self.divide_kwargs(kwargs)
FloatParameter.__init__(self, **luigi_kwargs)
Real.__init__(self, *args, **skopt_kwargs)
class SChoiceParameter(Categorical, ChoiceParameter, SkoptLuigiParameter):
"""Implements a choice parameter
Example:
c = SChoiceParameter(
[0, 1, 2],
name="categorical",
choices=["0", "1", "2"],
description="categorical"
)
"""
skopt_keys = ["prior", "transform", "name"]
def __init__(self, *args, **kwargs):
luigi_kwargs, skopt_kwargs = self.divide_kwargs(kwargs)
choices = args[0]
ChoiceParameter.__init__(self, choices=choices, **luigi_kwargs)
Categorical.__init__(self, *args, **skopt_kwargs)
class TargetLock(object):
def __init__(self, target):
self.target = target
self.path = target.path
self.lock = FileLock(self.path + ".lock")
def __enter__(self):
self.lock.acquire()
# logger.info(f"{self.__class__.__name__}[{os.getpid()}]: acquired {self.path}")
self.loaded = self.target.load()
return self.loaded
def __exit__(self, type, value, traceback):
self.target.dump(self.loaded)
# logger.info(f"{self.__class__.__name__}[{os.getpid()}]: releasing {self.path}")
self.lock.release()
class Opt:
opt_version = IntParameter(
default=0,
description="Version number of the optimizer run",
)
iterations = luigi.IntParameter(
default=4,
description="Number of iterations",
)
n_parallel = luigi.IntParameter(
default=2,
description="Number of parallel optimization streams",
)
objective_key = luigi.Parameter("objective")
status_frequency = luigi.IntParameter(
default=50,
description="Frequency to give a status.",
)
def store_parts(self):
return super().store_parts() + (f"opt_version_{self.opt_version}",)
class OptimizerPreparation(Opt):
"""
Task that prepares the optimizer and draws a todo list.
"""
n_initial = luigi.IntParameter(
default=10,
description="Number of random sampled values \
before starting optimizations",
)
@property
def n_initial_points(self):
return max(self.n_initial, self.n_parallel)
def output(self):
return {
"opt": self.local_target("optimizer.pkl"),
"todos": self.local_target("todos.json"),
"keys": self.local_target("keys.json"),
}
@property
def objective(self):
raise NotImplementedError
def optimizable_parameters(self):
params = self.objective.get_params()
opt_params = OrderedDict()
for name, param in params:
if isinstance(param, SkoptLuigiParameter):
if param.optimizable:
opt_params[name] = param
return opt_params
def run(self):
import skopt
opt_params = self.optimizable_parameters()
optimizer = skopt.Optimizer(
dimensions=list(opt_params.values()),
random_state=1,
n_initial_points=self.n_initial_points,
)
x = [optimizer.ask() for i in range(self.n_initial_points)]
ask = [dict(zip(opt_params.keys(), val)) for val in x]
with self.output()["opt"].localize("w") as tmp:
tmp.dump(optimizer)
with self.output()["todos"].localize("w") as tmp:
tmp.dump(ask, cls=NumpyEncoder)
with self.output()["keys"].localize("w") as tmp:
tmp.dump(list(opt_params.keys()))
class Optimizer(Opt):
"""
Workflow that runs optimization.
"""
ind = luigi.IntParameter(0, description="Index of the optimization stream")
@property
def objective(self):
raise NotImplementedError
@property
def optimizer_preparation(self):
raise NotImplementedError
def requires(self):
return self.optimizer_preparation.req(self)
def output(self):
return {
"opt": self.local_target("optimizer.pkl"),
"conv": self.local_target("convergence.pdf"),
"obj": self.local_target("objective.pdf"),
}
def plot_status(self, opt):
result = opt.run(None, 0)
output = self.output()
plot_convergence(result)
output["conv"].dump(plt.gcf(), bbox_inches="tight")
plot_objective(result)
output["obj"].dump(plt.gcf(), bbox_inches="tight")
plt.close()
@property
def todo(self):
return self.local_target(f"todos_{self.ind}.json")
def obj_req(self, ask):
return self.objective.req(self, **ask)
def run(self):
if self.todo.exists():
ask = self.todo.load()
obj = yield self.obj_req(ask)
y = obj[self.objective_key].load()
with TargetLock(self.input()["opt"]) as opt:
opt.tell(list(ask.values()), y)
self.todo.remove()
with TargetLock(self.input()["opt"]) as opt, TargetLock(
self.input()["todos"]
) as todos, TargetLock(self.input()["keys"]) as keys:
iteration = len(opt.Xi)
if iteration and iteration % self.status_frequency == 0:
self.plot_status(opt)
if iteration >= self.iterations:
self.output()["opt"].dump(opt)
self.output()["obj"].touch()
self.output()["conv"].touch()
return
logger.info("got new todo", end=", ")
if len(todos) > 0:
ask = todos.pop(0)
logger.info("from todos", end=": ")
else:
x = opt.ask()
ask = dict(zip(keys, x))
logger.info("by asking", end=": ")
logger.info(ask)
self.todo.dump(ask, cls=NumpyEncoder)
yield self.obj_req(ask)
def get_best(self):
br = self.as_branch(0)
return self.obj_req(
dict(
zip(br.input()["keys"].load(), br.output()["opt"].load().get_result().x)
)
)
class OptimizerPlot(Opt):
"""
Workflow that runs optimization and plots results.
"""
plot_objective = luigi.BoolParameter(
default=True,
description="Plot objective. \
Can be expensive to evaluate for high dimensional input",
)
@property
def optimizer(self):
raise NotImplementedError
def requires(self):
return [self.optimizer.req(self, ind=ind) for ind in range(self.n_parallel)]
def output(self):
collection = {
"evaluations": self.local_target("evaluations.pdf"),
"convergence": self.local_target("convergence.pdf"),
}
if self.plot_objective:
collection["objective"] = self.local_target("objective.pdf")
return collection
def run(self):
result = self.input()[0]["opt"].load().run(None, 0)
output = self.output()
plot_convergence(result)
output["convergence"].dump(plt.gcf(), bbox_inches="tight")
plt.close()
plot_evaluations(result, bins=10)
output["evaluations"].dump(plt.gcf(), bbox_inches="tight")
plt.close()
if self.plot_objective:
plot_objective(result)
output["objective"].dump(plt.gcf(), bbox_inches="tight")
plt.close()