Passed
Push — master ( 588022...8a2a5a )
by Simon
01:36
created

GridSearch.get_test_params()   A

Complexity

Conditions 1

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 25
rs 9.65
c 0
b 0
f 0
cc 1
nop 2
1
from hyperactive.opt._adapters._gfo import _BaseGFOadapter
2
3
4
class GridSearch(_BaseGFOadapter):
5
    """Grid search optimizer.
6
7
    Parameters
8
    ----------
9
    search_space : dict[str, list]
10
        The search space to explore. A dictionary with parameter
11
        names as keys and a numpy array as values.
12
    initialize : dict[str, int]
13
        The method to generate initial positions. A dictionary with
14
        the following key literals and the corresponding value type:
15
        {"grid": int, "vertices": int, "random": int, "warm_start": list[dict]}
16
    constraints : list[callable]
17
        A list of constraints, where each constraint is a callable.
18
        The callable returns `True` or `False` dependend on the input parameters.
19
    random_state : None, int
20
        If None, create a new random state. If int, create a new random state
21
        seeded with the value.
22
    rand_rest_p : float
23
        The probability of a random iteration during the the search process.
24
    step_size : int
25
        The step-size for the grid search.
26
    direction : "diagonal" or "orthogonal"
27
        The direction of the grid search.
28
    n_iter : int, default=100
29
        The number of iterations to run the optimizer.
30
    verbose : bool, default=False
31
        If True, print the progress of the optimization process.
32
    experiment : BaseExperiment, optional
33
        The experiment to optimize parameters for.
34
        Optional, can be passed later via ``set_params``.
35
36
    Examples
37
    --------
38
    Basic usage of GridSearch with a scikit-learn experiment:
39
40
    1. defining the experiment to optimize:
41
    >>> from hyperactive.experiment.integrations import SklearnCvExperiment
42
    >>> from sklearn.datasets import load_iris
43
    >>> from sklearn.svm import SVC
44
    >>>
45
    >>> X, y = load_iris(return_X_y=True)
46
    >>>
47
    >>> sklearn_exp = SklearnCvExperiment(
48
    ...     estimator=SVC(),
49
    ...     X=X,
50
    ...     y=y,
51
    ... )
52
53
    2. setting up the gridSearch optimizer:
54
    >>> from hyperactive.opt import GridSearch
55
    >>> import numpy as np
56
    >>>
57
    >>> config = {
58
    ...     "search_space": {
59
    ...         "C": [0.01, 0.1, 1, 10],
60
    ...         "gamma": [0.0001, 0.01, 0.1, 1, 10],
61
    ...     },
62
    ...     "n_iter": 100,
63
    ... }
64
    >>> optimizer = GridSearch(experiment=sklearn_exp, **config)
65
66
    3. running the optimization:
67
    >>> best_params = optimizer.run()
68
69
    Best parameters can also be accessed via:
70
    >>> best_params = optimizer.best_params_
71
    """
72
73
    _tags = {
74
        "info:name": "Grid Search",
75
        "info:local_vs_global": "global",
76
        "info:explore_vs_exploit": "explore",
77
        "info:compute": "high",
78
    }
79
80
    def __init__(
81
        self,
82
        search_space=None,
83
        initialize=None,
84
        constraints=None,
85
        random_state=None,
86
        rand_rest_p=0.1,
87
        step_size=1,
88
        direction="diagonal",
89
        n_iter=100,
90
        verbose=False,
91
        experiment=None,
92
    ):
93
        self.random_state = random_state
94
        self.rand_rest_p = rand_rest_p
95
        self.step_size = step_size
96
        self.direction = direction
97
        self.search_space = search_space
98
        self.initialize = initialize
99
        self.constraints = constraints
100
        self.n_iter = n_iter
101
        self.experiment = experiment
102
        self.verbose = verbose
103
104
        super().__init__()
105
106
    def _get_gfo_class(self):
107
        """Get the GFO class to use.
108
109
        Returns
110
        -------
111
        class
112
            The GFO class to use. One of the concrete GFO classes
113
        """
114
        from gradient_free_optimizers import GridSearchOptimizer
115
116
        return GridSearchOptimizer
117
118
    @classmethod
119
    def get_test_params(cls, parameter_set="default"):
120
        """Get the test parameters for the optimizer.
121
122
        Returns
123
        -------
124
        dict with str keys
125
            The test parameters dictionary.
126
        """
127
        import numpy as np
128
129
        params = super().get_test_params()
130
        experiment = params[0]["experiment"]
131
        more_params = {
132
            "experiment": experiment,
133
            "step_size": 3,
134
            "direction": "orthogonal",
135
            "search_space": {
136
                "C": [0.01, 0.1, 1, 10],
137
                "gamma": [0.0001, 0.01, 0.1, 1, 10],
138
            },
139
            "n_iter": 100,
140
        }
141
        params.append(more_params)
142
        return params
143