Passed
Push — master ( b3cc5b...cdf567 )
by Simon
01:59
created

LongTermMemory.save_memory()   B

Complexity

Conditions 6

Size

Total Lines 47
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 34
dl 0
loc 47
rs 8.1306
c 0
b 0
f 0
cc 6
nop 4
1
# Author: Simon Blanke
2
# Email: [email protected]
3
# License: MIT License
4
5
import os
6
import glob
7
import json
8
import dill
9
import pickle
10
import datetime
11
import hashlib
12
import inspect
13
14
import numpy as np
15
import pandas as pd
16
17
18
class Memory:
19
    def __init__(self, _space_, _main_args_, _cand_):
20
        self._space_ = _space_
21
        self._main_args_ = _main_args_
22
23
        self.pos_best = None
24
        self.score_best = -np.inf
25
26
        self.memory_type = _main_args_.memory
27
        self.memory_dict = {}
28
29
        self.meta_data_found = False
30
31
32
class ShortTermMemory(Memory):
33
    def __init__(self, _space_, _main_args_, _cand_):
34
        super().__init__(_space_, _main_args_, _cand_)
35
36
37
class LongTermMemory(Memory):
38
    def __init__(self, _space_, _main_args_, _cand_):
39
        super().__init__(_space_, _main_args_, _cand_)
40
41
        self.score_col_name = "mean_test_score"
42
43
        current_path = os.path.realpath(__file__)
44
        meta_learn_path, _ = current_path.rsplit("/", 1)
45
46
        self.datetime = datetime.datetime.now().strftime("%d.%m.%Y - %H:%M:%S") + "/"
47
        func_str = self._get_func_str(_cand_.func_)
48
        self.func_path_ = self._get_hash(func_str.encode("utf-8")) + "/"
49
50
        self.meta_path = meta_learn_path + "/meta_data/"
51
        self.func_path = self.meta_path + self.func_path_
52
        self.date_path = self.meta_path + self.func_path_ + self.datetime
53
54
        if not os.path.exists(self.date_path):
55
            os.makedirs(self.date_path, exist_ok=True)
56
57
    def load_memory(self, model_func):
58
        para, score = self._read_func_metadata(model_func)
59
        if para is None or score is None:
60
            return
61
62
        self._load_data_into_memory(para, score)
63
64
    def save_memory(self, _main_args_, _opt_args_, _cand_):
65
66
        path = self._get_file_path(_cand_.func_)
67
        meta_data = self._collect(_cand_)
68
69
        self._save_toCSV(meta_data, path)
70
71
        obj_func_path = self.func_path + "objective_function.py"
72
        if not os.path.exists(obj_func_path):
73
            file = open(obj_func_path, "w")
74
            file.write(self._get_func_str(_cand_.func_))
75
            file.close()
76
77
        search_config_path = self.date_path + "search_config.py"
78
        search_config_temp = dict(self._main_args_.search_config)
79
80
        for key in search_config_temp.keys():
81
            if isinstance(key, str):
82
                continue
83
            search_config_temp[key.__name__] = search_config_temp[key]
84
            del search_config_temp[key]
85
86
        search_config_str = "search_config = " + str(search_config_temp)
87
88
        if not os.path.exists(search_config_path):
89
            file = open(search_config_path, "w")
90
            file.write(search_config_str)
91
            file.close()
92
93
        os.chdir(self.date_path)
94
        os.system("black search_config.py")
95
        os.getcwd()
96
97
        run_data = {
98
            "random_state": self._main_args_.random_state,
99
            "max_time": self._main_args_.random_state,
100
            "n_iter": self._main_args_.n_iter,
101
            "optimizer": self._main_args_.optimizer,
102
            "n_jobs": self._main_args_.n_jobs,
103
            "eval_time": np.array(_cand_.eval_time).sum(),
104
            "total_time": _cand_.total_time,
105
        }
106
107
        with open("run_data.json", "w") as f:
108
            json.dump(run_data, f, indent=4)
109
110
        """
111
112
        print("_opt_args_.kwargs_opt", _opt_args_.kwargs_opt)
113
114
        opt_para = pd.DataFrame.from_dict(_opt_args_.kwargs_opt, dtype=object)
115
        print("opt_para", opt_para)
116
        opt_para.to_csv(
117
            self.meta_data_path + self.func_path + self.datetime + "opt_para",
118
            index=False,
119
        )
120
        """
121
122
    def _save_toCSV(self, meta_data_new, path):
123
        if os.path.exists(path):
124
            meta_data_old = pd.read_csv(path)
125
            meta_data = meta_data_old.append(meta_data_new)
126
127
            columns = list(meta_data.columns)
128
            noScore = ["mean_test_score", "cv_default_score"]
129
            columns_noScore = [c for c in columns if c not in noScore]
130
131
            meta_data = meta_data.drop_duplicates(subset=columns_noScore)
132
        else:
133
            meta_data = meta_data_new
134
135
        meta_data.to_csv(path, index=False)
136
137
    def _read_func_metadata(self, model_func):
138
        paths = self._get_func_data_names()
139
140
        meta_data_list = []
141
        for path in paths:
142
            meta_data = pd.read_csv(path)
143
            meta_data_list.append(meta_data)
144
            self.meta_data_found = True
145
146
        if len(meta_data_list) > 0:
147
            meta_data = pd.concat(meta_data_list, ignore_index=True)
148
149
            column_names = meta_data.columns
150
            score_name = [name for name in column_names if self.score_col_name in name]
151
152
            para = meta_data.drop(score_name, axis=1)
153
            score = meta_data[score_name]
154
155
            print("Loading meta data successful")
156
            return para, score
157
158
        else:
159
            print("Warning: No meta data found for following function:", model_func)
160
            return None, None
161
162
    def _get_opt_meta_data(self):
163
        results_dict = {}
164
        para_list = []
165
        score_list = []
166
167
        for key in self.memory_dict.keys():
168
            pos = np.fromstring(key, dtype=int)
169
            para = self._space_.pos2para(pos)
170
            score = self.memory_dict[key]
171
172
            for key in para.keys():
173
                if (
174
                    not isinstance(para[key], int)
175
                    and not isinstance(para[key], float)
176
                    and not isinstance(para[key], str)
177
                ):
178
179
                    para_dill = dill.dumps(para[key])
180
                    para_hash = self._get_hash(para_dill)
181
182
                    with open(
183
                        self.date_path + str(para_hash) + ".pkl", "wb"
184
                    ) as pickle_file:
185
                        dill.dump(para_dill, pickle_file)
186
187
                    para[key] = para_hash
188
189
            if score != 0:
190
                para_list.append(para)
191
                score_list.append(score)
192
193
        results_dict["params"] = para_list
194
        results_dict["mean_test_score"] = score_list
195
196
        return results_dict
197
198
    def _load_data_into_memory(self, paras, scores):
199
200
        for idx in range(paras.shape[0]):
201
            para = paras.iloc[[idx]]
202
203
            pos = self._space_.para2pos(paras.iloc[[idx]], self._get_pkl_hash)
204
            pos_str = pos.tostring()
205
206
            score = float(scores.values[idx])
207
            self.memory_dict[pos_str] = score
208
209
            if score > self.score_best:
210
                self.score_best = score
211
                self.pos_best = pos
212
213
    def _get_para(self):
214
        results_dict = self._get_opt_meta_data()
215
216
        return pd.DataFrame(results_dict["params"])
217
218
    def _get_score(self):
219
        results_dict = self._get_opt_meta_data()
220
        return pd.DataFrame(
221
            results_dict["mean_test_score"], columns=["mean_test_score"]
222
        )
223
224
    def _collect(self, _cand_):
225
        para_pd = self._get_para()
226
        metric_pd = self._get_score()
227
228
        eval_time = pd.DataFrame(_cand_.eval_time, columns=["eval_time"])
229
        md_model = pd.concat(
230
            [para_pd, metric_pd, eval_time], axis=1, ignore_index=False
231
        )
232
233
        return md_model
234
235
    def _get_hash(self, object):
236
        return hashlib.sha1(object).hexdigest()
237
238
    def _get_func_str(self, func):
239
        return inspect.getsource(func)
240
241
    def _get_subdirs(self):
242
        subdirs = glob.glob(self.func_path + "*/")
243
244
        return subdirs
245
246
    def _get_func_data_names(self):
247
        subdirs = self._get_subdirs()
248
249
        path_list = []
250
        for subdir in subdirs:
251
            paths = glob.glob(subdir + "*.csv")
252
            path_list = path_list + paths
253
254
        return path_list
255
256
    def _get_pkl_hash(self, hash):
257
        subdirs = self._get_subdirs()
258
259
        path_list = []
260
        for subdir in subdirs:
261
            paths = glob.glob(subdir + hash + "*.pkl")
262
            path_list = path_list + paths
263
264
        return path_list
265
266
    def _get_file_path(self, model_func):
267
        feature_hash = self._get_hash(self._main_args_.X)
268
        label_hash = self._get_hash(self._main_args_.y)
269
270
        if not os.path.exists(self.date_path):
271
            os.makedirs(self.date_path)
272
273
        return self.date_path + (feature_hash + "_" + label_hash + ".csv")
274