Coverage for mlos_core/mlos_core/util.py: 100%
10 statements
« prev ^ index » next coverage.py v7.6.7, created at 2024-11-22 01:18 +0000
« prev ^ index » next coverage.py v7.6.7, created at 2024-11-22 01:18 +0000
1#
2# Copyright (c) Microsoft Corporation.
3# Licensed under the MIT License.
4#
5"""Internal helper functions for mlos_core package."""
7from typing import Union
9import pandas as pd
10from ConfigSpace import Configuration, ConfigurationSpace
13def config_to_dataframe(config: Configuration) -> pd.DataFrame:
14 """
15 Converts a ConfigSpace config to a DataFrame.
17 Parameters
18 ----------
19 config : ConfigSpace.Configuration
20 The config to convert.
22 Returns
23 -------
24 pandas.DataFrame
25 A DataFrame with a single row, containing the config's parameters.
26 """
27 return pd.DataFrame([dict(config)])
30def drop_nulls(d: dict) -> dict:
31 """
32 Remove all key-value pairs where the value is None.
34 Parameters
35 ----------
36 d : dict
37 The dictionary to clean.
39 Returns
40 -------
41 dict
42 The cleaned dictionary.
43 """
44 return {k: v for k, v in d.items() if v is not None}
47def normalize_config(
48 config_space: ConfigurationSpace,
49 config: Union[Configuration, dict],
50) -> Configuration:
51 """
52 Convert a dictionary to a valid ConfigSpace configuration.
54 Some optimizers and adapters ignore ConfigSpace conditionals when proposing new
55 configurations. We have to manually remove inactive hyperparameters such suggestions.
57 Parameters
58 ----------
59 config_space : ConfigSpace.ConfigurationSpace
60 The parameter space to use.
61 config : dict
62 The configuration to convert.
64 Returns
65 -------
66 cs_config: ConfigSpace.Configuration
67 A valid ConfigSpace configuration with inactive parameters removed.
68 """
69 cs_config = Configuration(config_space, values=config, allow_inactive_with_values=True)
70 return Configuration(
71 config_space,
72 values={key: cs_config[key] for key in config_space.get_active_hyperparameters(cs_config)},
73 )