1
|
|
|
import time |
2
|
|
|
import numpy as np |
3
|
|
|
from sklearn.datasets import load_breast_cancer |
4
|
|
|
from sklearn.model_selection import cross_val_score |
5
|
|
|
from sklearn.tree import DecisionTreeClassifier |
6
|
|
|
from gradient_free_optimizers import ( |
7
|
|
|
RandomSearchOptimizer, |
8
|
|
|
HillClimbingOptimizer, |
9
|
|
|
) |
10
|
|
|
|
11
|
|
|
|
12
|
|
|
def objective_function(para): |
13
|
|
|
score = -para["x1"] * para["x1"] |
14
|
|
|
return score |
15
|
|
|
|
16
|
|
|
|
17
|
|
|
search_space = { |
18
|
|
|
"x1": np.arange(0, 100000, 0.1), |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
|
22
|
|
|
def test_max_score_0(): |
23
|
|
|
def objective_function(para): |
24
|
|
|
score = -para["x1"] * para["x1"] |
25
|
|
|
return score |
26
|
|
|
|
27
|
|
|
search_space = { |
28
|
|
|
"x1": np.arange(0, 100, 0.1), |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
max_score = -9999 |
32
|
|
|
|
33
|
|
|
opt = HillClimbingOptimizer( |
34
|
|
|
search_space, |
35
|
|
|
initialize={"warm_start": [{"x1": 99}]}, |
36
|
|
|
epsilon=0.01, |
37
|
|
|
rand_rest_p=0, |
38
|
|
|
) |
39
|
|
|
opt.search( |
40
|
|
|
objective_function, |
41
|
|
|
n_iter=100000, |
42
|
|
|
max_score=max_score, |
43
|
|
|
) |
44
|
|
|
|
45
|
|
|
print("\n Results head \n", opt.results.head()) |
46
|
|
|
print("\n Results tail \n", opt.results.tail()) |
47
|
|
|
|
48
|
|
|
print("\nN iter:", len(opt.results)) |
49
|
|
|
|
50
|
|
|
assert -100 > opt.best_score > max_score |
51
|
|
|
|
52
|
|
|
|
53
|
|
|
def test_max_score_1(): |
54
|
|
|
def objective_function(para): |
55
|
|
|
score = -para["x1"] * para["x1"] |
56
|
|
|
time.sleep(0.01) |
57
|
|
|
return score |
58
|
|
|
|
59
|
|
|
search_space = { |
60
|
|
|
"x1": np.arange(0, 100, 0.1), |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
max_score = -9999 |
64
|
|
|
|
65
|
|
|
c_time = time.time() |
66
|
|
|
opt = HillClimbingOptimizer(search_space, initialize={"warm_start": [{"x1": 99}]}) |
67
|
|
|
opt.search( |
68
|
|
|
objective_function, |
69
|
|
|
n_iter=100000, |
70
|
|
|
max_score=max_score, |
71
|
|
|
) |
72
|
|
|
diff_time = time.time() - c_time |
73
|
|
|
|
74
|
|
|
print("\n Results head \n", opt.results.head()) |
75
|
|
|
print("\n Results tail \n", opt.results.tail()) |
76
|
|
|
|
77
|
|
|
print("\nN iter:", len(opt.results)) |
78
|
|
|
|
79
|
|
|
assert diff_time < 1 |
80
|
|
|
|