Skip to content

Configuration

ConfigSpace.configuration #

Configuration #

Configuration(
    configuration_space: ConfigurationSpace,
    values: Mapping[str, Any] | None = None,
    vector: Array[f64] | None = None,
    allow_inactive_with_values: bool = False,
    origin: Any | None = None,
    config_id: int | None = None,
)

Bases: Mapping[str, Any]

Class for a single configuration.

The Configuration object holds for all active hyperparameters a value. While the ConfigurationSpace stores the definitions for the hyperparameters (value ranges, constraints,...), a Configuration object is more an instance of it. Parameters of a Configuration object can be accessed and modified similar to python dictionaries (c.f. user guilde).

PARAMETER DESCRIPTION
configuration_space

The space this configuration is in

TYPE: ConfigurationSpace

values

A dictionary with pairs (hyperparameter_name, value), where value is a legal value of the hyperparameter in the above configuration_space

TYPE: Mapping[str, Any] | None DEFAULT: None

vector

A numpy array for efficient representation. Either values or vector has to be given

TYPE: Array[f64] | None DEFAULT: None

allow_inactive_with_values

Whether an Exception will be raised if a value for an inactive hyperparameter is given. Default is to raise an Exception. Default to False

TYPE: bool DEFAULT: False

origin

Store information about the origin of this configuration. Defaults to None.

TYPE: Any | None DEFAULT: None

config_id

Integer configuration ID which can be used by a program using the ConfigSpace package.

TYPE: int | None DEFAULT: None

Source code in src/ConfigSpace/configuration.py
def __init__(
    self,
    configuration_space: ConfigurationSpace,
    values: Mapping[str, Any] | None = None,
    vector: Array[f64] | None = None,
    allow_inactive_with_values: bool = False,
    origin: Any | None = None,
    config_id: int | None = None,
) -> None:
    """Create a new configuration.

    Args:
        configuration_space:
            The space this configuration is in
        values:
            A dictionary with pairs (hyperparameter_name, value), where value is
            a legal value of the hyperparameter in the above configuration_space
        vector:
            A numpy array for efficient representation. Either values or vector
            has to be given
        allow_inactive_with_values:
            Whether an Exception will be raised if a value for an inactive
            hyperparameter is given. Default is to raise an Exception.
            Default to False
        origin:
            Store information about the origin of this configuration.
            Defaults to None.
        config_id:
            Integer configuration ID which can be used by a program using the
            ConfigSpace package.
    """
    if (
        values is not None
        and vector is not None
        or values is None
        and vector is None
    ):
        raise ValueError(
            "Specify Configuration as either a dictionary or a vector.",
        )

    self.config_space = configuration_space
    self.allow_inactive_with_values = allow_inactive_with_values
    self.origin = origin
    self.config_id = config_id

    # This is cached. When it's None, it means it needs to be relaoaded
    # which is primarly handled in __getitem__.
    self._values: dict[str, Any] | None = None

    # Will be set below
    self._vector: np.ndarray

    if values is not None:
        unknown_keys = values.keys() - self.config_space.keys()
        if any(unknown_keys):
            raise ValueError(f"Unknown hyperparameter(s) {unknown_keys}")

        # Using cs._hyperparameters to iterate makes sure that the hyperparameters
        # in the configuration are sorted in the same way as they are sorted in
        # the configuration space
        self._values = {}
        self._vector = np.empty(shape=len(configuration_space), dtype=f64)

        for key, hp in configuration_space.items():
            i = configuration_space.index_of[key]

            value = values.get(key, NotSet)
            if value is NotSet:
                self._vector[i] = np.nan
                continue

            if not hp.legal_value(value):
                raise IllegalValueError(hp, value)

            # Truncate the float to be of constant lengt
            if isinstance(hp, FloatHyperparameter):
                value = float(np.round(value, ROUND_PLACES))  # type: ignore

            self._values[key] = value
            self._vector[i] = hp.to_vector(value)  # type: ignore

        self.check_valid_configuration()

    elif vector is not None:
        if not isinstance(vector, np.ndarray):
            _vector = np.asarray(vector, dtype=f64)
        else:
            _vector = vector

        if _vector.ndim != 1:
            # If we have a 2d array with shape (n, 1), flatten it
            if len(_vector.shape) == 2 and _vector.shape[1] == 1:
                _vector = _vector.flatten()
            else:
                raise ValueError(
                    "Only 1d arrays can be converted to a Configuration, "
                    f"you passed an array of shape {_vector.shape}",
                )

        n_hyperparameters = len(self.config_space)
        if len(_vector) != n_hyperparameters:
            raise ValueError(
                f"Expected array of length {n_hyperparameters}, got {len(_vector)}",
            )

        self._vector = _vector

config_id instance-attribute #

config_id: int | None = config_id

The configuration id of the Configuration, sometimes used by tools working with ConfigSpace.

config_space instance-attribute #

The space this configuration is in.

origin instance-attribute #

origin: Any | None = origin

The origin of the Configuration, sometimes used by tools working with ConfigSpace.

check_valid_configuration #

check_valid_configuration() -> None

Check if the object is a valid.

RAISES DESCRIPTION
ValueError

If configuration is not valid.

Source code in src/ConfigSpace/configuration.py
def check_valid_configuration(self) -> None:
    """Check if the object is a valid.

    Raises:
        ValueError: If configuration is not valid.
    """
    from ConfigSpace.util import check_configuration

    check_configuration(
        self.config_space,
        self._vector,
        allow_inactive_with_values=self.allow_inactive_with_values,
    )

get_array #

get_array() -> Array[f64]

The internal vector representation of this config.

All continuous values are scaled between zero and one.

RETURNS DESCRIPTION
Array[f64]

The vector representation of the configuration

Source code in src/ConfigSpace/configuration.py
def get_array(self) -> Array[f64]:
    """The internal vector representation of this config.

    All continuous values are scaled between zero and one.

    Returns:
        The vector representation of the configuration
    """
    return self._vector

get_dictionary #

get_dictionary() -> dict[str, Any]

A representation of the Configuration in dictionary form.

Deprecated

Please use dict(config) instead of config.get_dictionary() or use it as a dictionary directly if needed.,

RETURNS DESCRIPTION
dict[str, Any]

Configuration as dictionary

Source code in src/ConfigSpace/configuration.py
@deprecated(
    "Please use `dict(config)` instead of `config.get_dictionary()`"
    " or use it as a dictionary directly if needed.",
)
def get_dictionary(self) -> dict[str, Any]:
    """A representation of the `Configuration` in dictionary form.

    !!! warning "Deprecated"
        Please use `dict(config)` instead of `config.get_dictionary()`
        or use it as a dictionary directly if needed.,

    Returns:
        Configuration as dictionary
    """
    return dict(self)