跳到内容

场景

smac.场景 #

场景 dataclass #

Scenario(
    configspace: ConfigurationSpace,
    name: str | None = None,
    output_directory: Path = Path("smac3_output"),
    deterministic: bool = False,
    objectives: str | list[str] = "cost",
    crash_cost: float | list[float] = inf,
    termination_cost_threshold: float | list[float] = inf,
    walltime_limit: float = inf,
    cputime_limit: float = inf,
    trial_walltime_limit: float | None = None,
    trial_memory_limit: int | None = None,
    n_trials: int = 100,
    use_default_config: bool = False,
    instances: list[str] | None = None,
    instance_features: dict[str, list[float]] | None = None,
    min_budget: float | int | None = None,
    max_budget: float | int | None = None,
    seed: int = 0,
    n_workers: int = 1,
)

场景管理环境变量,因此提供了优化执行的上下文框架。

参数#

configspace : ConfigurationSpace 用于从中采样配置的配置空间。 name : str | None,默认为 None 运行的名称。如果未传递名称,SMAC 将根据元数据生成一个哈希值。指定此参数可方便地识别您的运行。 output_directory : Path,默认为 Path("smac3_output") 保存输出的目录。文件保存在 ./output_directory/name/seed 中。 deterministic : bool,默认为 False 如果 deterministic 设置为 true,则只向目标函数传递一个种子。否则,将向目标函数传递多个种子(如果强化器的 n_seeds 大于 1),以确保泛化。 objectives : str | list[str] | None,默认为 "cost" 要优化的目标(s)。多目标优化需要此参数。 crash_cost : float | list[float],默认为 np.inf 定义失败试验的成本。在多目标情况下,每个目标可以关联不同的成本。 termination_cost_threshold : float | list[float],默认为 np.inf 定义优化应停止的成本阈值。在多目标情况下,每个目标必须关联一个成本。当所有目标都超过阈值时,优化停止。 walltime_limit : float,默认为 np.inf SMAC 允许运行的最大时间(秒)。 cputime_limit : float,默认为 np.inf SMAC 允许运行的最大 CPU 时间(秒)。 trial_walltime_limit : float | None,默认为 None 试验允许运行的最大时间(秒)。如果未指定,则不强制任何约束。否则,将由 pynisher 启动进程。 trial_memory_limit : int | None,默认为 None 试验允许使用的最大内存(MB)。如果未指定,则不强制任何约束。否则,将由 pynisher 启动进程。 n_trials : int,默认为 100 要运行的最大试验次数(配置、种子、预算和实例的组合,具体取决于任务)。 use_default_config: bool,默认为 False。如果为 True,则在初始设计中评估 configspace 的默认配置。出于历史基准测试原因,默认情况下为 False。请注意,这将导致初始设计的配置数量为 n_configs + 1。考虑到 n_trials,这将导致优化中评估的配置少一个。 instances : list[str] | None,默认为 None 要使用的实例名称。如果为 None,则不使用实例。实例可以是数据集名称、种子、子集等。 instance_features : dict[str, list[float]] | None,默认为 None 实例可以关联特征。例如,可以包含数据集的元数据(均值、方差等),然后这些元数据进一步用于扩展代理模型的训练数据。 min_budget : float | int | None,默认为 None 用于优化的最小预算(轮次、子集大小、实例数量等)。如果您使用多保真度或实例优化,请使用此参数。 max_budget : float | int | None,默认为 None 用于优化的最大预算(轮次、子集大小、实例数量等)。如果您使用多保真度或实例优化,请使用此参数。 seed : int,默认为 0 种子用于使结果可重现。如果 seed 为 -1,SMAC 将生成一个随机种子。 n_workers : int,默认为 1 用于并行化的 worker 数量。如果 n_workers 大于 1,SMAC 将使用 Dask 进行优化并行化。

元数据 property #

meta: dict[str, Any]

返回 SMAC 运行的元数据。

注意#

元数据在外观模式初始化时设置。

__post_init__ #

__post_init__() -> None

检查配置是否有效。

源代码位于 smac/scenario.py
def __post_init__(self) -> None:
    """Checks whether the config is valid."""
    # Use random seed if seed is -1
    if self.seed == -1:
        seed = random.randint(0, 999999)
        object.__setattr__(self, "seed", seed)

    # Transform instances to string if they are not
    if self.instances is not None:
        instances = [str(instance) for instance in self.instances]
        object.__setattr__(self, "instances", instances)

    # Transform instance features to string if they are not
    if self.instance_features is not None:
        instance_features = {str(instance): features for instance, features in self.instance_features.items()}
        object.__setattr__(self, "instance_features", instance_features)

    # Change directory wrt name and seed
    self._change_output_directory()

    # Set empty meta
    object.__setattr__(self, "_meta", {})

count_instance_features #

count_instance_features() -> int

计算实例特征的数量。

源代码位于 smac/scenario.py
def count_instance_features(self) -> int:
    """Counts the number of instance features."""
    # Check whether key of instance features exist
    n_features = 0
    if self.instance_features is not None:
        for k, v in self.instance_features.items():
            if self.instances is None or k not in self.instances:
                raise RuntimeError(f"Instance {k} is not specified in instances.")

            if n_features == 0:
                n_features = len(v)
            else:
                if len(v) != n_features:
                    raise RuntimeError("Instances must have the same number of features.")

    return n_features

count_objectives #

count_objectives() -> int

计算目标的数量。

源代码位于 smac/scenario.py
def count_objectives(self) -> int:
    """Counts the number of objectives."""
    if isinstance(self.objectives, list):
        return len(self.objectives)

    return 1

load staticmethod #

load(path: Path) -> Scenario

从文件中加载场景和配置空间。

源代码位于 smac/scenario.py
@staticmethod
def load(path: Path) -> Scenario:
    """Loads a scenario and the configuration space from a file."""
    filename = path / "scenario.json"
    with open(filename, "r") as fh:
        data = json.load(fh)

    # Convert `output_directory` to path object again
    data["output_directory"] = Path(data["output_directory"])
    meta = data["_meta"]
    del data["_meta"]

    # Read configspace
    configspace_filename = path / "configspace.json"
    configspace = ConfigurationSpace.from_json(configspace_filename)

    data["configspace"] = configspace

    scenario = Scenario(**data)
    scenario._set_meta(meta)

    return scenario

make_serializable staticmethod #

make_serializable(scenario: Scenario) -> dict[str, Any]

使场景可序列化。

源代码位于 smac/scenario.py
@staticmethod
def make_serializable(scenario: Scenario) -> dict[str, Any]:
    """Makes the scenario serializable."""
    s = copy.deepcopy(scenario.__dict__)
    del s["configspace"]
    s["output_directory"] = str(s["output_directory"])

    return json.loads(json.dumps(s))

save #

save() -> None

将内部变量和配置空间保存到文件中。

源代码位于 smac/scenario.py
def save(self) -> None:
    """Saves internal variables and the configuration space to a file."""
    if self.meta == {}:
        logger.warning("Scenario will saved without meta data. Please call the facade first to set meta data.")

    if self.name is None:
        raise RuntimeError(
            "Please specify meta data for generating a name. Alternatively, you can specify a name manually."
        )

    self.output_directory.mkdir(parents=True, exist_ok=True)

    data = {}
    for k, v in self.__dict__.items():
        if k in ["configspace", "output_directory"]:
            continue

        data[k] = v

    # Convert `output_directory`
    data["output_directory"] = str(self.output_directory)

    # Save everything
    filename = self.output_directory / "scenario.json"
    with open(filename, "w") as fh:
        json.dump(data, fh, indent=4, cls=NumpyEncoder)

    # Save configspace on its own
    configspace_filename = self.output_directory / "configspace.json"
    self.configspace.to_json(configspace_filename)