File size: 8,143 Bytes
4be2d4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"""
์œ ํ‹ธ๋ฆฌํ‹ฐ ํ•จ์ˆ˜
"""
import os
import io
import json
import pickle
import logging
import contextlib
import traceback
import numpy as np
import tensorflow as tf
from pathlib import Path
from tqdm import tqdm

class TqdmProgressCallback(tf.keras.callbacks.Callback):
    """
    TensorFlow ํ›ˆ๋ จ์„ ์œ„ํ•œ ์ปค์Šคํ…€ ์ฝœ๋ฐฑ
    """
    def __init__(self, epochs, verbose=1):
        super(TqdmProgressCallback, self).__init__()
        self.epochs = epochs
        self.verbose = verbose
        self.tqdm_bar = None
    
    def on_train_begin(self, logs=None):
        if self.verbose:
            self.tqdm_bar = tqdm(total=self.epochs, desc="Training", unit="epoch")
    
    def on_epoch_end(self, epoch, logs=None):
        if self.verbose:
            logs = logs or {}
            log_items = []
            for k, v in logs.items():
                if 'val_' not in k:  # ํ›ˆ๋ จ ์ง€ํ‘œ๋งŒ ์ถœ๋ ฅ
                    log_items.append(f"{k}: {v:.4f}")
            
            desc = ", ".join(log_items)
            self.tqdm_bar.set_description(desc)
            self.tqdm_bar.update(1)
    
    def on_train_end(self, logs=None):
        if self.verbose and self.tqdm_bar is not None:
            self.tqdm_bar.close()
            print("ํ•™์Šต ์™„๋ฃŒ!")

def get_project_root():
    """
    ํ”„๋กœ์ ํŠธ ๋ฃจํŠธ ๋””๋ ‰ํ† ๋ฆฌ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค
    """
    return Path(__file__).parent.parent.parent

def ensure_directory(directory_path):
    """
    ๋””๋ ‰ํ† ๋ฆฌ๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฉด ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
    """
    Path(directory_path).mkdir(parents=True, exist_ok=True)
    return Path(directory_path)

def normalize_path(path_str, base_dir=None):
    """
    ์ƒ๋Œ€ ๊ฒฝ๋กœ๋ฅผ ์ ˆ๋Œ€ ๊ฒฝ๋กœ๋กœ ๋ณ€ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
    """
    path = Path(path_str)
    
    if path.is_absolute():
        return path
    
    if base_dir is None:
        base_dir = get_project_root()
    
    return Path(base_dir) / path

def save_model(model, model_path, config=None, encoders=None):
    """
    ๋ชจ๋ธ์„ TensorFlow Lite ํ˜•์‹์œผ๋กœ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.
    """
    model_path = Path(model_path)
    ensure_directory(model_path.parent)
    
    # TensorFlow ๋กœ๊ทธ ๋ ˆ๋ฒจ ์ž„์‹œ ์กฐ์ •
    original_tf_log_level = os.environ.get('TF_CPP_MIN_LOG_LEVEL', '')
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
    
    tf_logger = logging.getLogger('tensorflow')
    original_tf_level = tf_logger.level
    tf_logger.setLevel(logging.ERROR)
    
    try:
        # .tflite ํ™•์žฅ์ž๋กœ ๋ณ€๊ฒฝ
        if not str(model_path).endswith('.tflite'):
            model_path = Path(str(model_path).replace('.keras', '').replace('.h5', '') + '.tflite')
        
        # TensorFlow Lite ๋ณ€ํ™˜
        print("TensorFlow Lite ๋ชจ๋ธ๋กœ ๋ณ€ํ™˜ ์ค‘...")
        converter = tf.lite.TFLiteConverter.from_keras_model(model)
        
        # LSTM ํ˜ธํ™˜์„ฑ์„ ์œ„ํ•œ ์„ค์ •
        converter.optimizations = [tf.lite.Optimize.DEFAULT]
        converter.target_spec.supported_ops = [
            tf.lite.OpsSet.TFLITE_BUILTINS,    # ๊ธฐ๋ณธ TFLite ์—ฐ์‚ฐ
            tf.lite.OpsSet.SELECT_TF_OPS       # ์ถ”๊ฐ€ TensorFlow ์—ฐ์‚ฐ ํ—ˆ์šฉ
        ]
        converter._experimental_lower_tensor_list_ops = False  # TensorList ๋ณ€ํ™˜ ๋น„ํ™œ์„ฑํ™”
        converter.allow_custom_ops = True  # ์ปค์Šคํ…€ ์—ฐ์‚ฐ ํ—ˆ์šฉ
        
        # ๋ณ€ํ™˜ ์‹คํ–‰
        with contextlib.redirect_stdout(io.StringIO()):
            with contextlib.redirect_stderr(io.StringIO()):
                tflite_model = converter.convert()
        
        # TFLite ๋ชจ๋ธ ์ €์žฅ
        with open(model_path, 'wb') as f:
            f.write(tflite_model)
        
        print(f"TensorFlow Lite ๋ชจ๋ธ์ด {model_path}์— ์ €์žฅ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.")
        
        # ๋ชจ๋ธ ํŒŒ์ผ ๊ธฐ๋ณธ๋ช… ์ถ”์ถœ
        model_stem = model_path.stem
        
        # ์ธ์ฝ”๋” ์ •๋ณด ์ €์žฅ
        if encoders is not None:
            encoder_path = model_path.parent / f"{model_stem}_encoders.json"
            with open(encoder_path, 'w') as f:
                json.dump(encoders, f, indent=2)
            print(f"์ธ์ฝ”๋” ์ •๋ณด๊ฐ€ {encoder_path}์— ์ €์žฅ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.")
        
        # ๋ชจ๋ธ ์„ค์ • ์ €์žฅ
        if config is not None:
            config_path = model_path.parent / f"{model_stem}_config.json"
            with open(config_path, 'w') as f:
                # ์ง๋ ฌํ™” ๊ฐ€๋Šฅํ•œ ํ˜•ํƒœ๋กœ ๋ณ€ํ™˜
                json_safe_config = {k: str(v) if not isinstance(v, (int, float, str, bool, list, dict)) else v 
                                  for k, v in config.items()}
                json.dump(json_safe_config, f, indent=2)
            print(f"๋ชจ๋ธ ์„ค์ •์ด {config_path}์— ์ €์žฅ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.")
        
        return True
    
    finally:
        # ์›๋ž˜ ๋กœ๊ทธ ์„ค์ • ๋ณต์›
        tf_logger.setLevel(original_tf_level)
        if original_tf_log_level:
            os.environ['TF_CPP_MIN_LOG_LEVEL'] = original_tf_log_level
        else:
            os.environ.pop('TF_CPP_MIN_LOG_LEVEL', None)

def load_tflite_model(model_path):
    """
    TensorFlow Lite ๋ชจ๋ธ์„ ๋กœ๋“œํ•ฉ๋‹ˆ๋‹ค.
    """
    try:
        # TFLite ์ธํ„ฐํ”„๋ฆฌํ„ฐ ์ƒ์„ฑ
        interpreter = tf.lite.Interpreter(model_path=str(model_path))
        interpreter.allocate_tensors()
        
        print(f"TensorFlow Lite ๋ชจ๋ธ์ด {model_path}์—์„œ ์„ฑ๊ณต์ ์œผ๋กœ ๋กœ๋“œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.")
        return interpreter
    
    except Exception as e:
        print(f"TensorFlow Lite ๋ชจ๋ธ ๋กœ๋“œ ์‹คํŒจ: {e}")
        print(traceback.format_exc())
        return None

def predict_with_tflite(interpreter, inputs, verbose=False):
    """
    TensorFlow Lite ๋ชจ๋ธ๋กœ ์˜ˆ์ธก ์ˆ˜ํ–‰
    """
    try:
        # ์ž…๋ ฅ ํ…์„œ ์ •๋ณด ๊ฐ€์ ธ์˜ค๊ธฐ
        input_details = interpreter.get_input_details()
        output_details = interpreter.get_output_details()
        
        # ๊ฐ ์ž…๋ ฅ ์„ค์ •
        for i, input_tensor in enumerate(inputs):
            if i < len(input_details):
                interpreter.set_tensor(input_details[i]['index'], input_tensor)
        
        # ์‹คํ–‰
        interpreter.invoke()
        
        # ์ถœ๋ ฅ ๊ฐ€์ ธ์˜ค๊ธฐ
        outputs = []
        for output_detail in output_details:
            output = interpreter.get_tensor(output_detail['index'])
            outputs.append(output)
        
        return outputs if len(outputs) > 1 else outputs[0]
        
    except Exception as e:
        print("์˜ˆ์ธก ์‹คํŒจ")
        return None

def save_results(results, output_path, include_model=False):
    """
    ์ตœ์ ํ™” ๊ฒฐ๊ณผ๋ฅผ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.
    """
    output_path = Path(output_path)
    ensure_directory(output_path.parent)
    
    # ๊ฒฐ๊ณผ ๋ณต์‚ฌ๋ณธ ์ƒ์„ฑ
    pickle_safe_results = {
        'grid_results': [],
        'best_config': results.get('best_config', {})
    }
    
    # ๋ชจ๋ธ ๊ฐ์ฒด ์ œ๊ฑฐํ•œ ๊ฒฐ๊ณผ ๋ณต์‚ฌ
    results_list = results.get('results', [])
    if not results_list and 'best_result' in results:
        results_list = [results['best_result']]
    
    for result in results_list:
        result_copy = result.copy()
        if not include_model and 'model' in result_copy:
            del result_copy['model']
        pickle_safe_results['grid_results'].append(result_copy)
    
    # ํ…Œ์ŠคํŠธ ๊ฒฐ๊ณผ ์ถ”๊ฐ€
    if 'test_backtest' in results:
        pickle_safe_results['test_backtest'] = results['test_backtest']
    
    # ๊ฒฐ๊ณผ ์ €์žฅ
    with open(output_path, 'wb') as f:
        pickle.dump(pickle_safe_results, f)
    print(f"์ตœ์ ํ™” ๊ฒฐ๊ณผ๊ฐ€ {output_path}์— ์ €์žฅ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.")
    
    return True

def save_metadata(metadata, output_path):
    """
    ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ๋ฅผ JSON ํ˜•์‹์œผ๋กœ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.
    """
    output_path = Path(output_path)
    ensure_directory(output_path.parent)
    
    # ์ง๋ ฌํ™” ๊ฐ€๋Šฅํ•œ ํ˜•ํƒœ๋กœ ๋ณ€ํ™˜
    json_safe_metadata = {k: str(v) if not isinstance(v, (int, float, str, bool, list, dict)) else v 
                       for k, v in metadata.items()}
    
    with open(output_path, 'w') as f:
        json.dump(json_safe_metadata, f, indent=2)
    print(f"๋ฉ”ํƒ€๋ฐ์ดํ„ฐ๊ฐ€ {output_path}์— ์ €์žฅ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.")
    
    return True