Ackley._evaluate()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 25
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 25
rs 10
c 0
b 0
f 0
cc 1
nop 2
1
"""Ackley function, common benchmark for optimization algorithms."""
2
# copyright: hyperactive developers, MIT License (see LICENSE file)
3
4
import numpy as np
5
6
from hyperactive.base import BaseExperiment
7
8
9
class Ackley(BaseExperiment):
10
    """Ackley class."""
11
12
    r"""Ackley function, common benchmark for optimization algorithms.
13
14
    The Ackley function is a non-convex function used to test optimization algorithms.
15
    It is defined as:
16
17
    .. math::
18
        f(x) = -a \cdot \exp(-\frac{b}{\sqrt{d}\left\|x\right\|}) - \exp(\frac{1}{d} \sum_{i=1}^d\cos (c x_i) ) + a + \exp(1)
19
20
    where :math:`a` (= `a`), :math:`b` (= `b`), and :math:`c` (= `c`) are constants,
21
    :math:`d` (= `d`) is the number of dimensions of the real input vector :math:`x`,
22
    and :math:`\left\|x\right\|` is the Euclidean norm of the vector :math:`x`.
23
24
    The components of the function argument :math:`x`
25
    are the input variables of the `score` method,
26
    and are set as `x0`, `x1`, ..., `x[d]` respectively.
27
28
    Parameters
29
    ----------
30
    a : float, optional, default=20
31
        Amplitude constant used in the calculation of the Ackley function.
32
    b : float, optional, default=0.2
33
        Decay constant used in the calculation of the Ackley function.
34
    c : float, optional, default=2*pi
35
        Frequency constant used in the calculation of the Ackley function.
36
    d : int, optional, default=2
37
        Number of dimensions for the Ackley function. The default is 2.
38
39
    Example
40
    -------
41
    >>> from hyperactive.experiment.toy import Ackley
42
    >>> ackley = Ackley(a=20)
43
    >>> params = {"x0": 1, "x1": 2}
44
    >>> score, add_info = ackley.score(params)
45
46
    Quick call without metadata return or dictionary:
47
    >>> score = ackley(x0=1, x1=2)
48
    """  # noqa: E501
49
50
    _tags = {
51
        "property:randomness": "deterministic",  # random or deterministic
52
        # if deterministic, two calls of score will result in the same value
53
        # random = two calls may result in different values; same as "stochastic"
54
        "property:higher_or_lower_is_better": "lower",
55
        # values are "higher", "lower", "mixed"
56
        # whether higher or lower scores are better
57
    }
58
59
    def __init__(self, a=20, b=0.2, c=2 * np.pi, d=2):
60
        self.a = a
61
        self.b = b
62
        self.c = c
63
        self.d = d
64
        super().__init__()
65
66
    def _paramnames(self):
67
        return [f"x{i}" for i in range(self.d)]
68
69
    def _evaluate(self, params):
70
        """Evaluate the parameters.
71
72
        Parameters
73
        ----------
74
        params : dict with string keys
75
            Parameters to evaluate.
76
77
        Returns
78
        -------
79
        float
80
            The value of the parameters as per evaluation.
81
        dict
82
            Additional metadata about the search.
83
        """
84
        x_vec = np.array([params[f"x{i}"] for i in range(self.d)])
85
86
        loss1 = -self.a * np.exp(-self.b * np.sqrt(np.sum(x_vec**2) / self.d))
87
        loss2 = -np.exp(np.sum(np.cos(self.c * x_vec)) / self.d)
88
        loss3 = np.exp(1)
89
        loss4 = self.a
90
91
        loss = loss1 + loss2 + loss3 + loss4
92
93
        return loss, {}
94
95
    @classmethod
96
    def get_test_params(cls, parameter_set="default"):
97
        """Return testing parameter settings for the skbase object.
98
99
        ``get_test_params`` is a unified interface point to store
100
        parameter settings for testing purposes. This function is also
101
        used in ``create_test_instance`` and ``create_test_instances_and_names``
102
        to construct test instances.
103
104
        ``get_test_params`` should return a single ``dict``, or a ``list`` of ``dict``.
105
106
        Each ``dict`` is a parameter configuration for testing,
107
        and can be used to construct an "interesting" test instance.
108
        A call to ``cls(**params)`` should
109
        be valid for all dictionaries ``params`` in the return of ``get_test_params``.
110
111
        The ``get_test_params`` need not return fixed lists of dictionaries,
112
        it can also return dynamic or stochastic parameter settings.
113
114
        Parameters
115
        ----------
116
        parameter_set : str, default="default"
117
            Name of the set of test parameters to return, for use in tests. If no
118
            special parameters are defined for a value, will return `"default"` set.
119
120
        Returns
121
        -------
122
        params : dict or list of dict, default = {}
123
            Parameters to create testing instances of the class
124
            Each dict are parameters to construct an "interesting" test instance, i.e.,
125
            `MyClass(**params)` or `MyClass(**params[i])` creates a valid test instance.
126
            `create_test_instance` uses the first (or only) dictionary in `params`
127
        """
128
        return [{"a": 0}, {"a": 20, "d": 42}, {"a": -42, "b": 0.5, "c": 1, "d": 10}]
129
130
    @classmethod
131
    def _get_score_params(self):
132
        """Return settings for testing score/evaluate functions. Used in tests only.
133
134
        Returns a list, the i-th element should be valid arguments for
135
        self.evaluate and self.score, of an instance constructed with
136
        self.get_test_params()[i].
137
138
        Returns
139
        -------
140
        list of dict
141
            The parameters to be used for scoring.
142
        """
143
        params0 = {"x0": 0, "x1": 0}
144
        params1 = {f"x{i}": i + 3 for i in range(42)}
145
        params2 = {f"x{i}": i**2 for i in range(10)}
146
        return [params0, params1, params2]
147