Skip to content

Commit 6071921

Browse files
v0.0.20 cleanup
1 parent 259f83b commit 6071921

3 files changed

Lines changed: 199 additions & 6 deletions

File tree

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
77

88
[project]
99
name = "spotPython"
10-
version = "0.0.19"
10+
version = "0.0.20"
1111
authors = [
1212
{ name="T. Bartz-Beielstein", email="tbb@bartzundbartz.de" }
1313
]

src/spotPython/hyperparameters/values.py

Lines changed: 187 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,89 @@
1-
from spotPython.utils.convert import class_for_name
21
import numpy as np
2+
import copy
3+
4+
from spotPython.utils.convert import class_for_name
5+
from spotPython.utils.transform import transform_hyper_parameter_values
6+
7+
8+
def assign_values(X: np.array, var_list: list):
9+
"""
10+
This function takes an np.array X and a list of variable names as input arguments
11+
and returns a dictionary where the keys are the variable names and the values are assigned from X.
12+
13+
Parameters:
14+
X (np.array): A 2D numpy array where each column represents a variable.
15+
var_list (list): A list of strings representing variable names.
16+
17+
Returns:
18+
dict: A dictionary where keys are variable names and values are assigned from X.
19+
20+
Example:
21+
>>> import numpy as np
22+
>>> X = np.array([[1, 2], [3, 4], [5, 6]])
23+
>>> var_list = ['a', 'b']
24+
>>> result = assign_values(X, var_list)
25+
>>> print(result)
26+
{'a': array([1, 3, 5]), 'b': array([2, 4, 6])}
27+
"""
28+
result = {}
29+
for i, var_name in enumerate(var_list):
30+
result[var_name] = X[:, i]
31+
return result
32+
33+
34+
def iterate_dict_values(var_dict: dict):
35+
"""
36+
This function takes a dictionary of variables as input arguments and returns an iterator that
37+
yields the values from the arrays in the dictionary.
38+
39+
Parameters:
40+
var_dict (dict): A dictionary where keys are variable names and values are numpy arrays.
41+
42+
Returns:
43+
iterator: An iterator that yields the values from the arrays in the dictionary.
44+
45+
Example:
46+
>>> import numpy as np
47+
>>> var_dict = {'a': np.array([1, 3, 5]), 'b': np.array([2, 4, 6])}
48+
>>> for values in iterate_dict_values(var_dict):
49+
... print(values)
50+
{'a': 1, 'b': 2}
51+
{'a': 3, 'b': 4}
52+
{'a': 5, 'b': 6}
53+
"""
54+
n = len(next(iter(var_dict.values())))
55+
for i in range(n):
56+
yield {key: value[i] for key, value in var_dict.items()}
57+
58+
59+
def convert_keys(d: dict, var_type: list):
60+
"""
61+
Convert values in a dictionary to integers based on a list of variable types.
62+
63+
This function takes a dictionary `d` and a list of variable types `var_type` as arguments.
64+
For each key in the dictionary,
65+
if the corresponding entry in `var_type` is not equal to `"num"`,
66+
the value associated with that key is converted to an integer.
67+
68+
Args:
69+
d (dict): The input dictionary.
70+
var_type (list): A list of variable types. If the entry is not `"num"` the corresponding
71+
value will be converted to the type `"int"`.
72+
73+
Returns:
74+
dict: The modified dictionary with values converted to integers based on `var_type`.
75+
76+
Example:
77+
>>> d = {'a': '1.1', 'b': '2', 'c': '3.1'}
78+
>>> var_type = ["int", "num", "int"]
79+
>>> convert_keys(d, var_type)
80+
{'a': 1, 'b': '2', 'c': 3}
81+
"""
82+
keys = list(d.keys())
83+
for i in range(len(keys)):
84+
if var_type[i] not in ["num", "float"]:
85+
d[keys[i]] = int(d[keys[i]])
86+
return d
387

488

589
def modify_hyper_parameter_levels(fun_control, hyperparameter, levels):
@@ -308,3 +392,105 @@ def get_bound_values(fun_control: dict, bound: str, as_list=False) -> list or np
308392
return b
309393
else:
310394
return np.array(b)
395+
396+
397+
def replace_levels_with_positions(hyper_dict, hyper_dict_values):
398+
"""Replace the levels with the position in the levels list.
399+
The function that takes two dictionaries.
400+
The first contains as hyperparameters as keys.
401+
If the hyperparameter has the key "levels",
402+
then the value of the corresponding hyperparameter in the second dictionary is
403+
replaced by the position of the value in the list of levels.
404+
The function returns a dictionary with the same keys as the second dictionary.
405+
For example, if the second dictionary is {"a": 1, "b": "model1", "c": 3}
406+
and the first dictionary is {
407+
"a": {"type": "int"},
408+
"b": {"levels": ["model4", "model5", "model1"]},
409+
"d": {"type": "float"}},
410+
then the function should return {"a": 1, "b": 2, "c": 3}.
411+
Args:
412+
hyper_dict (dict): dictionary with levels
413+
hyper_dict_values (dict): dictionary with values
414+
Returns:
415+
(dict): dictionary with values
416+
Example:
417+
>>> hyper_dict = {"leaf_prediction": {
418+
"levels": ["mean", "model", "adaptive"],
419+
"type": "factor",
420+
"default": "mean",
421+
"core_model_parameter_type": "str"},
422+
"leaf_model": {
423+
"levels": ["linear_model.LinearRegression", "linear_model.PARegressor", "linear_model.Perceptron"],
424+
"type": "factor",
425+
"default": "LinearRegression",
426+
"core_model_parameter_type": "instance"},
427+
"splitter": {
428+
"levels": ["EBSTSplitter", "TEBSTSplitter", "QOSplitter"],
429+
"type": "factor",
430+
"default": "EBSTSplitter",
431+
"core_model_parameter_type": "instance()"},
432+
"binary_split": {
433+
"levels": [0, 1],
434+
"type": "factor",
435+
"default": 0,
436+
"core_model_parameter_type": "bool"},
437+
"stop_mem_management": {
438+
"levels": [0, 1],
439+
"type": "factor",
440+
"default": 0,
441+
"core_model_parameter_type": "bool"}}
442+
>>> hyper_dict_values = {"leaf_prediction": "mean",
443+
"leaf_model": "linear_model.LinearRegression",
444+
"splitter": "EBSTSplitter",
445+
"binary_split": 0,
446+
"stop_mem_management": 0}
447+
>>> replace_levels_with_position(hyper_dict, hyper_dict_values)
448+
{'leaf_prediction': 0,
449+
'leaf_model': 0,
450+
'splitter': 0,
451+
'binary_split': 0,
452+
'stop_mem_management': 0}
453+
"""
454+
hyper_dict_values_new = copy.deepcopy(hyper_dict_values)
455+
for key, value in hyper_dict_values.items():
456+
if key in hyper_dict.keys():
457+
if "levels" in hyper_dict[key].keys():
458+
hyper_dict_values_new[key] = hyper_dict[key]["levels"].index(value)
459+
return hyper_dict_values_new
460+
461+
462+
def get_values_from_dict(dictionary) -> np.array:
463+
"""Get the values from a dictionary as a list.
464+
Generate an np.array that contains the values of the keys of a dictionary
465+
in the same order as the keys of the dictionary.
466+
Args:
467+
dictionary (dict): dictionary with values
468+
Returns:
469+
(np.array): array with values
470+
Example:
471+
>>> d = {"a": 1, "b": 2, "c": 3}
472+
>>> get_values_from_dict(d)
473+
array([1, 2, 3])
474+
"""
475+
return np.array(list(dictionary.values()))
476+
477+
478+
def get_values_from_var_dict(var_dict: dict, fun_control: dict):
479+
"""This function takes a dictionary of variables and a dictionary of function control.
480+
Args:
481+
var_dict (dict): A dictionary of variables.
482+
fun_control (dict): A dictionary of function control.
483+
Returns:
484+
dict: A dictionary of hyper parameter values. Transformations are applied to the values.
485+
Example:
486+
>>> import numpy as np
487+
>>> var_dict = {'a': np.array([1, 3, 5]), 'b': np.array([2, 4, 6])}
488+
>>> fun_control = {'var_type': ['int', 'int']}
489+
>>> get_values_from_var_dict(var_dict, fun_control)
490+
{'a': [1, 3, 5], 'b': [2, 4, 6]}
491+
"""
492+
for values in iterate_dict_values(var_dict):
493+
values = convert_keys(values, fun_control["var_type"])
494+
values = get_dict_with_levels_and_types(fun_control=fun_control, v=values)
495+
values = transform_hyper_parameter_values(fun_control=fun_control, hyper_parameter_values=values)
496+
return values

src/spotPython/utils/transform.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,15 @@ def transform_power_2(x):
6363

6464
def transform_hyper_parameter_values(fun_control, hyper_parameter_values):
6565
"""
66-
Transform the values of the hyperparameters according to the transform function specified in f_c if the hyperparameter is of type "int", or "float" or "num".
67-
Let f_c = {"core_model_hyper_dict":{ "leaf_prediction": { "levels": ["mean", "model", "adaptive"], "type": "factor", "default": "mean", "core_model_parameter_type": "str"}, "max_depth": { "type": "int", "default": 20, "transform": "transform_power_2", "lower": 2, "upper": 20}}} and v = {'max_depth': 20,'leaf_prediction': 'mean'} and def transform_power_2(x): return 2**x.
66+
Transform the values of the hyperparameters according to the transform function specified in f_c
67+
if the hyperparameter is of type "int", or "float" or "num".
68+
Let f_c = {"core_model_hyper_dict":{ "leaf_prediction":
69+
{ "levels": ["mean", "model", "adaptive"], "type": "factor", "default": "mean", "core_model_parameter_type": "str"},
70+
"max_depth": { "type": "int", "default": 20, "transform": "transform_power_2", "lower": 2, "upper": 20}}}
71+
and v = {'max_depth': 20,'leaf_prediction': 'mean'} and def transform_power_2(x): return 2**x.
6872
The function takes f_c and v as input and returns a dictionary with the same structure as v.
69-
The function transforms the values of the hyperparameters according to the transform function specified in f_c if the hyperparameter is of type "int", or "float" or "num".
73+
The function transforms the values of the hyperparameters according to the transform function
74+
specified in f_c if the hyperparameter is of type "int", or "float" or "num".
7075
For example, transform_hyper_parameter_values(f_c, v) returns {'max_depth': 1048576, 'leaf_prediction': 'mean'}.
7176
Args:
7277
fun_control (dict): A dictionary containing the information about the core model and the hyperparameters.
@@ -76,7 +81,9 @@ def transform_hyper_parameter_values(fun_control, hyper_parameter_values):
7681
Example:
7782
>>> import copy
7883
>>> from spotPython.utils.transform import transform_hyper_parameter_values
79-
>>> fun_control = {"core_model_hyper_dict": {"leaf_prediction": {"levels": ["mean", "model", "adaptive"], "type": "factor", "default": "mean", "core_model_parameter_type": "str"}, "max_depth": {"type": "int", "default": 20, "transform": "transform_power_2", "lower": 2, "upper": 20}}}
84+
>>> fun_control = {"core_model_hyper_dict": {"leaf_prediction": {"levels": ["mean", "model", "adaptive"],
85+
"type": "factor", "default": "mean", "core_model_parameter_type": "str"},
86+
"max_depth": {"type": "int", "default": 20, "transform": "transform_power_2", "lower": 2, "upper": 20}}}
8087
>>> hyper_parameter_values = {'max_depth': 20, 'leaf_prediction': 'mean'}
8188
>>> transform_hyper_parameter_values(fun_control, hyper_parameter_values)
8289
{'max_depth': 1048576, 'leaf_prediction': 'mean'}

0 commit comments

Comments
 (0)