global_optimization.cpp 18.8 KB
Newer Older
1
2
3
// Copyright (C) 2017  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.

Davis King's avatar
Davis King committed
4
#include "opaque_types.h"
5
6
7
#include <dlib/python.h>
#include <dlib/global_optimization.h>
#include <dlib/matrix.h>
8
#include <pybind11/stl.h>
9
10
11
12


using namespace dlib;
using namespace std;
13
namespace py = pybind11;
14
15
16
17

// ----------------------------------------------------------------------------------------

std::vector<bool> list_to_bool_vector(
18
    const py::list& l
19
20
21
22
23
)
{
    std::vector<bool> result(len(l));
    for (long i = 0; i < result.size(); ++i)
    {
24
        result[i] = l[i].cast<bool>();
25
26
27
28
29
    }
    return result;
}

matrix<double,0,1> list_to_mat(
30
    const py::list& l
31
32
33
34
)
{
    matrix<double,0,1> result(len(l));
    for (long i = 0; i < result.size(); ++i)
35
        result(i) = l[i].cast<double>();
36
37
38
    return result;
}

39
py::list mat_to_list (
40
41
42
    const matrix<double,0,1>& m
)
{
43
    py::list l;
44
45
46
47
48
    for (long i = 0; i < m.size(); ++i)
        l.append(m(i));
    return l;
}

49
size_t num_function_arguments(py::object f, size_t expected_num)
50
{
51
52
53
54
55
    const auto code_object = f.attr(hasattr(f,"func_code") ? "func_code" : "__code__");
    const auto num = code_object.attr("co_argcount").cast<std::size_t>();
    if (num < expected_num && (code_object.attr("co_flags").cast<int>() & CO_VARARGS))
        return expected_num;
    return num;
56
57
}

58
double call_func(py::object f, const matrix<double,0,1>& args)
59
{
60
    const auto num = num_function_arguments(f, args.size());
61
62
63
64
    DLIB_CASSERT(num == args.size(), 
        "The function being optimized takes a number of arguments that doesn't agree with the size of the bounds lists you provided to find_max_global()");
    DLIB_CASSERT(0 < num && num < 15, "Functions being optimized must take between 1 and 15 scalar arguments.");

65
#define CALL_WITH_N_ARGS(N) case N: return dlib::gopt_impl::_cwv(f,args,typename make_compile_time_integer_range<N>::type()).cast<double>(); 
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
    switch (num)
    {
        CALL_WITH_N_ARGS(1)
        CALL_WITH_N_ARGS(2)
        CALL_WITH_N_ARGS(3)
        CALL_WITH_N_ARGS(4)
        CALL_WITH_N_ARGS(5)
        CALL_WITH_N_ARGS(6)
        CALL_WITH_N_ARGS(7)
        CALL_WITH_N_ARGS(8)
        CALL_WITH_N_ARGS(9)
        CALL_WITH_N_ARGS(10)
        CALL_WITH_N_ARGS(11)
        CALL_WITH_N_ARGS(12)
        CALL_WITH_N_ARGS(13)
        CALL_WITH_N_ARGS(14)
        CALL_WITH_N_ARGS(15)

        default:
            DLIB_CASSERT(false, "oops");
            break;
    }
}

// ----------------------------------------------------------------------------------------

92
93
94
95
96
py::tuple py_find_max_global (
    py::object f,
    py::list bound1,
    py::list bound2,
    py::list is_integer_variable,
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
    unsigned long num_function_calls,
    double solver_epsilon = 0
)
{
    DLIB_CASSERT(len(bound1) == len(bound2));
    DLIB_CASSERT(len(bound1) == len(is_integer_variable));

    auto func = [&](const matrix<double,0,1>& x)
    {
        return call_func(f, x);
    };

    auto result = find_max_global(func, list_to_mat(bound1), list_to_mat(bound2),
        list_to_bool_vector(is_integer_variable), max_function_calls(num_function_calls),
        solver_epsilon);

113
    return py::make_tuple(mat_to_list(result.x),result.y);
114
115
}

116
117
118
119
py::tuple py_find_max_global2 (
    py::object f,
    py::list bound1,
    py::list bound2,
120
121
122
123
124
125
126
127
128
129
130
131
132
    unsigned long num_function_calls,
    double solver_epsilon = 0
)
{
    DLIB_CASSERT(len(bound1) == len(bound2));

    auto func = [&](const matrix<double,0,1>& x)
    {
        return call_func(f, x);
    };

    auto result = find_max_global(func, list_to_mat(bound1), list_to_mat(bound2), max_function_calls(num_function_calls), solver_epsilon);

133
    return py::make_tuple(mat_to_list(result.x),result.y);
134
135
136
137
}

// ----------------------------------------------------------------------------------------

138
139
140
141
142
py::tuple py_find_min_global (
    py::object f,
    py::list bound1,
    py::list bound2,
    py::list is_integer_variable,
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
    unsigned long num_function_calls,
    double solver_epsilon = 0
)
{
    DLIB_CASSERT(len(bound1) == len(bound2));
    DLIB_CASSERT(len(bound1) == len(is_integer_variable));

    auto func = [&](const matrix<double,0,1>& x)
    {
        return call_func(f, x);
    };

    auto result = find_min_global(func, list_to_mat(bound1), list_to_mat(bound2),
        list_to_bool_vector(is_integer_variable), max_function_calls(num_function_calls),
        solver_epsilon);

159
    return py::make_tuple(mat_to_list(result.x),result.y);
160
161
}

162
163
164
165
py::tuple py_find_min_global2 (
    py::object f,
    py::list bound1,
    py::list bound2,
166
167
168
169
170
171
172
173
174
175
176
177
178
    unsigned long num_function_calls,
    double solver_epsilon = 0
)
{
    DLIB_CASSERT(len(bound1) == len(bound2));

    auto func = [&](const matrix<double,0,1>& x)
    {
        return call_func(f, x);
    };

    auto result = find_min_global(func, list_to_mat(bound1), list_to_mat(bound2), max_function_calls(num_function_calls), solver_epsilon);

179
    return py::make_tuple(mat_to_list(result.x),result.y);
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
function_spec py_function_spec1 (
    py::list a,
    py::list b
)
{
    return function_spec(list_to_mat(a), list_to_mat(b));
}

function_spec py_function_spec2 (
    py::list a,
    py::list b,
    py::list c
)
{
    return function_spec(list_to_mat(a), list_to_mat(b), list_to_bool_vector(c));
}

std::shared_ptr<global_function_search> py_global_function_search1 (
    py::list functions
)
{
    std::vector<function_spec> tmp;
206
    for (const auto& i : functions)
207
208
209
210
211
212
213
214
215
216
217
218
        tmp.emplace_back(i.cast<function_spec>());

    return std::make_shared<global_function_search>(tmp);
}

std::shared_ptr<global_function_search> py_global_function_search2 (
    py::list functions,
    py::list initial_function_evals,
    double relative_noise_magnitude
)
{
    std::vector<function_spec> specs;
219
    for (const auto& i : functions)
220
221
222
        specs.emplace_back(i.cast<function_spec>());

    std::vector<std::vector<function_evaluation>> func_evals;
223
    for (const auto& i : initial_function_evals)
224
225
    {
        std::vector<function_evaluation> evals;
226
        for (const auto& j : i)
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
        {
            evals.emplace_back(j.cast<function_evaluation>());
        }
        func_evals.emplace_back(std::move(evals));
    }

    return std::make_shared<global_function_search>(specs, func_evals, relative_noise_magnitude);
}

function_evaluation py_function_evaluation(
    const py::list& x, 
    double y
)
{
    return function_evaluation(list_to_mat(x), y);
}

// ----------------------------------------------------------------------------------------

246
void bind_global_optimization(py::module& m)
247
{
Davis King's avatar
Davis King committed
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


    const char* docstring =
"requires \n\
    - len(bound1) == len(bound2) == len(is_integer_variable) \n\
    - for all valid i: bound1[i] != bound2[i] \n\
    - solver_epsilon >= 0 \n\
    - f() is a real valued multi-variate function.  It must take scalar real \n\
      numbers as its arguments and the number of arguments must be len(bound1). \n\
ensures \n\
    - This function performs global optimization on the given f() function. \n\
      The goal is to maximize the following objective function: \n\
         f(x) \n\
      subject to the constraints: \n\
        min(bound1[i],bound2[i]) <= x[i] <= max(bound1[i],bound2[i]) \n\
        if (is_integer_variable[i]) then x[i] is an integer value (but still \n\
        represented with float type). \n\
    - find_max_global() runs until it has called f() num_function_calls times. \n\
      Then it returns the best x it has found along with the corresponding output \n\
      of f().  That is, it returns (best_x_seen,f(best_x_seen)).  Here best_x_seen \n\
      is a list containing the best arguments to f() this function has found. \n\
    - find_max_global() uses a global optimization method based on a combination of \n\
      non-parametric global function modeling and quadratic trust region modeling \n\
      to efficiently find a global maximizer.  It usually does a good job with a \n\
      relatively small number of calls to f().  For more information on how it \n\
      works read the documentation for dlib's global_function_search object. \n\
      However, one notable element is the solver epsilon, which you can adjust. \n\
 \n\
      The search procedure will only attempt to find a global maximizer to at most \n\
      solver_epsilon accuracy.  Once a local maximizer is found to that accuracy \n\
      the search will focus entirely on finding other maxima elsewhere rather than \n\
      on further improving the current local optima found so far.  That is, once a \n\
      local maxima is identified to about solver_epsilon accuracy, the algorithm \n\
      will spend all its time exploring the function to find other local maxima to \n\
      investigate.  An epsilon of 0 means it will keep solving until it reaches \n\
      full floating point precision.  Larger values will cause it to switch to pure \n\
      global exploration sooner and therefore might be more effective if your \n\
      objective function has many local maxima and you don't care about a super \n\
      high precision solution. \n\
    - Any variables that satisfy the following conditions are optimized on a log-scale: \n\
        - The lower bound on the variable is > 0 \n\
        - The ratio of the upper bound to lower bound is > 1000 \n\
        - The variable is not an integer variable \n\
      We do this because it's common to optimize machine learning models that have \n\
      parameters with bounds in a range such as [1e-5 to 1e10] (e.g. the SVM C \n\
      parameter) and it's much more appropriate to optimize these kinds of \n\
      variables on a log scale.  So we transform them by applying log() to \n\
      them and then undo the transform via exp() before invoking the function \n\
      being optimized.  Therefore, this transformation is invisible to the user \n\
      supplied functions.  In most cases, it improves the efficiency of the \n\
      optimizer.";
299
300
301
302
303
304
305
306
307
308
309
310
311
    /*!
        requires
            - len(bound1) == len(bound2) == len(is_integer_variable)
            - for all valid i: bound1[i] != bound2[i]
            - solver_epsilon >= 0
            - f() is a real valued multi-variate function.  It must take scalar real
              numbers as its arguments and the number of arguments must be len(bound1).
        ensures
            - This function performs global optimization on the given f() function.
              The goal is to maximize the following objective function:
                 f(x)
              subject to the constraints:
                min(bound1[i],bound2[i]) <= x[i] <= max(bound1[i],bound2[i])
Davis King's avatar
Davis King committed
312
313
                if (is_integer_variable[i]) then x[i] is an integer value (but still
                represented with float type).
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
            - find_max_global() runs until it has called f() num_function_calls times.
              Then it returns the best x it has found along with the corresponding output
              of f().  That is, it returns (best_x_seen,f(best_x_seen)).  Here best_x_seen
              is a list containing the best arguments to f() this function has found.
            - find_max_global() uses a global optimization method based on a combination of
              non-parametric global function modeling and quadratic trust region modeling
              to efficiently find a global maximizer.  It usually does a good job with a
              relatively small number of calls to f().  For more information on how it
              works read the documentation for dlib's global_function_search object.
              However, one notable element is the solver epsilon, which you can adjust.

              The search procedure will only attempt to find a global maximizer to at most
              solver_epsilon accuracy.  Once a local maximizer is found to that accuracy
              the search will focus entirely on finding other maxima elsewhere rather than
              on further improving the current local optima found so far.  That is, once a
              local maxima is identified to about solver_epsilon accuracy, the algorithm
              will spend all its time exploring the function to find other local maxima to
              investigate.  An epsilon of 0 means it will keep solving until it reaches
              full floating point precision.  Larger values will cause it to switch to pure
              global exploration sooner and therefore might be more effective if your
              objective function has many local maxima and you don't care about a super
              high precision solution.
            - Any variables that satisfy the following conditions are optimized on a log-scale:
                - The lower bound on the variable is > 0
                - The ratio of the upper bound to lower bound is > 1000
                - The variable is not an integer variable
              We do this because it's common to optimize machine learning models that have
              parameters with bounds in a range such as [1e-5 to 1e10] (e.g. the SVM C
              parameter) and it's much more appropriate to optimize these kinds of
              variables on a log scale.  So we transform them by applying log() to
              them and then undo the transform via exp() before invoking the function
              being optimized.  Therefore, this transformation is invisible to the user
              supplied functions.  In most cases, it improves the efficiency of the
              optimizer.
    !*/
Davis King's avatar
Davis King committed
349
350
351
    m.def("find_max_global", &py_find_max_global, docstring, py::arg("f"),
        py::arg("bound1"), py::arg("bound2"), py::arg("is_integer_variable"),
        py::arg("num_function_calls"), py::arg("solver_epsilon")=0);
352

353
    m.def("find_max_global", &py_find_max_global2, 
354
        "This function simply calls the other version of find_max_global() with is_integer_variable set to False for all variables.", 
Davis King's avatar
Davis King committed
355
356
        py::arg("f"), py::arg("bound1"), py::arg("bound2"), py::arg("num_function_calls"),
        py::arg("solver_epsilon")=0);
357
358
359



360
    m.def("find_min_global", &py_find_min_global, 
Davis King's avatar
Davis King committed
361
362
363
      "This function is just like find_max_global(), except it performs minimization rather than maximization.", 
        py::arg("f"), py::arg("bound1"), py::arg("bound2"), py::arg("is_integer_variable"),
        py::arg("num_function_calls"), py::arg("solver_epsilon")=0);
364

365
    m.def("find_min_global", &py_find_min_global2, 
366
        "This function simply calls the other version of find_min_global() with is_integer_variable set to False for all variables.", 
Davis King's avatar
Davis King committed
367
368
        py::arg("f"), py::arg("bound1"), py::arg("bound2"), py::arg("num_function_calls"),
        py::arg("solver_epsilon")=0);
369

370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
    // -------------------------------------------------
    // -------------------------------------------------


    py::class_<function_evaluation> (m, "function_evaluation",  R"RAW(  
This object records the output of a real valued function in response to
some input. 

In particular, if you have a function F(x) then the function_evaluation is
simply a struct that records x and the scalar value F(x). )RAW")
        .def(py::init<matrix<double,0,1>,double>(), py::arg("x"), py::arg("y"))
        .def(py::init<>(&py_function_evaluation), py::arg("x"), py::arg("y"))
        .def_readonly("x",       &function_evaluation::x)
        .def_readonly("y",       &function_evaluation::y);


    py::class_<function_spec> (m, "function_spec",  "See: http://dlib.net/dlib/global_optimization/global_function_search_abstract.h.html")
        .def(py::init<matrix<double,0,1>,matrix<double,0,1>>(), py::arg("bound1"), py::arg("bound2") )
        .def(py::init<matrix<double,0,1>,matrix<double,0,1>,std::vector<bool>>(), py::arg("bound1"), py::arg("bound2"), py::arg("is_integer") )
        .def(py::init<>(&py_function_spec1), py::arg("bound1"), py::arg("bound2"))
        .def(py::init<>(&py_function_spec2), py::arg("bound1"), py::arg("bound2"), py::arg("is_integer"))
        .def_readonly("lower",       &function_spec::lower)
        .def_readonly("upper",       &function_spec::upper)
        .def_readonly("is_integer_variable",       &function_spec::is_integer_variable);


    py::class_<function_evaluation_request> (m, "function_evaluation_request", "See: http://dlib.net/dlib/global_optimization/global_function_search_abstract.h.html")
        .def_property_readonly("function_idx", &function_evaluation_request::function_idx)
        .def_property_readonly("x", &function_evaluation_request::x)
        .def_property_readonly("has_been_evaluated", &function_evaluation_request::has_been_evaluated)
        .def("set", &function_evaluation_request::set);

    py::class_<global_function_search, std::shared_ptr<global_function_search>> (m, "global_function_search", "See: http://dlib.net/dlib/global_optimization/global_function_search_abstract.h.html")
        .def(py::init<function_spec>(), py::arg("function"))
        .def(py::init<>(&py_global_function_search1), py::arg("functions"))
        .def(py::init<>(&py_global_function_search2), py::arg("functions"), py::arg("initial_function_evals"), py::arg("relative_noise_magnitude"))
        .def("set_seed", &global_function_search::set_seed, py::arg("seed"))
        .def("num_functions", &global_function_search::num_functions)
        .def("get_function_evaluations", [](const global_function_search& self) { 
            std::vector<function_spec> specs;
            std::vector<std::vector<function_evaluation>> function_evals;
            self.get_function_evaluations(specs,function_evals); 
            py::list py_specs, py_func_evals;
413
            for (const auto& s : specs)
414
                py_specs.append(s);
415
            for (const auto& i : function_evals)
416
417
            {
                py::list tmp;
418
                for (const auto& j : i)
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
                    tmp.append(j);
                py_func_evals.append(tmp);
            }
            return py::make_tuple(py_specs,py_func_evals);})
        .def("get_best_function_eval", [](const global_function_search& self) { 
            matrix<double,0,1> x; double y; size_t idx; self.get_best_function_eval(x,y,idx); return py::make_tuple(x,y,idx);})
        .def("get_next_x", &global_function_search::get_next_x)
        .def("get_pure_random_search_probability", &global_function_search::get_pure_random_search_probability)
        .def("set_pure_random_search_probability", &global_function_search::set_pure_random_search_probability, py::arg("prob"))
        .def("get_solver_epsilon", &global_function_search::get_solver_epsilon)
        .def("set_solver_epsilon", &global_function_search::set_solver_epsilon, py::arg("eps"))
        .def("get_relative_noise_magnitude", &global_function_search::get_relative_noise_magnitude)
        .def("set_relative_noise_magnitude", &global_function_search::set_relative_noise_magnitude, py::arg("value"))
        .def("get_monte_carlo_upper_bound_sample_num", &global_function_search::get_monte_carlo_upper_bound_sample_num)
        .def("set_monte_carlo_upper_bound_sample_num", &global_function_search::set_monte_carlo_upper_bound_sample_num, py::arg("num"))
        ;

436
437
}