如何使用 OptunaHub 实现您的基准问题(基础)

OptunaHub 提供了 optunahub.benchmarks 模块用于实现基准问题。在本教程中,我们将解释如何使用 optunahub.benchmarks 实现您自己的基准问题。

首先,导入 optuna 和其他必需的模块。

from __future__ import annotations

import optuna

from optunahub.benchmarks import BaseProblem

接下来,通过继承 BaseProblem 类定义您自己的问题类。这里,让我们实现一个简单的二维 sphere 函数。

您需要实现 BaseProblem 类中定义的以下方法。

  • search_space: 此方法返回问题的搜索空间字典。字典的每个元素由参数名称和分布组成(参见 optuna.distributions)。

  • directions: 此方法返回问题的优化方向(最小化或最大化)。返回类型是 optuna.study.direction 的列表。

  • evaluate: 此方法根据给定的输入参数字典评估目标函数。

class Sphere2D(BaseProblem):
    @property
    def search_space(self) -> dict[str, optuna.distributions.BaseDistribution]:
        return {
            "x0": optuna.distributions.FloatDistribution(low=-5, high=5),
            "x1": optuna.distributions.FloatDistribution(low=-5, high=5),
        }

    @property
    def directions(self) -> list[optuna.study.StudyDirection]:
        return [optuna.study.StudyDirection.MINIMIZE]

    def evaluate(self, params: dict[str, float]) -> float:
        return params["x0"] ** 2 + params["x1"] ** 2

由于 BaseProblem 提供了 __call__(self, trial: optuna.Trial) 的默认实现,该实现内部调用 evaluate 方法,因此问题实例可以直接用作 study.optimize 的目标函数。

sphere2d = Sphere2D()
study = optuna.create_study(directions=sphere2d.directions)
study.optimize(sphere2d, n_trials=20)

问题类的构造函数可以自定义以引入额外的属性。为了说明这一点,我们展示一个具有动态维度的 sphere 函数的示例。

class SphereND(BaseProblem):
    def __init__(self, dim: int) -> None:
        self.dim = dim

    @property
    def search_space(self) -> dict[str, optuna.distributions.BaseDistribution]:
        return {
            f"x{i}": optuna.distributions.FloatDistribution(low=-5, high=5)
            for i in range(self.dim)
        }

    @property
    def directions(self) -> list[optuna.study.StudyDirection]:
        return [optuna.study.StudyDirection.MINIMIZE]

    def evaluate(self, params: dict[str, float]) -> float:
        return sum(params[f"x{i}"] ** 2 for i in range(self.dim))


sphere3d = SphereND(dim=3)
study = optuna.create_study(directions=sphere3d.directions)
study.optimize(sphere3d, n_trials=20)

在实现您自己的基准问题后,您可以将其注册到 OptunaHub。请参见 如何将您的包注册到 OptunaHub,了解如何将您的基准问题注册到 OptunaHub。

如何使用 OptunaHub 实现您的基准问题(进阶) 中,我们将解释如何实现更复杂的基准问题,例如具有动态搜索空间的问题。

脚本总运行时间: (0 分 0.141 秒)

由 Sphinx-Gallery 生成的图库