1
|
|
|
"""Grid search optimizer.""" |
2
|
|
|
|
3
|
|
|
# copyright: hyperactive developers, MIT License (see LICENSE file) |
4
|
|
|
|
5
|
|
|
from collections.abc import Sequence |
6
|
|
|
|
7
|
|
|
import numpy as np |
8
|
|
|
from sklearn.model_selection import ParameterSampler |
9
|
|
|
|
10
|
|
|
from hyperactive.base import BaseOptimizer |
11
|
|
|
|
12
|
|
|
|
13
|
|
|
class RandomSearchSk(BaseOptimizer): |
14
|
|
|
"""Random search optimizer leveraging sklearn's ``ParameterSampler``. |
15
|
|
|
|
16
|
|
|
Parameters |
17
|
|
|
---------- |
18
|
|
|
param_distributions : dict[str, list | scipy.stats.rv_frozen] |
19
|
|
|
Search space specification. Discrete lists are sampled uniformly; |
20
|
|
|
scipy distribution objects are sampled via their ``rvs`` method. |
21
|
|
|
n_iter : int, default=10 |
22
|
|
|
Number of parameter sets to evaluate. |
23
|
|
|
random_state : int | np.random.RandomState | None, default=None |
24
|
|
|
Controls the pseudo-random generator for reproducibility. |
25
|
|
|
error_score : float, default=np.nan |
26
|
|
|
Score assigned when the experiment raises an exception. |
27
|
|
|
experiment : BaseExperiment, optional |
28
|
|
|
Callable returning a scalar score when invoked with keyword |
29
|
|
|
arguments matching a parameter set. |
30
|
|
|
|
31
|
|
|
Attributes |
32
|
|
|
---------- |
33
|
|
|
best_params_ : dict[str, Any] |
34
|
|
|
Hyper-parameter configuration with the best (lowest) score. |
35
|
|
|
best_score_ : float |
36
|
|
|
Score achieved by ``best_params_``. |
37
|
|
|
best_index_ : int |
38
|
|
|
Index of ``best_params_`` in the sampled sequence. |
39
|
|
|
""" |
40
|
|
|
|
41
|
|
|
def __init__( |
42
|
|
|
self, |
43
|
|
|
param_distributions=None, |
44
|
|
|
n_iter=10, |
45
|
|
|
random_state=None, |
46
|
|
|
error_score=np.nan, |
47
|
|
|
experiment=None, |
48
|
|
|
): |
49
|
|
|
self.experiment = experiment |
50
|
|
|
self.param_distributions = param_distributions |
51
|
|
|
self.n_iter = n_iter |
52
|
|
|
self.random_state = random_state |
53
|
|
|
self.error_score = error_score |
54
|
|
|
|
55
|
|
|
super().__init__() |
56
|
|
|
|
57
|
|
|
@staticmethod |
58
|
|
|
def _is_distribution(obj) -> bool: |
59
|
|
|
"""Return True if *obj* looks like a scipy frozen distribution.""" |
60
|
|
|
return callable(getattr(obj, "rvs", None)) |
61
|
|
|
|
62
|
|
|
def _check_param_distributions(self, param_distributions): |
63
|
|
|
"""Validate ``param_distributions`` similar to sklearn ≤1.0.x.""" |
64
|
|
|
if hasattr(param_distributions, "items"): |
65
|
|
|
param_distributions = [param_distributions] |
66
|
|
|
|
67
|
|
|
for p in param_distributions: |
68
|
|
|
for name, v in p.items(): |
69
|
|
|
if self._is_distribution(v): |
70
|
|
|
# Assume scipy frozen distribution - nothing to check |
71
|
|
|
continue |
72
|
|
|
|
73
|
|
|
if isinstance(v, np.ndarray) and v.ndim > 1: |
74
|
|
|
raise ValueError("Parameter array should be one-dimensional.") |
75
|
|
|
|
76
|
|
|
if isinstance(v, str) or not isinstance(v, (np.ndarray, Sequence)): |
77
|
|
|
raise ValueError( |
78
|
|
|
f"Parameter distribution for ({name}) must be a list, numpy " |
79
|
|
|
f"array, or scipy.stats ``rv_frozen``, but got ({type(v)})." |
80
|
|
|
" Single values need to be wrapped in a sequence." |
81
|
|
|
) |
82
|
|
|
|
83
|
|
|
if len(v) == 0: |
84
|
|
|
raise ValueError( |
85
|
|
|
f"Parameter values for ({name}) need to be a " |
86
|
|
|
"non-empty sequence." |
87
|
|
|
) |
88
|
|
|
|
89
|
|
|
def _solve( |
90
|
|
|
self, |
91
|
|
|
experiment, |
92
|
|
|
param_distributions, |
93
|
|
|
n_iter, |
94
|
|
|
random_state, |
95
|
|
|
error_score, |
96
|
|
|
): |
97
|
|
|
"""Sample ``n_iter`` points and return the best parameter set.""" |
98
|
|
|
self._check_param_distributions(param_distributions) |
99
|
|
|
|
100
|
|
|
sampler = ParameterSampler( |
101
|
|
|
param_distributions=param_distributions, |
102
|
|
|
n_iter=n_iter, |
103
|
|
|
random_state=random_state, |
104
|
|
|
) |
105
|
|
|
candidate_params = list(sampler) |
106
|
|
|
|
107
|
|
|
scores: list[float] = [] |
108
|
|
|
for candidate_param in candidate_params: |
109
|
|
|
try: |
110
|
|
|
score = experiment(**candidate_param) |
111
|
|
|
except Exception: # noqa: B904 |
112
|
|
|
score = error_score |
113
|
|
|
scores.append(score) |
114
|
|
|
|
115
|
|
|
best_index = int(np.argmin(scores)) # lower-is-better convention |
116
|
|
|
best_params = candidate_params[best_index] |
117
|
|
|
|
118
|
|
|
# public attributes for external consumers |
119
|
|
|
self.best_index_ = best_index |
120
|
|
|
self.best_score_ = float(scores[best_index]) |
121
|
|
|
self.best_params_ = best_params |
122
|
|
|
|
123
|
|
|
return best_params |
124
|
|
|
|
125
|
|
|
@classmethod |
126
|
|
|
def get_test_params(cls, parameter_set: str = "default"): |
127
|
|
|
"""Provide deterministic toy configurations for unit tests.""" |
128
|
|
|
from hyperactive.experiment.integrations import SklearnCvExperiment |
129
|
|
|
from hyperactive.experiment.toy import Ackley |
130
|
|
|
|
131
|
|
|
# 1) ML example (Iris + SVC) |
132
|
|
|
sklearn_exp = SklearnCvExperiment.create_test_instance() |
133
|
|
|
param_dist_1 = { |
134
|
|
|
"C": [0.01, 0.1, 1, 10], |
135
|
|
|
"gamma": np.logspace(-4, 1, 6), |
136
|
|
|
} |
137
|
|
|
params_sklearn = { |
138
|
|
|
"experiment": sklearn_exp, |
139
|
|
|
"param_distributions": param_dist_1, |
140
|
|
|
"n_iter": 5, |
141
|
|
|
"random_state": 42, |
142
|
|
|
} |
143
|
|
|
|
144
|
|
|
# 2) continuous optimisation example (Ackley) |
145
|
|
|
ackley_exp = Ackley.create_test_instance() |
146
|
|
|
param_dist_2 = { |
147
|
|
|
"x0": np.linspace(-5, 5, 50), |
148
|
|
|
"x1": np.linspace(-5, 5, 50), |
149
|
|
|
} |
150
|
|
|
params_ackley = { |
151
|
|
|
"experiment": ackley_exp, |
152
|
|
|
"param_distributions": param_dist_2, |
153
|
|
|
"n_iter": 20, |
154
|
|
|
"random_state": 0, |
155
|
|
|
} |
156
|
|
|
|
157
|
|
|
return [params_sklearn, params_ackley] |
158
|
|
|
|