1
|
|
|
import time |
2
|
|
|
import numpy as np |
3
|
|
|
import pandas as pd |
4
|
|
|
from sklearn.datasets import load_breast_cancer |
5
|
|
|
from sklearn.model_selection import cross_val_score |
6
|
|
|
from sklearn.tree import DecisionTreeClassifier |
7
|
|
|
from gradient_free_optimizers import RandomSearchOptimizer |
8
|
|
|
|
9
|
|
|
|
10
|
|
|
def objective_function(para): |
11
|
|
|
score = -para["x1"] * para["x1"] |
12
|
|
|
return score |
13
|
|
|
|
14
|
|
|
|
15
|
|
|
search_space = { |
16
|
|
|
"x1": np.arange(0, 100000, 0.1), |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
|
20
|
|
|
def test_attributes_best_score_0(): |
21
|
|
|
opt = RandomSearchOptimizer(search_space) |
22
|
|
|
opt.search(objective_function, n_iter=100) |
23
|
|
|
|
24
|
|
|
assert np.inf > opt.best_score > -np.inf |
25
|
|
|
|
26
|
|
|
|
27
|
|
|
def test_attributes_best_para_0(): |
28
|
|
|
opt = RandomSearchOptimizer(search_space) |
29
|
|
|
opt.search(objective_function, n_iter=100) |
30
|
|
|
|
31
|
|
|
assert isinstance(opt.best_para, dict) |
32
|
|
|
|
33
|
|
|
|
34
|
|
|
def test_attributes_best_para_1(): |
35
|
|
|
opt = RandomSearchOptimizer(search_space) |
36
|
|
|
opt.search(objective_function, n_iter=100) |
37
|
|
|
|
38
|
|
|
assert list(opt.best_para.keys()) == list(search_space.keys()) |
39
|
|
|
|
40
|
|
|
|
41
|
|
|
def test_attributes_eval_times_0(): |
42
|
|
|
opt = RandomSearchOptimizer(search_space) |
43
|
|
|
opt.search(objective_function, n_iter=100) |
44
|
|
|
|
45
|
|
|
assert isinstance(opt.eval_times, list) |
46
|
|
|
|
47
|
|
|
|
48
|
|
|
def test_attributes_eval_times_1(): |
49
|
|
|
c_time = time.time() |
50
|
|
|
opt = RandomSearchOptimizer(search_space) |
51
|
|
|
opt.search(objective_function, n_iter=100) |
52
|
|
|
diff_time = time.time() - c_time |
53
|
|
|
|
54
|
|
|
assert np.array(opt.eval_times).sum() < diff_time |
55
|
|
|
|
56
|
|
|
|
57
|
|
|
def test_attributes_iter_times_0(): |
58
|
|
|
opt = RandomSearchOptimizer(search_space) |
59
|
|
|
opt.search(objective_function, n_iter=100) |
60
|
|
|
|
61
|
|
|
assert isinstance(opt.iter_times, list) |
62
|
|
|
|
63
|
|
|
|
64
|
|
|
def test_attributes_iter_times_1(): |
65
|
|
|
c_time = time.time() |
66
|
|
|
opt = RandomSearchOptimizer(search_space) |
67
|
|
|
opt.search(objective_function, n_iter=100) |
68
|
|
|
diff_time = time.time() - c_time |
69
|
|
|
|
70
|
|
|
assert np.array(opt.iter_times).sum() < diff_time |
71
|
|
|
|