Passed
Push — master ( 4a40b1...18f8a0 )
by Simon
01:39
created

BaseExperiment.evaluate()   A

Complexity

Conditions 2

Size

Total Lines 21
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 21
rs 10
c 0
b 0
f 0
cc 2
nop 2
1
"""Base class for experiment."""
2
# copyright: hyperactive developers, MIT License (see LICENSE file)
3
4
import numpy as np
5
from skbase.base import BaseObject
6
7
8
class BaseExperiment(BaseObject):
9
    """Base class for experiment."""
10
11
    _tags = {
12
        "object_type": "experiment",
13
        "python_dependencies": None,
14
        "property:randomness": "random",  # random or deterministic
15
        # if deterministic, two calls of score will result in the same value
16
        # random = two calls may result in different values; same as "stochastic"
17
        "property:higher_or_lower_is_better": "higher",  # "higher", "lower", "mixed"
18
        # whether higher or lower scores are better
19
    }
20
21
    def __init__(self):
22
        super().__init__()
23
24
    def __call__(self, **kwargs):
25
        """Score parameters, with kwargs call. Same as score call."""
26
        score, _ = self.score(kwargs)
27
        return score
28
29
    @property
30
    def __name__(self):
31
        return type(self).__name__
32
33
    def paramnames(self):
34
        """Return the parameter names of the search.
35
36
        Returns
37
        -------
38
        list of str
39
            The parameter names of the search parameters.
40
        """
41
        return self._paramnames()
42
43
    def _paramnames(self):
44
        """Return the parameter names of the search.
45
46
        Returns
47
        -------
48
        list of str
49
            The parameter names of the search parameters.
50
        """
51
        raise NotImplementedError
52
53
    def evaluate(self, params):
54
        """Evaluate the parameters.
55
56
        Parameters
57
        ----------
58
        params : dict with string keys
59
            Parameters to evaluate.
60
61
        Returns
62
        -------
63
        float
64
            The value of the parameters as per evaluation.
65
        dict
66
            Additional metadata about the search.
67
        """
68
        paramnames = self.paramnames()
69
        if not set(params.keys()) <= set(paramnames):
70
            raise ValueError("Parameters do not match.")
71
        res, metadata = self._evaluate(params)
72
        res = np.float64(res)
73
        return res, metadata
74
75
    def _evaluate(self, params):
76
        """Evaluate the parameters.
77
78
        Parameters
79
        ----------
80
        params : dict with string keys
81
            Parameters to evaluate.
82
83
        Returns
84
        -------
85
        float
86
            The value of the parameters as per evaluation.
87
        dict
88
            Additional metadata about the search.
89
        """
90
        raise NotImplementedError
91
92
    def score(self, params):
93
        """Score the parameters - with sign such that higher is always better.
94
95
        Same as ``evaluate`` call except for the sign chosen so that higher is better.
96
97
        If the tag ``property:higher_or_lower_is_better`` is set to
98
        ``"lower"``, the result is ``-self.evaluate(params)``.
99
100
        If the tag is set to ``"higher"``, the result is
101
        identical to ``self.evaluate(params)``.
102
103
        Parameters
104
        ----------
105
        params : dict with string keys
106
            Parameters to score.
107
108
        Returns
109
        -------
110
        float
111
            The score of the parameters.
112
        dict
113
            Additional metadata about the search.
114
        """
115
        hib = self.get_tag("property:higher_or_lower_is_better", "lower")
116
        if hib == "higher":
117
            sign = 1
118
        elif hib == "lower":
119
            sign = -1
120
121
        eval_res = self.evaluate(params)
122
        value = eval_res[0]
123
        metadata = eval_res[1]
124
125
        return sign * value, metadata
0 ignored issues
show
introduced by
The variable sign does not seem to be defined for all execution paths.
Loading history...
126