def _convert_to_gpyopt_domain( orig_domain: Domain ) -> Tuple[GPyOptDomain, GPyOptCategoricalValueMapper, GPyOptDiscreteTypeMapper]: """Convert a :class:`Domain` type object to :obj:`GPyOptDomain`. Args: orig_domain: :class:`Domain` to convert. Returns: A tuple of the converted :obj:`GPyOptDomain` object and a value mapper to assign each categorical value to an integer (0, 1, 2, 3 ...). This is done to abstract away the type of the categorical domain from the `GPyOpt` internals and thus arbitrary types are supported. Notes: The categorical options must be hashable. This behaviour may change in the future. """ gpyopt_domain = [] value_mapper = {} type_mapper = {} flat_domain = orig_domain.flatten() for names, vals in flat_domain.items(): dim_name = utils.join_strings(names) domain_type = Domain.get_type(vals) if domain_type == Domain.Continuous: dim_type = BayesianOptimisation.CONTINUOUS_TYPE elif domain_type == Domain.Discrete: dim_type = BayesianOptimisation.DISCRETE_TYPE type_mapper[dim_name] = {v: type(v) for v in vals} elif domain_type == Domain.Categorical: dim_type = BayesianOptimisation.CATEGORICAL_TYPE value_mapper[dim_name] = {v: i for i, v in enumerate(vals)} vals = tuple(range(len(vals))) else: raise ValueError( f"Badly specified subdomain {names} with values {vals}." ) gpyopt_domain.append({ "name": dim_name, "type": dim_type, "domain": tuple(vals) }) assert len(gpyopt_domain) == len(orig_domain), \ "Mismatching dimensionality after domain conversion." return gpyopt_domain, value_mapper, type_mapper
def _convert_to_hparams_domain(domain: Domain) -> Dict[str, hp.HParam]: hparams = {} for var_name, dim in domain.flatten().items(): dim_type = Domain.get_type(dim) joined_name = utils.join_strings(var_name, join_char="/") if dim_type == Domain.Continuous: hp_dim_type = hp.RealInterval vals = list(map(float, dim)) elif dim_type in [Domain.Discrete, Domain.Categorical]: hp_dim_type = hp.Discrete vals = (dim, ) else: raise TypeError(f"Cannot map subdomain of type {dim_type} " f"to a known HParams domain.") hparams[joined_name] = hp.HParam(joined_name, hp_dim_type(*vals)) return hparams
def test_from_list(): lst = [(("a", "b"), {2, 3, 4}), (("c", ), {0, 0.1}), (("d", "e", "f"), {0, 1}), (("d", "g"), {2, 3})] domain_true = Domain({ "a": { "b": {2, 3, 4} }, "c": {0, 0.1}, "d": { "e": { "f": {0, 1} }, "g": {2, 3} } }) domain_from_list = Domain.from_list(lst) assert domain_true == domain_from_list assert lst == list(domain_true.flatten().items())
def test_flatten(): dom = Domain({"a": {"b": [0, 1]}, "c": [0, 0.1]}) assert dom.flatten() == {("a", "b"): [0, 1], ("c", ): [0, 0.1]}