File: cma_sop.py

package info (click to toggle)
python-cmaes 0.12.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 544 kB
  • sloc: python: 5,136; sh: 88; makefile: 4
file content (196 lines) | stat: -rw-r--r-- 5,048 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import numpy as np
from cmaes.cmasop import CMASoP


def example1():
    """
    example with benchmark on sets of points
    """

    # number of total dimensions
    dim = 10

    # number of dimensions in each subspace
    subspace_dim = 2

    # number of points in each subspace
    point_num = 10

    # objective function
    def quadratic(x):
        coef = 1000 ** (np.arange(dim) / float(dim - 1))
        return np.sum((x * coef) ** 2)

    # sets_of_points (on [-5, 5])
    discrete_subspace_num = dim // subspace_dim
    sets_of_points = (
        2 * np.random.rand(discrete_subspace_num, point_num, subspace_dim) - 1
    ) * 5

    # add the optimal solution (for benchmark function)
    sets_of_points[:, -1] = np.zeros(subspace_dim)
    np.random.shuffle(sets_of_points)

    # optimizer (CMA-ES-SoP)
    optimizer = CMASoP(
        sets_of_points=sets_of_points,
        mean=np.random.rand(dim) * 4 + 1,
        sigma=2.0,
    )

    best_eval = np.inf
    eval_count = 0

    for generation in range(200):
        solutions = []
        for _ in range(optimizer.population_size):
            # Ask a parameter
            x, enc_x = optimizer.ask()
            value = quadratic(enc_x)

            # save best eval
            best_eval = np.min((best_eval, value))
            eval_count += 1

            solutions.append((x, value))

        # Tell evaluation values.
        optimizer.tell(solutions)

        print(f"#{generation} ({best_eval} {eval_count})")

        if best_eval < 1e-4 or optimizer.should_stop():
            break


def example2():
    """
    example with benchmark on mixed variable (sets of points and continuous variable)
    """

    # number of total dimensions
    dim = 10

    # number of dimensions in each subspace
    subspace_dim = 2

    # number of points in each subspace
    point_num = 10

    # objective function
    def quadratic(x):
        coef = 1000 ** (np.arange(dim) / float(dim - 1))
        return np.sum((x * coef) ** 2)

    # sets_of_points (on [-5, 5])
    # almost half of the subspaces are continuous spaces
    discrete_subspace_num = (dim // 2) // subspace_dim
    sets_of_points = (
        2 * np.random.rand(discrete_subspace_num, point_num, subspace_dim) - 1
    ) * 5

    # add the optimal solution (for benchmark function)
    sets_of_points[:, -1] = np.zeros(subspace_dim)
    np.random.shuffle(sets_of_points)

    # optimizer (CMA-ES-SoP)
    optimizer = CMASoP(
        sets_of_points=sets_of_points,
        mean=np.random.rand(dim) * 4 + 1,
        sigma=2.0,
    )

    best_eval = np.inf
    eval_count = 0

    for generation in range(200):
        solutions = []
        for _ in range(optimizer.population_size):
            # Ask a parameter
            x, enc_x = optimizer.ask()
            value = quadratic(enc_x)

            # save best eval
            best_eval = np.min((best_eval, value))
            eval_count += 1

            solutions.append((x, value))

        # Tell evaluation values.
        optimizer.tell(solutions)

        print(f"#{generation} ({best_eval} {eval_count})")

        if best_eval < 1e-4 or optimizer.should_stop():
            break


def example3():
    """
    example with benchmark on mixed variable
    (continuous variable and sets of points with different numbers of dimensions and points)
    """

    # numbers of dimensions in each subspace
    subspace_dim_list = [2, 3, 5]
    cont_dim = 10

    # numbers of points in each subspace
    point_num_list = [10, 20, 40]

    # number of total dimensions
    dim = int(np.sum(subspace_dim_list) + cont_dim)

    # objective function
    def quadratic(x):
        coef = 1000 ** (np.arange(dim) / float(dim - 1))
        return np.sum((coef * x) ** 2)

    # sets_of_points (on [-5, 5])
    discrete_subspace_num = len(subspace_dim_list)
    sets_of_points = [
        (2 * np.random.rand(point_num_list[i], subspace_dim_list[i]) - 1) * 5
        for i in range(discrete_subspace_num)
    ]

    # add the optimal solution (for benchmark function)
    for i in range(discrete_subspace_num):
        sets_of_points[i][-1] = np.zeros(subspace_dim_list[i])
        np.random.shuffle(sets_of_points[i])

    # optimizer (CMA-ES-SoP)
    optimizer = CMASoP(
        sets_of_points=sets_of_points,
        mean=np.random.rand(dim) * 4 + 1,
        sigma=2.0,
    )

    best_eval = np.inf
    eval_count = 0

    for generation in range(400):
        solutions = []
        for _ in range(optimizer.population_size):
            # Ask a parameter
            x, enc_x = optimizer.ask()
            value = quadratic(enc_x)

            # save best eval
            best_eval = np.min((best_eval, value))
            eval_count += 1

            solutions.append((x, value))

        # Tell evaluation values.
        optimizer.tell(solutions)

        print(f"#{generation} ({best_eval} {eval_count})")

        if best_eval < 1e-4 or optimizer.should_stop():
            break


if __name__ == "__main__":
    example1()
    example2()
    # example3()