cmaes


Namecmaes JSON
Version 0.10.0 PyPI version JSON
download
home_page
SummaryLightweight Covariance Matrix Adaptation Evolution Strategy (CMA-ES) implementation for Python 3.
upload_time2023-07-19 04:10:39
maintainer
docs_urlNone
author
requires_python>=3.7
licenseMIT License Copyright (c) 2020-2021 CyberAgent, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # CMA-ES

[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](./LICENSE) [![PyPI - Downloads](https://img.shields.io/pypi/dw/cmaes)](https://pypistats.org/packages/cmaes)

Lightweight Covariance Matrix Adaptation Evolution Strategy (CMA-ES) [1] implementation.

![visualize-six-hump-camel](https://user-images.githubusercontent.com/5564044/73486622-db5cff00-43e8-11ea-98fb-8246dbacab6d.gif)

## News
* **2023/05/23** Our paper, [M. Nomura, Y. Akimoto, and I. Ono, CMA-ES with Learning Rate Adaptation: Can CMA-ES with Default Population Size Solve Multimodal and Noisy Problems?](https://arxiv.org/abs/2304.03473), has been nominated for the Best Paper Award in the ENUM track at GECCO'23 :whale:
* **2023/04/01** Two papers have been accepted to GECCO'23 ENUM Track: (1) [M. Nomura, Y. Akimoto, and I. Ono, CMA-ES with Learning Rate Adaptation: Can CMA-ES with Default Population Size Solve Multimodal and Noisy Problems?](https://arxiv.org/abs/2304.03473), and (2) [Y. Watanabe, K. Uchida, R. Hamano, S. Saito, M. Nomura, and S. Shirakawa, (1+1)-CMA-ES with Margin for Discrete and Mixed-Integer Problems](https://arxiv.org/abs/2305.00849) :tada:
* **2022/05/13** The paper, ["CMA-ES with Margin: Lower-Bounding Marginal Probability for Mixed-Integer Black-Box Optimization"](https://arxiv.org/abs/2205.13482) written by Hamano, Saito, [@nomuramasahir0](https://github.com/nomuramasahir0) (the maintainer of this library), and Shirakawa, has been nominated as best paper at GECCO'22 ENUM track.
* **2021/03/10** ["Introduction to CMA-ES sampler"](https://medium.com/optuna/introduction-to-cma-es-sampler-ee68194c8f88) is published at Optuna Medium Blog. This article explains when and how to make the best use out of CMA-ES sampler. Please check it out!
* **2021/02/02** The paper ["Warm Starting CMA-ES for Hyperparameter Optimization"](https://arxiv.org/abs/2012.06932) written by [@nomuramasahir0](https://github.com/nomuramasahir0), the maintainer of this library, is accepted at AAAI 2021 :tada:
* **2020/07/29** Optuna's built-in CMA-ES sampler which uses this library under the hood is stabled at Optuna v2.0. Please check out the [v2.0 release blog](https://medium.com/optuna/optuna-v2-3165e3f1fc2).

## Installation

Supported Python versions are 3.7 or later.

```
$ pip install cmaes
```

Or you can install via [conda-forge](https://anaconda.org/conda-forge/cmaes).

```
$ conda install -c conda-forge cmaes
```

## Usage

This library provides an "ask-and-tell" style interface.

```python
import numpy as np
from cmaes import CMA

def quadratic(x1, x2):
    return (x1 - 3) ** 2 + (10 * (x2 + 2)) ** 2

if __name__ == "__main__":
    optimizer = CMA(mean=np.zeros(2), sigma=1.3)

    for generation in range(50):
        solutions = []
        for _ in range(optimizer.population_size):
            x = optimizer.ask()
            value = quadratic(x[0], x[1])
            solutions.append((x, value))
            print(f"#{generation} {value} (x1={x[0]}, x2 = {x[1]})")
        optimizer.tell(solutions)
```

And you can use this library via [Optuna](https://github.com/optuna/optuna) [2], an automatic hyperparameter optimization framework.
Optuna's built-in CMA-ES sampler which uses this library under the hood is available from [v1.3.0](https://github.com/optuna/optuna/releases/tag/v1.3.0) and stabled at [v2.0.0](https://github.com/optuna/optuna/releases/tag/v2.2.0).
See [the documentation](https://optuna.readthedocs.io/en/stable/reference/samplers/generated/optuna.samplers.CmaEsSampler.html) or [v2.0 release blog](https://medium.com/optuna/optuna-v2-3165e3f1fc2) for more details.

```python
import optuna

def objective(trial: optuna.Trial):
    x1 = trial.suggest_uniform("x1", -4, 4)
    x2 = trial.suggest_uniform("x2", -4, 4)
    return (x1 - 3) ** 2 + (10 * (x2 + 2)) ** 2

if __name__ == "__main__":
    sampler = optuna.samplers.CmaEsSampler()
    study = optuna.create_study(sampler=sampler)
    study.optimize(objective, n_trials=250)
```


## CMA-ES variants

#### CMA-ES with Margin [3]

CMA-ES with Margin introduces a lower bound on the marginal probability associated with each discrete dimension so that samples can avoid being fixed to a single point.
It can be applied to mixed spaces of continuous (float) and discrete (including integer and binary).

|CMA-ES|CMA-ESwM|
|---|---|
|![CMA-ES](https://raw.githubusercontent.com/EvoConJP/CMA-ES_with_Margin/main/fig/CMA-ES.gif)|![CMA-ESwM](https://raw.githubusercontent.com/EvoConJP/CMA-ES_with_Margin/main/fig/CMA-ESwM.gif)|

The above figures are taken from [EvoConJP/CMA-ES_with_Margin](https://github.com/EvoConJP/CMA-ES_with_Margin).

<details>
<summary>Source code</summary>

```python
import numpy as np
from cmaes import CMAwM


def ellipsoid_onemax(x, n_zdim):
    n = len(x)
    n_rdim = n - n_zdim
    r = 10
    if len(x) < 2:
        raise ValueError("dimension must be greater one")
    ellipsoid = sum([(1000 ** (i / (n_rdim - 1)) * x[i]) ** 2 for i in range(n_rdim)])
    onemax = n_zdim - (0.0 < x[(n - n_zdim) :]).sum()
    return ellipsoid + r * onemax


def main():
    binary_dim, continuous_dim = 10, 10
    dim = binary_dim + continuous_dim
    bounds = np.concatenate(
        [
            np.tile([-np.inf, np.inf], (continuous_dim, 1)),
            np.tile([0, 1], (binary_dim, 1)),
        ]
    )
    steps = np.concatenate([np.zeros(continuous_dim), np.ones(binary_dim)])
    optimizer = CMAwM(mean=np.zeros(dim), sigma=2.0, bounds=bounds, steps=steps)
    print(" evals    f(x)")
    print("======  ==========")

    evals = 0
    while True:
        solutions = []
        for _ in range(optimizer.population_size):
            x_for_eval, x_for_tell = optimizer.ask()
            value = ellipsoid_onemax(x_for_eval, binary_dim)
            evals += 1
            solutions.append((x_for_tell, value))
            if evals % 300 == 0:
                print(f"{evals:5d}  {value:10.5f}")
        optimizer.tell(solutions)

        if optimizer.should_stop():
            break


if __name__ == "__main__":
    main()
```

Source code is also available [here](./examples/cmaes_with_margin.py).

</details>

#### Warm Starting CMA-ES [4]

Warm Starting CMA-ES is a method to transfer prior knowledge on similar HPO tasks through the initialization of CMA-ES.
Here is the result of an experiment that tuning LightGBM for Kaggle's Toxic Comment Classification Challenge data, a multilabel classification dataset.
In this benchmark, we use 10% of a full dataset as the source task, and a full dataset as the target task.
Please refer [the paper](https://arxiv.org/abs/2012.06932) and/or https://github.com/c-bata/benchmark-warm-starting-cmaes for more details of experiment settings.

![benchmark-lightgbm-toxic](https://github.com/c-bata/benchmark-warm-starting-cmaes/raw/main/result.png)

<details>
<summary>Source code</summary>

```python
import numpy as np
from cmaes import CMA, get_warm_start_mgd

def source_task(x1: float, x2: float) -> float:
    b = 0.4
    return (x1 - b) ** 2 + (x2 - b) ** 2

def target_task(x1: float, x2: float) -> float:
    b = 0.6
    return (x1 - b) ** 2 + (x2 - b) ** 2

if __name__ == "__main__":
    # Generate solutions from a source task
    source_solutions = []
    for _ in range(1000):
        x = np.random.random(2)
        value = source_task(x[0], x[1])
        source_solutions.append((x, value))

    # Estimate a promising distribution of the source task,
    # then generate parameters of the multivariate gaussian distribution.
    ws_mean, ws_sigma, ws_cov = get_warm_start_mgd(
        source_solutions, gamma=0.1, alpha=0.1
    )
    optimizer = CMA(mean=ws_mean, sigma=ws_sigma, cov=ws_cov)

    # Run WS-CMA-ES
    print(" g    f(x1,x2)     x1      x2  ")
    print("===  ==========  ======  ======")
    while True:
        solutions = []
        for _ in range(optimizer.population_size):
            x = optimizer.ask()
            value = target_task(x[0], x[1])
            solutions.append((x, value))
            print(
                f"{optimizer.generation:3d}  {value:10.5f}"
                f"  {x[0]:6.2f}  {x[1]:6.2f}"
            )
        optimizer.tell(solutions)

        if optimizer.should_stop():
            break
```

The full source code is available [here](./examples/ws_cma_es.py).

</details>

#### Separable CMA-ES [5]

sep-CMA-ES is an algorithm which constrains the covariance matrix to be diagonal.
Due to the reduction of the number of parameters, the learning rate for the covariance matrix can be increased.
Consequently, this algorithm outperforms CMA-ES on separable functions.

<details>
<summary>Source code</summary>

```python
import numpy as np
from cmaes import SepCMA

def ellipsoid(x):
    n = len(x)
    if len(x) < 2:
        raise ValueError("dimension must be greater one")
    return sum([(1000 ** (i / (n - 1)) * x[i]) ** 2 for i in range(n)])

if __name__ == "__main__":
    dim = 40
    optimizer = SepCMA(mean=3 * np.ones(dim), sigma=2.0)
    print(" evals    f(x)")
    print("======  ==========")

    evals = 0
    while True:
        solutions = []
        for _ in range(optimizer.population_size):
            x = optimizer.ask()
            value = ellipsoid(x)
            evals += 1
            solutions.append((x, value))
            if evals % 3000 == 0:
                print(f"{evals:5d}  {value:10.5f}")
        optimizer.tell(solutions)

        if optimizer.should_stop():
            break
```

Full source code is available [here](./examples/sepcma_ellipsoid_function.py).

</details>

#### IPOP-CMA-ES [6]

IPOP-CMA-ES is a method to restart CMA-ES with increasing population size like below.

![visualize-ipop-cmaes-himmelblau](https://user-images.githubusercontent.com/5564044/88472274-f9e12480-cf4b-11ea-8aff-2a859eb51a15.gif)

<details>
<summary>Source code</summary>

```python
import math
import numpy as np
from cmaes import CMA

def ackley(x1, x2):
    # https://www.sfu.ca/~ssurjano/ackley.html
    return (
        -20 * math.exp(-0.2 * math.sqrt(0.5 * (x1 ** 2 + x2 ** 2)))
        - math.exp(0.5 * (math.cos(2 * math.pi * x1) + math.cos(2 * math.pi * x2)))
        + math.e + 20
    )

if __name__ == "__main__":
    bounds = np.array([[-32.768, 32.768], [-32.768, 32.768]])
    lower_bounds, upper_bounds = bounds[:, 0], bounds[:, 1]

    mean = lower_bounds + (np.random.rand(2) * (upper_bounds - lower_bounds))
    sigma = 32.768 * 2 / 5  # 1/5 of the domain width
    optimizer = CMA(mean=mean, sigma=sigma, bounds=bounds, seed=0)

    for generation in range(200):
        solutions = []
        for _ in range(optimizer.population_size):
            x = optimizer.ask()
            value = ackley(x[0], x[1])
            solutions.append((x, value))
            print(f"#{generation} {value} (x1={x[0]}, x2 = {x[1]})")
        optimizer.tell(solutions)

        if optimizer.should_stop():
            # popsize multiplied by 2 (or 3) before each restart.
            popsize = optimizer.population_size * 2
            mean = lower_bounds + (np.random.rand(2) * (upper_bounds - lower_bounds))
            optimizer = CMA(mean=mean, sigma=sigma, population_size=popsize)
            print(f"Restart CMA-ES with popsize={popsize}")
```

Full source code is available [here](./examples/ipop_cmaes.py).

</details>

#### BIPOP-CMA-ES [7]

BIPOP-CMA-ES applies two interlaced restart strategies, one with an increasing population size and one with varying small population sizes.

![visualize-bipop-cmaes-himmelblau](https://user-images.githubusercontent.com/5564044/88471815-55111800-cf48-11ea-8933-5a4b48c49eba.gif)

<details>
<summary>Source code</summary>

```python
import math
import numpy as np
from cmaes import CMA

def ackley(x1, x2):
    # https://www.sfu.ca/~ssurjano/ackley.html
    return (
        -20 * math.exp(-0.2 * math.sqrt(0.5 * (x1 ** 2 + x2 ** 2)))
        - math.exp(0.5 * (math.cos(2 * math.pi * x1) + math.cos(2 * math.pi * x2)))
        + math.e + 20
    )

if __name__ == "__main__":
    bounds = np.array([[-32.768, 32.768], [-32.768, 32.768]])
    lower_bounds, upper_bounds = bounds[:, 0], bounds[:, 1]

    mean = lower_bounds + (np.random.rand(2) * (upper_bounds - lower_bounds))
    sigma = 32.768 * 2 / 5  # 1/5 of the domain width
    optimizer = CMA(mean=mean, sigma=sigma, bounds=bounds, seed=0)

    n_restarts = 0  # A small restart doesn't count in the n_restarts
    small_n_eval, large_n_eval = 0, 0
    popsize0 = optimizer.population_size
    inc_popsize = 2

    # Initial run is with "normal" population size; it is
    # the large population before first doubling, but its
    # budget accounting is the same as in case of small
    # population.
    poptype = "small"

    for generation in range(200):
        solutions = []
        for _ in range(optimizer.population_size):
            x = optimizer.ask()
            value = ackley(x[0], x[1])
            solutions.append((x, value))
            print(f"#{generation} {value} (x1={x[0]}, x2 = {x[1]})")
        optimizer.tell(solutions)

        if optimizer.should_stop():
            n_eval = optimizer.population_size * optimizer.generation
            if poptype == "small":
                small_n_eval += n_eval
            else:  # poptype == "large"
                large_n_eval += n_eval

            if small_n_eval < large_n_eval:
                poptype = "small"
                popsize_multiplier = inc_popsize ** n_restarts
                popsize = math.floor(
                    popsize0 * popsize_multiplier ** (np.random.uniform() ** 2)
                )
            else:
                poptype = "large"
                n_restarts += 1
                popsize = popsize0 * (inc_popsize ** n_restarts)

            mean = lower_bounds + (np.random.rand(2) * (upper_bounds - lower_bounds))
            optimizer = CMA(
                mean=mean,
                sigma=sigma,
                bounds=bounds,
                population_size=popsize,
            )
            print("Restart CMA-ES with popsize={} ({})".format(popsize, poptype))
```

Full source code is available [here](./examples/bipop_cmaes.py).

</details>

## Benchmark results

| [Rosenbrock function](https://www.sfu.ca/~ssurjano/rosen.html) | [Six-Hump Camel function](https://www.sfu.ca/~ssurjano/camel6.html) |
| ------------------- | ----------------------- |
| ![rosenbrock](https://user-images.githubusercontent.com/5564044/73486735-0cd5ca80-43e9-11ea-9e6e-35028edf4ee8.png) | ![six-hump-camel](https://user-images.githubusercontent.com/5564044/73486738-0e9f8e00-43e9-11ea-8e65-d60fd5853b8d.png) |

This implementation (green) stands comparison with [pycma](https://github.com/CMA-ES/pycma) (blue).
See [benchmark](./benchmark) for details.

## Links

**Projects using cmaes:**

* [Optuna](https://github.com/optuna/optuna) : A hyperparameter optimization framework that supports CMA-ES using this library under the hood.
* (If you have a project which uses `cmaes` and want your own project to be listed here, please submit a GitHub issue.)

**Other libraries:**

I respect all libraries involved in CMA-ES.

* [pycma](https://github.com/CMA-ES/pycma) : Most famous CMA-ES implementation by Nikolaus Hansen.
* [pymoo](https://github.com/msu-coinlab/pymoo) : Multi-objective optimization in Python.
* [evojax](https://github.com/google/evojax) : EvoJAX provides a JAX-port of this library.
* [evosax](https://github.com/RobertTLange/evosax) : evosax provides JAX-based CMA-ES and sep-CMA-ES implementation, which is inspired by this library.

**References:**

* [1] [N. Hansen, The CMA Evolution Strategy: A Tutorial. arXiv:1604.00772, 2016.](https://arxiv.org/abs/1604.00772)
* [2] [T. Akiba, S. Sano, T. Yanase, T. Ohta, M. Koyama, Optuna: A Next-generation Hyperparameter Optimization Framework, KDD, 2019.](https://dl.acm.org/citation.cfm?id=3330701)
* [3] [R. Hamano, S. Saito, M. Nomura, S. Shirakawa, CMA-ES with Margin: Lower-Bounding Marginal Probability for Mixed-Integer Black-Box Optimization, GECCO, 2022.](https://arxiv.org/abs/2205.13482)
* [4] [M. Nomura, S. Watanabe, Y. Akimoto, Y. Ozaki, M. Onishi, Warm Starting CMA-ES for Hyperparameter Optimization, AAAI, 2021.](https://arxiv.org/abs/2012.06932)
* [5] [R. Ros, N. Hansen, A Simple Modification in CMA-ES Achieving Linear Time and Space Complexity, PPSN, 2008.](https://hal.inria.fr/inria-00287367/document)
* [6] [A. Auger, N. Hansen, A restart CMA evolution strategy with increasing population size, CEC, 2005.](https://sci2s.ugr.es/sites/default/files/files/TematicWebSites/EAMHCO/contributionsCEC05/auger05ARCMA.pdf)
* [7] [N. Hansen, Benchmarking a BI-Population CMA-ES on the BBOB-2009 Function Testbed, GECCO Workshop, 2009.](https://hal.inria.fr/inria-00382093/document)

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "cmaes",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": "Masahiro Nomura <nomura_masahiro@cyberagent.co.jp>",
    "keywords": "",
    "author": "",
    "author_email": "Masashi Shibata <m.shibata1020@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/33/75/56c6c7a608e6f10c802830acc448d4705a64a2cca38e9645b1faf07d6a9a/cmaes-0.10.0.tar.gz",
    "platform": null,
    "description": "# CMA-ES\n\n[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](./LICENSE) [![PyPI - Downloads](https://img.shields.io/pypi/dw/cmaes)](https://pypistats.org/packages/cmaes)\n\nLightweight Covariance Matrix Adaptation Evolution Strategy (CMA-ES) [1] implementation.\n\n![visualize-six-hump-camel](https://user-images.githubusercontent.com/5564044/73486622-db5cff00-43e8-11ea-98fb-8246dbacab6d.gif)\n\n## News\n* **2023/05/23** Our paper, [M. Nomura, Y. Akimoto, and I. Ono, CMA-ES with Learning Rate Adaptation: Can CMA-ES with Default Population Size Solve Multimodal and Noisy Problems?](https://arxiv.org/abs/2304.03473), has been nominated for the Best Paper Award in the ENUM track at GECCO'23 :whale:\n* **2023/04/01** Two papers have been accepted to GECCO'23 ENUM Track: (1) [M. Nomura, Y. Akimoto, and I. Ono, CMA-ES with Learning Rate Adaptation: Can CMA-ES with Default Population Size Solve Multimodal and Noisy Problems?](https://arxiv.org/abs/2304.03473), and (2) [Y. Watanabe, K. Uchida, R. Hamano, S. Saito, M. Nomura, and S. Shirakawa, (1+1)-CMA-ES with Margin for Discrete and Mixed-Integer Problems](https://arxiv.org/abs/2305.00849) :tada:\n* **2022/05/13** The paper, [\"CMA-ES with Margin: Lower-Bounding Marginal Probability for Mixed-Integer Black-Box Optimization\"](https://arxiv.org/abs/2205.13482) written by Hamano, Saito, [@nomuramasahir0](https://github.com/nomuramasahir0) (the maintainer of this library), and Shirakawa, has been nominated as best paper at GECCO'22 ENUM track.\n* **2021/03/10** [\"Introduction to CMA-ES sampler\"](https://medium.com/optuna/introduction-to-cma-es-sampler-ee68194c8f88) is published at Optuna Medium Blog. This article explains when and how to make the best use out of CMA-ES sampler. Please check it out!\n* **2021/02/02** The paper [\"Warm Starting CMA-ES for Hyperparameter Optimization\"](https://arxiv.org/abs/2012.06932) written by [@nomuramasahir0](https://github.com/nomuramasahir0), the maintainer of this library, is accepted at AAAI 2021 :tada:\n* **2020/07/29** Optuna's built-in CMA-ES sampler which uses this library under the hood is stabled at Optuna v2.0. Please check out the [v2.0 release blog](https://medium.com/optuna/optuna-v2-3165e3f1fc2).\n\n## Installation\n\nSupported Python versions are 3.7 or later.\n\n```\n$ pip install cmaes\n```\n\nOr you can install via [conda-forge](https://anaconda.org/conda-forge/cmaes).\n\n```\n$ conda install -c conda-forge cmaes\n```\n\n## Usage\n\nThis library provides an \"ask-and-tell\" style interface.\n\n```python\nimport numpy as np\nfrom cmaes import CMA\n\ndef quadratic(x1, x2):\n    return (x1 - 3) ** 2 + (10 * (x2 + 2)) ** 2\n\nif __name__ == \"__main__\":\n    optimizer = CMA(mean=np.zeros(2), sigma=1.3)\n\n    for generation in range(50):\n        solutions = []\n        for _ in range(optimizer.population_size):\n            x = optimizer.ask()\n            value = quadratic(x[0], x[1])\n            solutions.append((x, value))\n            print(f\"#{generation} {value} (x1={x[0]}, x2 = {x[1]})\")\n        optimizer.tell(solutions)\n```\n\nAnd you can use this library via [Optuna](https://github.com/optuna/optuna) [2], an automatic hyperparameter optimization framework.\nOptuna's built-in CMA-ES sampler which uses this library under the hood is available from [v1.3.0](https://github.com/optuna/optuna/releases/tag/v1.3.0) and stabled at [v2.0.0](https://github.com/optuna/optuna/releases/tag/v2.2.0).\nSee [the documentation](https://optuna.readthedocs.io/en/stable/reference/samplers/generated/optuna.samplers.CmaEsSampler.html) or [v2.0 release blog](https://medium.com/optuna/optuna-v2-3165e3f1fc2) for more details.\n\n```python\nimport optuna\n\ndef objective(trial: optuna.Trial):\n    x1 = trial.suggest_uniform(\"x1\", -4, 4)\n    x2 = trial.suggest_uniform(\"x2\", -4, 4)\n    return (x1 - 3) ** 2 + (10 * (x2 + 2)) ** 2\n\nif __name__ == \"__main__\":\n    sampler = optuna.samplers.CmaEsSampler()\n    study = optuna.create_study(sampler=sampler)\n    study.optimize(objective, n_trials=250)\n```\n\n\n## CMA-ES variants\n\n#### CMA-ES with Margin [3]\n\nCMA-ES with Margin introduces a lower bound on the marginal probability associated with each discrete dimension so that samples can avoid being fixed to a single point.\nIt can be applied to mixed spaces of continuous (float) and discrete (including integer and binary).\n\n|CMA-ES|CMA-ESwM|\n|---|---|\n|![CMA-ES](https://raw.githubusercontent.com/EvoConJP/CMA-ES_with_Margin/main/fig/CMA-ES.gif)|![CMA-ESwM](https://raw.githubusercontent.com/EvoConJP/CMA-ES_with_Margin/main/fig/CMA-ESwM.gif)|\n\nThe above figures are taken from [EvoConJP/CMA-ES_with_Margin](https://github.com/EvoConJP/CMA-ES_with_Margin).\n\n<details>\n<summary>Source code</summary>\n\n```python\nimport numpy as np\nfrom cmaes import CMAwM\n\n\ndef ellipsoid_onemax(x, n_zdim):\n    n = len(x)\n    n_rdim = n - n_zdim\n    r = 10\n    if len(x) < 2:\n        raise ValueError(\"dimension must be greater one\")\n    ellipsoid = sum([(1000 ** (i / (n_rdim - 1)) * x[i]) ** 2 for i in range(n_rdim)])\n    onemax = n_zdim - (0.0 < x[(n - n_zdim) :]).sum()\n    return ellipsoid + r * onemax\n\n\ndef main():\n    binary_dim, continuous_dim = 10, 10\n    dim = binary_dim + continuous_dim\n    bounds = np.concatenate(\n        [\n            np.tile([-np.inf, np.inf], (continuous_dim, 1)),\n            np.tile([0, 1], (binary_dim, 1)),\n        ]\n    )\n    steps = np.concatenate([np.zeros(continuous_dim), np.ones(binary_dim)])\n    optimizer = CMAwM(mean=np.zeros(dim), sigma=2.0, bounds=bounds, steps=steps)\n    print(\" evals    f(x)\")\n    print(\"======  ==========\")\n\n    evals = 0\n    while True:\n        solutions = []\n        for _ in range(optimizer.population_size):\n            x_for_eval, x_for_tell = optimizer.ask()\n            value = ellipsoid_onemax(x_for_eval, binary_dim)\n            evals += 1\n            solutions.append((x_for_tell, value))\n            if evals % 300 == 0:\n                print(f\"{evals:5d}  {value:10.5f}\")\n        optimizer.tell(solutions)\n\n        if optimizer.should_stop():\n            break\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\nSource code is also available [here](./examples/cmaes_with_margin.py).\n\n</details>\n\n#### Warm Starting CMA-ES [4]\n\nWarm Starting CMA-ES is a method to transfer prior knowledge on similar HPO tasks through the initialization of CMA-ES.\nHere is the result of an experiment that tuning LightGBM for Kaggle's Toxic Comment Classification Challenge data, a multilabel classification dataset.\nIn this benchmark, we use 10% of a full dataset as the source task, and a full dataset as the target task.\nPlease refer [the paper](https://arxiv.org/abs/2012.06932) and/or https://github.com/c-bata/benchmark-warm-starting-cmaes for more details of experiment settings.\n\n![benchmark-lightgbm-toxic](https://github.com/c-bata/benchmark-warm-starting-cmaes/raw/main/result.png)\n\n<details>\n<summary>Source code</summary>\n\n```python\nimport numpy as np\nfrom cmaes import CMA, get_warm_start_mgd\n\ndef source_task(x1: float, x2: float) -> float:\n    b = 0.4\n    return (x1 - b) ** 2 + (x2 - b) ** 2\n\ndef target_task(x1: float, x2: float) -> float:\n    b = 0.6\n    return (x1 - b) ** 2 + (x2 - b) ** 2\n\nif __name__ == \"__main__\":\n    # Generate solutions from a source task\n    source_solutions = []\n    for _ in range(1000):\n        x = np.random.random(2)\n        value = source_task(x[0], x[1])\n        source_solutions.append((x, value))\n\n    # Estimate a promising distribution of the source task,\n    # then generate parameters of the multivariate gaussian distribution.\n    ws_mean, ws_sigma, ws_cov = get_warm_start_mgd(\n        source_solutions, gamma=0.1, alpha=0.1\n    )\n    optimizer = CMA(mean=ws_mean, sigma=ws_sigma, cov=ws_cov)\n\n    # Run WS-CMA-ES\n    print(\" g    f(x1,x2)     x1      x2  \")\n    print(\"===  ==========  ======  ======\")\n    while True:\n        solutions = []\n        for _ in range(optimizer.population_size):\n            x = optimizer.ask()\n            value = target_task(x[0], x[1])\n            solutions.append((x, value))\n            print(\n                f\"{optimizer.generation:3d}  {value:10.5f}\"\n                f\"  {x[0]:6.2f}  {x[1]:6.2f}\"\n            )\n        optimizer.tell(solutions)\n\n        if optimizer.should_stop():\n            break\n```\n\nThe full source code is available [here](./examples/ws_cma_es.py).\n\n</details>\n\n#### Separable CMA-ES [5]\n\nsep-CMA-ES is an algorithm which constrains the covariance matrix to be diagonal.\nDue to the reduction of the number of parameters, the learning rate for the covariance matrix can be increased.\nConsequently, this algorithm outperforms CMA-ES on separable functions.\n\n<details>\n<summary>Source code</summary>\n\n```python\nimport numpy as np\nfrom cmaes import SepCMA\n\ndef ellipsoid(x):\n    n = len(x)\n    if len(x) < 2:\n        raise ValueError(\"dimension must be greater one\")\n    return sum([(1000 ** (i / (n - 1)) * x[i]) ** 2 for i in range(n)])\n\nif __name__ == \"__main__\":\n    dim = 40\n    optimizer = SepCMA(mean=3 * np.ones(dim), sigma=2.0)\n    print(\" evals    f(x)\")\n    print(\"======  ==========\")\n\n    evals = 0\n    while True:\n        solutions = []\n        for _ in range(optimizer.population_size):\n            x = optimizer.ask()\n            value = ellipsoid(x)\n            evals += 1\n            solutions.append((x, value))\n            if evals % 3000 == 0:\n                print(f\"{evals:5d}  {value:10.5f}\")\n        optimizer.tell(solutions)\n\n        if optimizer.should_stop():\n            break\n```\n\nFull source code is available [here](./examples/sepcma_ellipsoid_function.py).\n\n</details>\n\n#### IPOP-CMA-ES [6]\n\nIPOP-CMA-ES is a method to restart CMA-ES with increasing population size like below.\n\n![visualize-ipop-cmaes-himmelblau](https://user-images.githubusercontent.com/5564044/88472274-f9e12480-cf4b-11ea-8aff-2a859eb51a15.gif)\n\n<details>\n<summary>Source code</summary>\n\n```python\nimport math\nimport numpy as np\nfrom cmaes import CMA\n\ndef ackley(x1, x2):\n    # https://www.sfu.ca/~ssurjano/ackley.html\n    return (\n        -20 * math.exp(-0.2 * math.sqrt(0.5 * (x1 ** 2 + x2 ** 2)))\n        - math.exp(0.5 * (math.cos(2 * math.pi * x1) + math.cos(2 * math.pi * x2)))\n        + math.e + 20\n    )\n\nif __name__ == \"__main__\":\n    bounds = np.array([[-32.768, 32.768], [-32.768, 32.768]])\n    lower_bounds, upper_bounds = bounds[:, 0], bounds[:, 1]\n\n    mean = lower_bounds + (np.random.rand(2) * (upper_bounds - lower_bounds))\n    sigma = 32.768 * 2 / 5  # 1/5 of the domain width\n    optimizer = CMA(mean=mean, sigma=sigma, bounds=bounds, seed=0)\n\n    for generation in range(200):\n        solutions = []\n        for _ in range(optimizer.population_size):\n            x = optimizer.ask()\n            value = ackley(x[0], x[1])\n            solutions.append((x, value))\n            print(f\"#{generation} {value} (x1={x[0]}, x2 = {x[1]})\")\n        optimizer.tell(solutions)\n\n        if optimizer.should_stop():\n            # popsize multiplied by 2 (or 3) before each restart.\n            popsize = optimizer.population_size * 2\n            mean = lower_bounds + (np.random.rand(2) * (upper_bounds - lower_bounds))\n            optimizer = CMA(mean=mean, sigma=sigma, population_size=popsize)\n            print(f\"Restart CMA-ES with popsize={popsize}\")\n```\n\nFull source code is available [here](./examples/ipop_cmaes.py).\n\n</details>\n\n#### BIPOP-CMA-ES [7]\n\nBIPOP-CMA-ES applies two interlaced restart strategies, one with an increasing population size and one with varying small population sizes.\n\n![visualize-bipop-cmaes-himmelblau](https://user-images.githubusercontent.com/5564044/88471815-55111800-cf48-11ea-8933-5a4b48c49eba.gif)\n\n<details>\n<summary>Source code</summary>\n\n```python\nimport math\nimport numpy as np\nfrom cmaes import CMA\n\ndef ackley(x1, x2):\n    # https://www.sfu.ca/~ssurjano/ackley.html\n    return (\n        -20 * math.exp(-0.2 * math.sqrt(0.5 * (x1 ** 2 + x2 ** 2)))\n        - math.exp(0.5 * (math.cos(2 * math.pi * x1) + math.cos(2 * math.pi * x2)))\n        + math.e + 20\n    )\n\nif __name__ == \"__main__\":\n    bounds = np.array([[-32.768, 32.768], [-32.768, 32.768]])\n    lower_bounds, upper_bounds = bounds[:, 0], bounds[:, 1]\n\n    mean = lower_bounds + (np.random.rand(2) * (upper_bounds - lower_bounds))\n    sigma = 32.768 * 2 / 5  # 1/5 of the domain width\n    optimizer = CMA(mean=mean, sigma=sigma, bounds=bounds, seed=0)\n\n    n_restarts = 0  # A small restart doesn't count in the n_restarts\n    small_n_eval, large_n_eval = 0, 0\n    popsize0 = optimizer.population_size\n    inc_popsize = 2\n\n    # Initial run is with \"normal\" population size; it is\n    # the large population before first doubling, but its\n    # budget accounting is the same as in case of small\n    # population.\n    poptype = \"small\"\n\n    for generation in range(200):\n        solutions = []\n        for _ in range(optimizer.population_size):\n            x = optimizer.ask()\n            value = ackley(x[0], x[1])\n            solutions.append((x, value))\n            print(f\"#{generation} {value} (x1={x[0]}, x2 = {x[1]})\")\n        optimizer.tell(solutions)\n\n        if optimizer.should_stop():\n            n_eval = optimizer.population_size * optimizer.generation\n            if poptype == \"small\":\n                small_n_eval += n_eval\n            else:  # poptype == \"large\"\n                large_n_eval += n_eval\n\n            if small_n_eval < large_n_eval:\n                poptype = \"small\"\n                popsize_multiplier = inc_popsize ** n_restarts\n                popsize = math.floor(\n                    popsize0 * popsize_multiplier ** (np.random.uniform() ** 2)\n                )\n            else:\n                poptype = \"large\"\n                n_restarts += 1\n                popsize = popsize0 * (inc_popsize ** n_restarts)\n\n            mean = lower_bounds + (np.random.rand(2) * (upper_bounds - lower_bounds))\n            optimizer = CMA(\n                mean=mean,\n                sigma=sigma,\n                bounds=bounds,\n                population_size=popsize,\n            )\n            print(\"Restart CMA-ES with popsize={} ({})\".format(popsize, poptype))\n```\n\nFull source code is available [here](./examples/bipop_cmaes.py).\n\n</details>\n\n## Benchmark results\n\n| [Rosenbrock function](https://www.sfu.ca/~ssurjano/rosen.html) | [Six-Hump Camel function](https://www.sfu.ca/~ssurjano/camel6.html) |\n| ------------------- | ----------------------- |\n| ![rosenbrock](https://user-images.githubusercontent.com/5564044/73486735-0cd5ca80-43e9-11ea-9e6e-35028edf4ee8.png) | ![six-hump-camel](https://user-images.githubusercontent.com/5564044/73486738-0e9f8e00-43e9-11ea-8e65-d60fd5853b8d.png) |\n\nThis implementation (green) stands comparison with [pycma](https://github.com/CMA-ES/pycma) (blue).\nSee [benchmark](./benchmark) for details.\n\n## Links\n\n**Projects using cmaes:**\n\n* [Optuna](https://github.com/optuna/optuna) : A hyperparameter optimization framework that supports CMA-ES using this library under the hood.\n* (If you have a project which uses `cmaes` and want your own project to be listed here, please submit a GitHub issue.)\n\n**Other libraries:**\n\nI respect all libraries involved in CMA-ES.\n\n* [pycma](https://github.com/CMA-ES/pycma) : Most famous CMA-ES implementation by Nikolaus Hansen.\n* [pymoo](https://github.com/msu-coinlab/pymoo) : Multi-objective optimization in Python.\n* [evojax](https://github.com/google/evojax) : EvoJAX provides a JAX-port of this library.\n* [evosax](https://github.com/RobertTLange/evosax) : evosax provides JAX-based CMA-ES and sep-CMA-ES implementation, which is inspired by this library.\n\n**References:**\n\n* [1] [N. Hansen, The CMA Evolution Strategy: A Tutorial. arXiv:1604.00772, 2016.](https://arxiv.org/abs/1604.00772)\n* [2] [T. Akiba, S. Sano, T. Yanase, T. Ohta, M. Koyama, Optuna: A Next-generation Hyperparameter Optimization Framework, KDD, 2019.](https://dl.acm.org/citation.cfm?id=3330701)\n* [3] [R. Hamano, S. Saito, M. Nomura, S. Shirakawa, CMA-ES with Margin: Lower-Bounding Marginal Probability for Mixed-Integer Black-Box Optimization, GECCO, 2022.](https://arxiv.org/abs/2205.13482)\n* [4] [M. Nomura, S. Watanabe, Y. Akimoto, Y. Ozaki, M. Onishi, Warm Starting CMA-ES for Hyperparameter Optimization, AAAI, 2021.](https://arxiv.org/abs/2012.06932)\n* [5] [R. Ros, N. Hansen, A Simple Modification in CMA-ES Achieving Linear Time and Space Complexity, PPSN, 2008.](https://hal.inria.fr/inria-00287367/document)\n* [6] [A. Auger, N. Hansen, A restart CMA evolution strategy with increasing population size, CEC, 2005.](https://sci2s.ugr.es/sites/default/files/files/TematicWebSites/EAMHCO/contributionsCEC05/auger05ARCMA.pdf)\n* [7] [N. Hansen, Benchmarking a BI-Population CMA-ES on the BBOB-2009 Function Testbed, GECCO Workshop, 2009.](https://hal.inria.fr/inria-00382093/document)\n",
    "bugtrack_url": null,
    "license": "MIT License  Copyright (c) 2020-2021 CyberAgent, Inc.  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ",
    "summary": "Lightweight Covariance Matrix Adaptation Evolution Strategy (CMA-ES) implementation for Python 3.",
    "version": "0.10.0",
    "project_urls": {
        "Homepage": "https://github.com/CyberAgentAILab/cmaes"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f7467d9544d453346f6c0c405916c95fdb653491ea2e9976cabb810ba2fe8cd4",
                "md5": "86347a2022622e0a2d85e3815c7e9b0c",
                "sha256": "72cea747ad37b1780b0eb6f3c098cee33907fafbf6690c0c02db1e010cab72f6"
            },
            "downloads": -1,
            "filename": "cmaes-0.10.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "86347a2022622e0a2d85e3815c7e9b0c",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 29950,
            "upload_time": "2023-07-19T04:10:38",
            "upload_time_iso_8601": "2023-07-19T04:10:38.145390Z",
            "url": "https://files.pythonhosted.org/packages/f7/46/7d9544d453346f6c0c405916c95fdb653491ea2e9976cabb810ba2fe8cd4/cmaes-0.10.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "337556c6c7a608e6f10c802830acc448d4705a64a2cca38e9645b1faf07d6a9a",
                "md5": "4faed20691db6bbc92ab3d4569ae9433",
                "sha256": "48afc70df027114739872b50489ae6b32461c307b92d084a63c7090a9742faf9"
            },
            "downloads": -1,
            "filename": "cmaes-0.10.0.tar.gz",
            "has_sig": false,
            "md5_digest": "4faed20691db6bbc92ab3d4569ae9433",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 29081,
            "upload_time": "2023-07-19T04:10:39",
            "upload_time_iso_8601": "2023-07-19T04:10:39.688607Z",
            "url": "https://files.pythonhosted.org/packages/33/75/56c6c7a608e6f10c802830acc448d4705a64a2cca38e9645b1faf07d6a9a/cmaes-0.10.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-07-19 04:10:39",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "CyberAgentAILab",
    "github_project": "cmaes",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "cmaes"
}
        
Elapsed time: 0.08983s