Coverage for mlos_core/mlos_core/util.py: 100%

10 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-10-07 01:52 +0000

1# 

2# Copyright (c) Microsoft Corporation. 

3# Licensed under the MIT License. 

4# 

5"""Internal helper functions for mlos_core package.""" 

6 

7from typing import Union 

8 

9import pandas as pd 

10from ConfigSpace import Configuration, ConfigurationSpace 

11 

12 

13def config_to_dataframe(config: Configuration) -> pd.DataFrame: 

14 """ 

15 Converts a ConfigSpace config to a DataFrame. 

16 

17 Parameters 

18 ---------- 

19 config : ConfigSpace.Configuration 

20 The config to convert. 

21 

22 Returns 

23 ------- 

24 pd.DataFrame 

25 A DataFrame with a single row, containing the config's parameters. 

26 """ 

27 return pd.DataFrame([dict(config)]) 

28 

29 

30def drop_nulls(d: dict) -> dict: 

31 """ 

32 Remove all key-value pairs where the value is None. 

33 

34 Parameters 

35 ---------- 

36 d : dict 

37 The dictionary to clean. 

38 

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} 

45 

46 

47def normalize_config( 

48 config_space: ConfigurationSpace, 

49 config: Union[Configuration, dict], 

50) -> Configuration: 

51 """ 

52 Convert a dictionary to a valid ConfigSpace configuration. 

53 

54 Some optimizers and adapters ignore ConfigSpace conditionals when proposing new 

55 configurations. We have to manually remove inactive hyperparameters such suggestions. 

56 

57 Parameters 

58 ---------- 

59 config_space : ConfigurationSpace 

60 The parameter space to use. 

61 config : dict 

62 The configuration to convert. 

63 

64 Returns 

65 ------- 

66 cs_config: 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 )