Passed
Push — master ( 051bec...b89548 )
by Simon
01:31
created

Converter._memory2dataframe()   A

Complexity

Conditions 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nop 2
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
# Author: Simon Blanke
2
# Email: [email protected]
3
# License: MIT License
4
5
import numbers
6
import numpy as np
7
import pandas as pd
8
9
10
class Converter:
11
    def __init__(self, search_space):
12
        self.search_space = search_space
13
        self.para_names = list(self.search_space.keys())
14
15
    def value2position(self, value):
16
        position = []
17
        for n, space_dim in enumerate(self.search_space_values):
18
            pos = np.abs(value[n] - space_dim).argmin()
19
            position.append(pos)
20
21
        return np.array(position).astype(int)
22
23
    def value2para(self, value):
24
        para = {}
25
        for key, p_ in zip(self.para_names, value):
26
            para[key] = p_
27
28
        return para
29
30
    def position2value(self, position):
31
        value = []
32
33
        for n, space_dim in enumerate(self.search_space_values):
34
            value.append(space_dim[position[n]])
35
36
        return np.array(value)
37
38
    def positions2values(self, positions):
39
        values_temp = []
40
        positions_np = np.array(positions)
41
42
        for n, space_dim in enumerate(self.search_space_values):
43
            pos_1d = positions_np[:, n]
44
            value_ = np.take(space_dim, pos_1d, axis=0)
45
            values_temp.append(value_)
46
47
        values = list(np.array(values_temp).T)
48
        return values
49
50
    def para2value(self, para):
51
        value = []
52
        for para_name in self.para_names:
53
            value.append(para[para_name])
54
55
        return np.array(value)
56
57
    def _memory2dataframe(self, memory_dict):
58
        positions = [np.array(pos).astype(int) for pos in list(memory_dict.keys())]
59
        scores = list(memory_dict.values())
60
61
        memory_positions = pd.DataFrame(positions, columns=self.para_names)
62
        memory_positions["score"] = scores
63
64
        return memory_positions
65
66
67
class HyperGradientTrafo(Converter):
68
    def __init__(self, search_space):
69
        super().__init__(search_space)
70
        self.search_space_values = list(self.search_space.values())
71
72
        search_space_positions = {}
73
        for key in search_space.keys():
74
            search_space_positions[key] = np.array(range(len(search_space[key])))
75
        self.search_space_positions = search_space_positions
76
77
        """
78
        self.search_space_ltm = {}
79
        self.data_types = {}
80
        for para_name in search_space.keys():
81
            value0 = search_space[para_name][0]
82
83
            if isinstance(value0, numbers.Number):
84
                type0 = "number"
85
                search_dim_ltm = search_space[para_name]
86
            elif isinstance(value0, str):
87
                type0 = "string"
88
                search_dim_ltm = search_space[para_name]
89
90
            elif callable(value0):
91
                type0 = "function"
92
93
                search_dim_ltm = []
94
                for func in list(search_space[para_name]):
95
                    search_dim_ltm.append(func.__name__)
96
97
            else:
98
                type0 = None
99
                search_dim_ltm = search_space[para_name]
100
101
            self.data_types[para_name] = type0
102
            self.search_space_ltm[para_name] = search_dim_ltm
103
        """
104
105
    def trafo_initialize(self, initialize):
106
        if "warm_start" in list(initialize.keys()):
107
            warm_start = initialize["warm_start"]
108
            warm_start_gfo = []
109
            for warm_start_ in warm_start:
110
                value = self.para2value(warm_start_)
111
                position = self.value2position(value)
112
                pos_para = self.value2para(position)
113
114
                warm_start_gfo.append(pos_para)
115
116
            initialize["warm_start"] = warm_start_gfo
117
118
        return initialize
119
120
    def get_list_positions(self, list1_values, search_dim):
121
        list_positions = []
122
123
        for value2 in list1_values:
124
            pos_appended = False
125
            for value1 in search_dim:
126
                if value1 == value2:
127
                    list_positions.append(search_dim.index(value1))
128
                    pos_appended = True
129
                    break
130
131
            if not pos_appended:
132
                list_positions.append(None)
133
134
        return list_positions
135
136
    def trafo_memory_warm_start(self, results):
137
        if results is None:
138
            return results
139
140
        df_positions_dict = {}
141
        for para_name in self.para_names:
142
            result_dim_values = list(results[para_name].values)
143
            search_dim = self.search_space[para_name]
144
145
            # if self.data_types[para_name] == "function":
146
            #     result_dim_values = [value.__name__ for value in result_dim_values]
147
148
            # print("\n para_name", para_name)
149
150
            # print(" result_dim_values", result_dim_values)
151
            # print(" search_dim", search_dim)
152
153
            list1_positions = self.get_list_positions(result_dim_values, search_dim)
154
155
            # remove None
156
            # list1_positions_ = [x for x in list1_positions if x is not None]
157
            df_positions_dict[para_name] = list1_positions
158
159
        results_new = pd.DataFrame(df_positions_dict)
160
        results_new["score"] = results["score"]
161
        results_new.dropna(how="any", inplace=True)
162
163
        return results_new
164