Skip to content

Categorical

ConfigSpace.hyperparameters.categorical #

CACHE_ARANGE_CATEGORICAL_SIZE module-attribute #

CACHE_ARANGE_CATEGORICAL_SIZE = 25

For sizes smaller than this, we cache the arange for faster neighbor generation.

CACHE_NEIGHBORS_CATEGORICAL_SIZE module-attribute #

CACHE_NEIGHBORS_CATEGORICAL_SIZE = 5

For sizes smaller than this, we cache the possible neighbors for faster neighbor generation.

CategoricalHyperparameter dataclass #

CategoricalHyperparameter(
    name: str,
    choices: Sequence[Any],
    default_value: Any | _NotSet = NotSet,
    meta: Mapping[Hashable, Any] | None = None,
    weights: Sequence[float] | Array[number] | None = None,
)

Bases: Hyperparameter[Any, Any]

A hyperparameter that can take on one of a fixed set of values.

It is assumed there is no inherent order between the choices. If you know an order exists, use the OrdinalHyperparameter instead.

The values are sampled uniformly by default, but can be weighted using the weights parameter. The weights parameter is a list of floats, one for each choice, that determines the probability of each choice being sampled. The probabilities are normalized to sum to 1.

PARAMETER DESCRIPTION
name

Name of the hyperparameter, with which it can be accessed.

TYPE: str

choices

The possible values the hyperparameter can take on.

TYPE: Sequence[Any]

default_value

The default value of this hyperparameter. If None, the first choice is used.

TYPE: Any | _NotSet DEFAULT: NotSet

meta

Field for holding meta data provided by the user. Not used by ConfigSpace.

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

weights

The weights of the choices. If None, the choices are sampled uniformly. If given, the probabilities are normalized to sum to 1. The length of the weights has to be the same as the length of the choices.

TYPE: Sequence[float] | Array[number] | None DEFAULT: None

Source code in src/ConfigSpace/hyperparameters/categorical.py
def __init__(
    self,
    name: str,
    choices: Sequence[Any],
    default_value: Any | _NotSet = NotSet,
    meta: Mapping[Hashable, Any] | None = None,
    weights: Sequence[float] | Array[np.number] | None = None,
) -> None:
    """Initialize a categorical hyperparameter.

    Args:
        name:
            Name of the hyperparameter, with which it can be accessed.
        choices:
            The possible values the hyperparameter can take on.
        default_value:
            The default value of this hyperparameter. If `None`, the first
            choice is used.
        meta:
            Field for holding meta data provided by the user. Not used by
            ConfigSpace.
        weights:
            The weights of the choices. If `None`, the choices are sampled
            uniformly. If given, the probabilities are normalized to sum to 1.
            The length of the weights has to be the same as the length of the
            choices.
    """
    if isinstance(choices, Set):
        raise TypeError(
            "Using a set of choices is prohibited as it can result in "
            "non-deterministic behavior. Please use a list or a tuple.",
        )

    choices = tuple(choices)

    # We first try the fast route if it's Hashable, otherwise we resort to doing
    # an N^2 check.
    try:
        counter = Counter(choices)
        for choice, count in counter.items():
            if count > 1:
                raise ValueError(
                    f"Choices for categorical hyperparameters {name} contain"
                    f" choice `{choice}` {count} times, while only a single"
                    " occurence is allowed.",
                )
    except TypeError:
        for a, b in product(choices, choices):
            if a is not b and a == b:
                raise ValueError(  # noqa: B904
                    f"Choices for categorical hyperparameters {name} contain"
                    f" choice `{a}` multiple times, while only a single occurence"
                    " is allowed.",
                )

    if isinstance(weights, set):
        raise TypeError(
            "Using a set of weights is prohibited as it can result in "
            "non-deterministic behavior. Please use a list or a tuple.",
        )

    if isinstance(weights, Sequence):
        if len(weights) != len(choices):
            raise ValueError(
                "The list of weights and the list of choices are required to be"
                f" of same length. Gave {len(weights)} weights and"
                f" {len(choices)} choices.",
            )
        if any(weight < 0 for weight in weights):
            raise ValueError(
                f"Negative weights are not allowed. Got {weights}.",
            )
        if all(weight == 0 for weight in weights):
            raise ValueError(
                "All weights are zero, at least one weight has to be strictly"
                " positive.",
            )
        tupled_weights = tuple(weights)
    elif weights is not None:
        raise TypeError(
            f"The weights have to be a list, tuple or None. Got {weights!r}.",
        )
    else:
        tupled_weights = None

    if default_value is not NotSet and default_value not in choices:
        raise ValueError(
            "The default value has to be one of the choices. "
            f"Got {default_value!r} which is not in {choices}.",
        )

    size = len(choices)
    if weights is None:
        probabilities: Array[f64] = np.full(size, fill_value=1 / size, dtype=f64)
    else:
        _weights: Array[f64] = np.asarray(weights, dtype=f64)
        probabilities = _weights / np.sum(_weights)

    if default_value is NotSet and weights is None:
        default_value = choices[0]
    elif default_value is NotSet:
        highest_prob_index = np.argmax(probabilities)
        default_value = choices[highest_prob_index]
    elif default_value in choices:
        pass
    else:
        raise ValueError(f"Illegal default value {default_value}")

    # We only need to pass probabilties is they are non-uniform...
    vector_dist: Distribution
    if weights is not None:
        vector_dist = WeightedIntegerDiscreteDistribution(
            size=size,
            probabilities=np.asarray(probabilities),
        )
    else:
        vector_dist = UniformIntegerDistribution(size=size)

    try:
        # This can fail with a ValueError if the choices contain arbitrary objects
        # that are list like.
        seq_choices = np.asarray(choices)
        if seq_choices.ndim != 1:
            raise ValueError

        # NOTE: Unfortunatly, numpy will promote number types to str
        # if there are string types in the array, where we'd rather
        # stick to object type in that case. Hence the manual...
        if seq_choices.dtype.kind in {"U", "S"} and not all(
            isinstance(choice, str) for choice in choices
        ):
            seq_choices = np.array(choices, dtype=object)

    except ValueError:
        seq_choices = list(choices)

    # If the Hyperparameter recieves as a Sequence during legality checks or
    # conversions, we need to inform it that one of the values is a Sequence itself,
    # i.e. we should treat it as a single value and not a list of multiple values
    self._contains_sequence_as_value = any(
        isinstance(choice, Sequence) and not isinstance(choice, str)
        for choice in choices
    )

    self.probabilities = probabilities
    self.choices = choices
    self.weights = tupled_weights

    super().__init__(
        name=name,
        default_value=default_value,
        vector_dist=vector_dist,
        size=size,
        transformer=TransformerSeq(seq=seq_choices),
        neighborhood=NeighborhoodCat(size=size),
        neighborhood_size=self._categorical_neighborhood_size,
        meta=meta,
        value_cast=None,
    )

LEGAL_VALUE_TYPES class-attribute #

LEGAL_VALUE_TYPES: tuple[type, ...] | Literal["all"] = "all"

The types of values that are legal for this hyperparameter. If set to "all" any type is legal. Otherwise, a tuple of types can be provided.

choices instance-attribute #

choices: Sequence[Any] = choices

The possible values the hyperparameter can take on.

default_value instance-attribute #

default_value: Any

The default value of this hyperparameter.

lower_vectorized property #

lower_vectorized: f64

Lower bound of the hyperparameter in vector space.

meta instance-attribute #

meta: Mapping[Hashable, Any] | None

Field for holding meta data provided by the user. Not used by ConfigSpace.

name instance-attribute #

name: str

Name of the hyperparameter, with which it can be accessed.

size instance-attribute #

size: int

The number of possible values for the categorical hyperparameter.

upper_vectorized property #

upper_vectorized: f64

Upper bound of the hyperparameter in vector space.

weights instance-attribute #

weights: tuple[float, ...] | None = tupled_weights

The weights of the choices. If None, the choices are sampled uniformly.

copy #

copy(**kwargs: Any) -> Self

Create a copy of the hyperparameter with updated attributes.

PARAMETER DESCRIPTION
**kwargs

The attributes to update.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
Self

A copy of the hyperparameter with the updated attributes.

Source code in src/ConfigSpace/hyperparameters/hyperparameter.py
def copy(self, **kwargs: Any) -> Self:
    """Create a copy of the hyperparameter with updated attributes.

    Args:
        **kwargs:
            The attributes to update.

    Returns:
        A copy of the hyperparameter with the updated attributes.
    """
    # HACK: Really the only thing implementing Hyperparameter should be a dataclass
    # If a hyperparameter is somehow not a dataclass, it will likely need to
    # overwrite this.
    return replace(self, **kwargs)  # type: ignore

get_max_density #

get_max_density() -> float

Get the maximum density of the hyperparameter distribution.

Source code in src/ConfigSpace/hyperparameters/hyperparameter.py
def get_max_density(self) -> float:
    """Get the maximum density of the hyperparameter distribution."""
    return self._vector_dist.max_density()

get_neighbors #

get_neighbors(
    value: f64,
    rs: RandomState,
    number: int | None = None,
    std: float | None = None,
    transform: bool = False,
) -> Array[f64]

Deprecated.

Source code in src/ConfigSpace/hyperparameters/hyperparameter.py
@deprecated("Please use `neighbors_vectorized`  instead.")
def get_neighbors(
    self,
    value: f64,
    rs: np.random.RandomState,
    number: int | None = None,
    std: float | None = None,
    transform: bool = False,
) -> Array[f64]:
    """Deprecated."""
    if transform is True:
        raise RuntimeError(
            "Previous `get_neighbors` with `transform=True` had different"
            " behaviour depending on the hyperparameter. Notably numerics"
            " were still considered to be in vectorized form while for ordinals"
            " they were considered to be in value form."
            "\nPlease use either `neighbors_vectorized` or `neighbors_values`"
            " instead, depending on your need. You can use `to_value` or"
            " `to_vector` to switch between the results of the two.",
        )

    if number is None:
        warnings.warn(
            "Please provide a number of neighbors to sample. The"
            " default used to be `4` but will be explicitly required"
            " in the futurefuture.",
            DeprecationWarning,
            stacklevel=2,
        )
        number = 4

    return self.neighbors_vectorized(value, number, std=std, seed=rs)

get_num_neighbors #

get_num_neighbors(
    value: ValueT | DType | _NotSet = NotSet,
) -> int | float

Get the number of neighbors to sample for a given value.

PARAMETER DESCRIPTION
value

The value to get the number of neighbors for. If None the default value is used. Defaults to None.

TYPE: ValueT | DType | _NotSet DEFAULT: NotSet

RETURNS DESCRIPTION
int | float

The number of neighbors to sample.

Source code in src/ConfigSpace/hyperparameters/hyperparameter.py
def get_num_neighbors(
    self,
    value: ValueT | DType | _NotSet = NotSet,
) -> int | float:
    """Get the number of neighbors to sample for a given value.

    Args:
        value:
            The value to get the number of neighbors for. If `None` the
            default value is used. Defaults to `None`.

    Returns:
        The number of neighbors to sample.
    """
    return (
        self._neighborhood_size(value)
        if callable(self._neighborhood_size)
        else self._neighborhood_size
    )

get_size #

get_size() -> int | float

Deprecated.

Source code in src/ConfigSpace/hyperparameters/hyperparameter.py
@deprecated("Please use `.size` attribute instead.")
def get_size(self) -> int | float:
    """Deprecated."""
    return self.size

has_neighbors #

has_neighbors() -> bool

Deprecated.

Source code in src/ConfigSpace/hyperparameters/hyperparameter.py
@deprecated("Please use `get_num_neighbors() > 0` or `hp.size > 1` instead.")
def has_neighbors(self) -> bool:
    """Deprecated."""
    return self.get_num_neighbors() > 0
is_legal(value: DType) -> bool

Deprecated.

Source code in src/ConfigSpace/hyperparameters/hyperparameter.py
@deprecated("Please use `legal_value(value)` instead")
def is_legal(self, value: DType) -> bool:
    """Deprecated."""
    return self.legal_value(value)
is_legal_vector(value: f64) -> bool

Deprecated.

Source code in src/ConfigSpace/hyperparameters/hyperparameter.py
@deprecated("Please use `legal_vector(vector)` instead.")
def is_legal_vector(self, value: f64) -> bool:
    """Deprecated."""
    return self.legal_vector(value)

legal_vector #

legal_vector(vector: Number | Array[f64]) -> Mask | bool

Check if a vectorized value is legal for this hyperparameter.

PARAMETER DESCRIPTION
vector

The vectorized value to check.

TYPE: Number | Array[f64]

RETURNS DESCRIPTION
Mask | bool

True if the vector is legal, False otherwise. If vector is an array of vectors, a mask of legal values is returned.

Source code in src/ConfigSpace/hyperparameters/hyperparameter.py
def legal_vector(self, vector: Number | Array[f64]) -> Mask | bool:
    """Check if a vectorized value is legal for this hyperparameter.

    Args:
        vector:
            The vectorized value to check.

    Returns:
        `True` if the vector is legal, `False` otherwise. If `vector` is an
        array of vectors, a mask of legal values is returned.
    """
    if isinstance(vector, np.ndarray):
        if not np.issubdtype(vector.dtype, np.number):
            raise ValueError(
                "The vector must be of a numeric dtype to check for legality."
                f"Got {vector.dtype=} for {vector=}.",
            )
        return self._transformer.legal_vector(vector)

    if not isinstance(vector, (int, float, np.number)):
        return False

    return self._transformer.legal_vector_single(f64(vector))

neighbors_values #

neighbors_values(
    value: ValueT | DType,
    n: int,
    *,
    std: float | None = None,
    seed: RandomState | None = None
) -> Array[DType]

Sample neighbors of a value.

PARAMETER DESCRIPTION
value

The value to sample neighbors from.

TYPE: ValueT | DType

n

The number of unique neighbors to sample.

Warning

If there are less than n legal neighbors, then all legal neighbors are returned, which is some number less than n.

TYPE: int

std

The standard deviation of the neighborhood. If None the neighborhood is deterministic. Defaults to None.

Warning

Hyperparameter subclasses are under no obligation to use this if it does not make sense, i.e. for an OrdinalHyperparameter or a CategoricalHyperparameter.

TYPE: float | None DEFAULT: None

seed

The random state to use for sampling. If None the global random state is used. Defaults to None.

TYPE: RandomState | None DEFAULT: None

RETURNS DESCRIPTION
Array[DType]

The sampled neighbors in value space.

Source code in src/ConfigSpace/hyperparameters/hyperparameter.py
def neighbors_values(
    self,
    value: ValueT | DType,
    n: int,
    *,
    std: float | None = None,
    seed: np.random.RandomState | None = None,
) -> Array[DType]:
    """Sample neighbors of a value.

    Args:
        value:
            The value to sample neighbors from.
        n:
            The number of **unique** neighbors to sample.

            !!! warning

                If there are less than `n` legal neighbors, then all legal
                neighbors are returned, which is some number less than `n`.
        std:
            The standard deviation of the neighborhood. If `None` the
            neighborhood is deterministic. Defaults to `None`.

            !!! warning

                Hyperparameter subclasses are under no obligation to use
                this if it does not make sense, i.e. for an
                [`OrdinalHyperparameter`][ConfigSpace.hyperparameters.OrdinalHyperparameter]
                or a
                [`CategoricalHyperparameter`][ConfigSpace.hyperparameters.CategoricalHyperparameter].

        seed:
            The random state to use for sampling. If `None` the global
            random state is used. Defaults to `None`.

    Returns:
        The sampled neighbors in value space.
    """
    vector = self.to_vector(value)
    return self.to_value(
        vector=self.neighbors_vectorized(vector, n, std=std, seed=seed),
    )

neighbors_vectorized #

neighbors_vectorized(
    vector: Number,
    n: int,
    *,
    std: float | None = None,
    seed: RandomState | None = None
) -> Array[f64]

Sample neighbors of a vectorized value.

PARAMETER DESCRIPTION
vector

The vectorized value to sample neighbors from.

TYPE: Number

n

The number of unique neighbors to sample.

Warning

If there are less than n legal neighbors, then all legal neighbors are returned, which is some number less than n.

TYPE: int

std

The standard deviation of the neighborhood. If None the neighborhood is deterministic. Defaults to None.

Warning

Hyperparameter subclasses are under no obligation to use this if it does not make sense, i.e. for an OrdinalHyperparameter or a CategoricalHyperparameter.

TYPE: float | None DEFAULT: None

seed

The random state to use for sampling. If None the global random state is used. Defaults to None.

TYPE: RandomState | None DEFAULT: None

RETURNS DESCRIPTION
Array[f64]

The sampled neighbors in vectorized space.

Source code in src/ConfigSpace/hyperparameters/hyperparameter.py
def neighbors_vectorized(
    self,
    vector: Number,
    n: int,
    *,
    std: float | None = None,
    seed: np.random.RandomState | None = None,
) -> Array[f64]:
    """Sample neighbors of a vectorized value.

    Args:
        vector:
            The vectorized value to sample neighbors from.
        n:
            The number of **unique** neighbors to sample.

            !!! warning

                If there are less than `n` legal neighbors, then all legal
                neighbors are returned, which is some number less than `n`.
        std:
            The standard deviation of the neighborhood. If `None` the
            neighborhood is deterministic. Defaults to `None`.

            !!! warning

                Hyperparameter subclasses are under no obligation to use
                this if it does not make sense, i.e. for an
                [`OrdinalHyperparameter`][ConfigSpace.hyperparameters.OrdinalHyperparameter]
                or a
                [`CategoricalHyperparameter`][ConfigSpace.hyperparameters.CategoricalHyperparameter].

        seed:
            The random state to use for sampling. If `None` the global
            random state is used. Defaults to `None`.

    Returns:
        The sampled neighbors in vectorized space.
    """
    if std is not None:
        assert 0.0 <= std <= 1.0, f"std must be in [0, 1], got {std}"

    if not self.legal_vector(vector):
        raise ValueError(
            f"Vector value {vector} is not legal for hyperparameter '{self.name}'."
            f"\n{self}",
        )

    return self._neighborhood(f64(vector), n, std=std, seed=seed)

pdf #

pdf(vector: DType | Array[DType]) -> f64 | Array[f64]

Deprecated.

Source code in src/ConfigSpace/hyperparameters/hyperparameter.py
@deprecated("Please use `pdf_values(value)` instead.")
def pdf(
    self,
    vector: DType | Array[DType],  # NOTE: New convention this should be value
) -> f64 | Array[f64]:
    """Deprecated."""
    if isinstance(vector, np.ndarray):
        return self.pdf_values(vector)

    return self.pdf_values(np.asarray([vector]))[0]  # type: ignore

pdf_vector #

pdf_vector(vector: Array[f64]) -> Array[f64]

Get the probability density of an array of vectorized values.

PARAMETER DESCRIPTION
vector

The vectorized values to get the probability density of.

TYPE: Array[f64]

RETURNS DESCRIPTION
Array[f64]

The probability density of the vectorized values. Where vectorized values are not legal, the probability density is zero.

Source code in src/ConfigSpace/hyperparameters/hyperparameter.py
def pdf_vector(self, vector: Array[f64]) -> Array[f64]:
    """Get the probability density of an array of vectorized values.

    Args:
        vector:
            The vectorized values to get the probability density of.

    Returns:
        The probability density of the vectorized values. Where vectorized
        values are not legal, the probability density is zero.
    """
    legal_mask: Array[f64] = self.legal_vector(vector).astype(f64)
    return self._vector_dist.pdf_vector(vector) * legal_mask

rvs #

rvs(
    size: int | None = None,
    *,
    random_state: (
        Generator | RandomState | int | None
    ) = None
) -> ValueT | Array[DType]

Sample a value from this hyperparameter, compatbile with scipy.stats.rvs.

PARAMETER DESCRIPTION
size

The number of values to sample. If None a single value is sampled. Defaults to None.

TYPE: int | None DEFAULT: None

random_state

The random state to use for sampling. If None the global random state is used. Defaults to None.

TYPE: Generator | RandomState | int | None DEFAULT: None

RETURNS DESCRIPTION
ValueT | Array[DType]

The sampled value or an array of sampled values, depending on size=.

Source code in src/ConfigSpace/hyperparameters/hyperparameter.py
def rvs(
    self,
    size: int | None = None,
    *,
    random_state: np.random.Generator | np.random.RandomState | int | None = None,
) -> ValueT | Array[DType]:
    """Sample a value from this hyperparameter, compatbile with scipy.stats.rvs.

    Args:
        size:
            The number of values to sample. If `None` a single value is
            sampled. Defaults to `None`.
        random_state:
            The random state to use for sampling. If `None` the global
            random state is used. Defaults to `None`.


    Returns:
        The sampled value or an array of sampled values, depending on `size=`.
    """
    if isinstance(random_state, int) or random_state is None:
        random_state = np.random.RandomState(random_state)
    elif isinstance(random_state, np.random.Generator):
        # HACK: This is to enable backwards compatibliity with numpy<=2.0,
        # where the default integer type is np.int32.
        MAX_INT = np.iinfo(np.int32).max
        random_state = np.random.RandomState(int(random_state.integers(0, MAX_INT)))

    vector = self.sample_vector(size=size, seed=random_state)
    return self.to_value(vector)

sample #

sample(rs: RandomState) -> ValueT

Deprecated.

Source code in src/ConfigSpace/hyperparameters/hyperparameter.py
@deprecated("Please use `sample_value(seed=rs)` instead.")
def sample(self, rs: np.random.RandomState) -> ValueT:
    """Deprecated."""
    return self.sample_value(seed=rs)

sample_value #

sample_value(
    size: int | None = None,
    *,
    seed: RandomState | None = None
) -> ValueT | Array[DType]

Sample a value from this hyperparameter.

PARAMETER DESCRIPTION
size

The number of values to sample. If None a single value is sampled. Defaults to None.

TYPE: int | None DEFAULT: None

seed

The random state to use for sampling. If None the global random state is used. Defaults to None.

TYPE: RandomState | None DEFAULT: None

RETURNS DESCRIPTION
ValueT | Array[DType]

The sampled value or an array of sampled values, depending on size=.

Source code in src/ConfigSpace/hyperparameters/hyperparameter.py
def sample_value(
    self,
    size: int | None = None,
    *,
    seed: np.random.RandomState | None = None,
) -> ValueT | Array[DType]:
    """Sample a value from this hyperparameter.

    Args:
        size:
            The number of values to sample. If `None` a single value is
            sampled. Defaults to `None`.
        seed:
            The random state to use for sampling. If `None` the global
            random state is used. Defaults to `None`.

    Returns:
        The sampled value or an array of sampled values, depending on `size=`.
    """
    samples = self.sample_vector(size=size, seed=seed)
    return self.to_value(samples)

sample_vector #

sample_vector(
    size: int | None = None,
    *,
    seed: RandomState | None = None
) -> f64 | Array[f64]

Sample a vectorized value from this hyperparameter.

PARAMETER DESCRIPTION
size

The number of values to sample. If None a single value is sampled. Defaults to None.

TYPE: int | None DEFAULT: None

seed

The random state to use for sampling. If None the global random state is used. Defaults to None.

TYPE: RandomState | None DEFAULT: None

RETURNS DESCRIPTION
f64 | Array[f64]

The sampled vector or an array of sampled vectors, depending on size=.

Source code in src/ConfigSpace/hyperparameters/hyperparameter.py
def sample_vector(
    self,
    size: int | None = None,
    *,
    seed: np.random.RandomState | None = None,
) -> f64 | Array[f64]:
    """Sample a vectorized value from this hyperparameter.

    Args:
        size:
            The number of values to sample. If `None` a single value is
            sampled. Defaults to `None`.
        seed:
            The random state to use for sampling. If `None` the global
            random state is used. Defaults to `None`.

    Returns:
        The sampled vector or an array of sampled vectors, depending on `size=`.
    """
    if size is None:
        return self._vector_dist.sample_vector(n=1, seed=seed)[0]  # type: ignore
    return self._vector_dist.sample_vector(n=size, seed=seed)

to_uniform #

to_uniform() -> CategoricalHyperparameter

Converts this hyperparameter to have uniform weights.

Source code in src/ConfigSpace/hyperparameters/categorical.py
def to_uniform(self) -> CategoricalHyperparameter:
    """Converts this hyperparameter to have uniform weights."""
    return CategoricalHyperparameter(
        name=self.name,
        choices=self.choices,
        weights=None,
        default_value=self.default_value,
        meta=self.meta,
    )

to_value #

to_value(
    vector: Number | Array[f64],
) -> ValueT | Array[DType]

Transform a vectorized value to a value in value space.

PARAMETER DESCRIPTION
vector

The vectorized value to transform.

TYPE: Number | Array[f64]

RETURNS DESCRIPTION
ValueT | Array[DType]

The value in value space.

Source code in src/ConfigSpace/hyperparameters/hyperparameter.py
def to_value(
    self,
    vector: Number | Array[f64],
) -> ValueT | Array[DType]:
    """Transform a vectorized value to a value in value space.

    Args:
        vector:
            The vectorized value to transform.

    Returns:
        The value in value space.
    """
    if isinstance(vector, np.ndarray):
        return self._transformer.to_value(vector)

    value: DType = self._transformer.to_value(np.array([vector]))[0]
    if self._value_cast is not None:
        return self._value_cast(value)

    return value  # type: ignore

NeighborhoodCat dataclass #

NeighborhoodCat(
    size: int,
    _cached_arange: Array[f64] | None = None,
    _cached_neighbors: list[Array[f64]] | None = None,
)

Bases: Neighborhood

Neighborhood for categorical hyperparameters.

Note

For CategoricalHyperparameter, all values are considered equally distant from each other. Thus, the possible neighbors is all other values except the current one.

size instance-attribute #

size: int

The number of possible values for the categorical hyperparameter.