File size: 12,317 Bytes
5092c1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import pickle
import json
import numpy as np
import pandas as pd
from pathlib import Path
from typing import Dict, List, Optional, Union
import warnings

warnings.filterwarnings('ignore')


class EarlyWarningPredictor:
    """์ž์˜์—… ์กฐ๊ธฐ๊ฒฝ๋ณด ์˜ˆ์ธก ๋ชจ๋ธ"""

    def __init__(self, model_path: Optional[str] = None):
        self.model_path = Path(model_path) if model_path else Path(__file__).parent.parent / 'model'
        self.xgb_model = None
        self.lgb_model = None
        self.catboost_model = None
        self.label_encoders = {}
        self.feature_names = []
        self.config = {}
        self.is_loaded = False

    @classmethod
    def from_pretrained(cls, model_name_or_path: str):
        predictor = cls(model_path=model_name_or_path)
        predictor.load_model()
        return predictor

    def load_model(self):
        """๋ชจ๋ธ ๋ฐ ์„ค์ • ๋กœ๋“œ"""
        if not self.model_path.exists():
            raise FileNotFoundError(f"Model directory not found: {self.model_path}")

        # XGBoost ๋กœ๋“œ
        xgb_path = self.model_path / 'xgboost_model.pkl'
        if xgb_path.exists():
            with open(xgb_path, 'rb') as f:
                self.xgb_model = pickle.load(f)

        # LightGBM ๋กœ๋“œ
        lgb_path = self.model_path / 'lightgbm_model.pkl'
        if lgb_path.exists():
            with open(lgb_path, 'rb') as f:
                self.lgb_model = pickle.load(f)

        # CatBoost ๋กœ๋“œ
        catboost_path = self.model_path / 'catboost_model.pkl'
        if catboost_path.exists():
            with open(catboost_path, 'rb') as f:
                self.catboost_model = pickle.load(f)

        # Label Encoders ๋กœ๋“œ
        le_path = self.model_path / 'label_encoders.pkl'
        if le_path.exists():
            with open(le_path, 'rb') as f:
                self.label_encoders = pickle.load(f)

        # Feature names ๋กœ๋“œ
        fn_path = self.model_path / 'feature_names.json'
        if fn_path.exists():
            with open(fn_path, 'r', encoding='utf-8') as f:
                self.feature_names = json.load(f)

        # Config ๋กœ๋“œ
        config_path = self.model_path / 'config.json'
        if config_path.exists():
            with open(config_path, 'r', encoding='utf-8') as f:
                self.config = json.load(f)

        self.is_loaded = True
        print(f"๋ชจ๋ธ ๋กœ๋“œ ์™„๋ฃŒ: v{self.config.get('model_version', '2.0')}")

    def predict(self, store_data: Dict,
                monthly_usage: Optional[pd.DataFrame] = None,
                monthly_customers: Optional[pd.DataFrame] = None,
                threshold: Optional[float] = None) -> Dict:
        if not self.is_loaded:
            self.load_model()

        # ํŠน์ง• ์ƒ์„ฑ
        from src.feature_engineering import FeatureEngineer
        engineer = FeatureEngineer()

        if monthly_usage is None or monthly_customers is None:
            # ๊ฐ„๋‹จํ•œ ๋ฐ์ดํ„ฐ ํ˜•์‹
            features = self._create_simple_features(store_data)
        else:
            # ์ „์ฒด ํŠน์ง• ์ƒ์„ฑ
            features = engineer.create_features(store_data, monthly_usage, monthly_customers)

        # ํŠน์ง• ์ •๋ ฌ ๋ฐ ๊ฒฐ์ธก์น˜ ์ฒ˜๋ฆฌ
        features = self._align_features(features)

        # ์˜ˆ์ธก
        threshold = threshold or self.config.get('threshold', 0.5)

        if self.xgb_model and self.lgb_model:
            # ์•™์ƒ๋ธ” ์˜ˆ์ธก
            xgb_prob = self.xgb_model.predict_proba(features)[0][1]
            lgb_prob = self.lgb_model.predict_proba(features)[0][1]

            weights = self.config.get('ensemble_weights', [0.5, 0.5])
            closure_probability = weights[0] * xgb_prob + weights[1] * lgb_prob

            if self.catboost_model and len(weights) > 2:
                cat_prob = self.catboost_model.predict_proba(features)[0][1]
                closure_probability = (weights[0] * xgb_prob +
                                       weights[1] * lgb_prob +
                                       weights[2] * cat_prob)
        else:
            closure_probability = 0.5

        # ์œ„ํ—˜๋„ ์ ์ˆ˜(0-100)
        risk_score = closure_probability * 100

        # ์œ„ํ—˜ ๋“ฑ๊ธ‰
        if risk_score < 30:
            risk_level = '๋‚ฎ์Œ'
            risk_color = 'green'
        elif risk_score < 60:
            risk_level = '๋ณดํ†ต'
            risk_color = 'yellow'
        else:
            risk_level = '๋†’์Œ'
            risk_color = 'red'

        # ์˜ˆ์ธก ๊ฒฐ๊ณผ
        result = {
            'risk_score': round(risk_score, 2),
            'risk_level': risk_level,
            'risk_color': risk_color,
            'closure_probability': round(closure_probability, 4),
            'is_at_risk': closure_probability > threshold,
            'threshold': threshold,
            'confidence': max(closure_probability, 1 - closure_probability),
            'model_version': self.config.get('model_version', '2.0')
        }

        # ์œ„ํ—˜ ์š”์ธ ๋ถ„์„(ํŠน์ง• ์ค‘์š”๋„ ๊ธฐ๋ฐ˜)
        if self.xgb_model:
            result['risk_factors'] = self._analyze_risk_factors(features)

        # ์•ก์…˜ ์•„์ดํ…œ
        result['action_items'] = self._generate_action_items(result, store_data)

        return result

    def predict_batch(self, stores_df: pd.DataFrame) -> pd.DataFrame:
        results = []

        for idx, row in stores_df.iterrows():
            store_data = row.to_dict()
            result = self.predict(store_data)
            result['store_id'] = row.get('store_id', idx)
            results.append(result)

        return pd.DataFrame(results)

    def explain(self, store_data: Dict, top_n: int = 10) -> Dict:
        # SHAP ๋ถ„์„(๊ฐ„๋‹จํ•œ ๋ฒ„์ „)
        result = self.predict(store_data)

        explanation = {
            'prediction': result,
            'top_features': result.get('risk_factors', {}),
            'interpretation': self._interpret_prediction(result)
        }

        return explanation

    def _create_simple_features(self, store_data: Dict) -> pd.DataFrame:
        """๊ฐ„๋‹จํ•œ ํŠน์ง• ์ƒ์„ฑ"""
        # ๊ธฐ๋ณธ ํŠน์ง•๋งŒ ์‚ฌ์šฉ
        features = {
            'sales_avg_all': store_data.get('avg_sales', 50),
            'customer_reuse_rate': store_data.get('reuse_rate', 25),
            'operation_months': store_data.get('operating_months', 12),
            'trend_slope': store_data.get('sales_trend', 0),
        }

        # ๋‚˜๋จธ์ง€ ํŠน์ง•์€ ๊ธฐ๋ณธ๊ฐ’์œผ๋กœ
        for fname in self.feature_names:
            if fname not in features:
                features[fname] = 0

        return pd.DataFrame([features])

    def _align_features(self, features: pd.DataFrame) -> pd.DataFrame:
        """ํŠน์ง• ์ •๋ ฌ ๋ฐ ์ „์ฒ˜๋ฆฌ"""
        # ๋ชจ๋ธ ํ•™์Šต ์‹œ ์‚ฌ์šฉํ•œ ํŠน์ง• ์ˆœ์„œ๋กœ ์ •๋ ฌ
        aligned = pd.DataFrame()

        for fname in self.feature_names:
            if fname in features.columns:
                aligned[fname] = features[fname]
            else:
                aligned[fname] = 0

        # ๊ฒฐ์ธก์น˜ ์ฒ˜๋ฆฌ
        aligned = aligned.fillna(aligned.median().fillna(0))

        return aligned

    def _analyze_risk_factors(self, features: pd.DataFrame) -> Dict[str, float]:
        """์œ„ํ—˜ ์š”์ธ ๋ถ„์„"""
        # ํŠน์ง• ์ค‘์š”๋„ ๊ธฐ๋ฐ˜
        if not hasattr(self.xgb_model, 'feature_importances_'):
            return {}

        importance = self.xgb_model.feature_importances_
        feature_values = features.iloc[0].values

        # ์ค‘์š”๋„์™€ ๊ฐ’์„ ๊ณฑํ•ด์„œ ๊ธฐ์—ฌ๋„ ๊ณ„์‚ฐ
        contributions = {}

        for i, fname in enumerate(self.feature_names):
            if importance[i] > 0.01:  # ์ค‘์š”ํ•œ ํŠน์ง•๋งŒ
                score = importance[i] * abs(feature_values[i]) * 10

                # ํŠน์ง•๋ช…์„ ํ•œ๊ธ€๋กœ ๋ณ€ํ™˜
                readable_name = self._translate_feature_name(fname)
                contributions[readable_name] = min(round(score, 1), 100)

        # ์ƒ์œ„ 6๊ฐœ๋งŒ ๋ฐ˜ํ™˜
        sorted_factors = sorted(contributions.items(), key=lambda x: x[1], reverse=True)[:6]

        return dict(sorted_factors)

    def _translate_feature_name(self, fname: str) -> str:
        """ํŠน์ง•๋ช…์„ ์ฝ๊ธฐ ์‰ฌ์šด ํ˜•ํƒœ๋กœ ๋ณ€ํ™˜"""
        translations = {
            'sales_avg': '๋งค์ถœ',
            'trend_slope': '๋งค์ถœ ์ถ”์„ธ',
            'trend_consecutive_down': '์—ฐ์† ํ•˜๋ฝ',
            'customer_reuse_rate': '์žฌ์ด์šฉ๋ฅ ',
            'volatility_cv': '๋งค์ถœ ๋ณ€๋™์„ฑ',
            'operation_months': '์˜์—… ๊ธฐ๊ฐ„',
            'sales_recent_vs_previous': '์ตœ๊ทผ ๋งค์ถœ ๋ณ€ํ™”'
        }

        for key, value in translations.items():
            if key in fname:
                return value

        return fname

    def _generate_action_items(self, result: Dict, store_data: Dict) -> List[str]:
        """์•ก์…˜ ์•„์ดํ…œ ์ƒ์„ฑ"""
        actions = []

        risk_score = result['risk_score']

        if risk_score > 70:
            actions.append("์ฆ‰์‹œ ์กฐ์น˜ ํ•„์š”: ๋น„์šฉ ์ ˆ๊ฐ ๋ฐ ๋งค์ถœ ์ฆ๋Œ€ ๋ฐฉ์•ˆ ๋งˆ๋ จ")
            actions.append("ํ˜„๊ธˆํ๋ฆ„ ๊ฐœ์„ : ์™ธ์ƒ ๋งค์ถœ ํšŒ์ˆ˜ ๋ฐ ์žฌ๊ณ  ์ตœ์ ํ™”")
            actions.append("์ „๋ฌธ๊ฐ€ ์ƒ๋‹ด: ๊ฒฝ์˜ ์ปจ์„คํŒ… ๋ฐ ๊ตฌ์กฐ์กฐ์ • ๊ฒ€ํ† ")
        elif risk_score > 40:
            actions.append("๋งค์ถœ ๋ถ„์„: ์ฃผ๋ ฅ ์ƒํ’ˆ/์„œ๋น„์Šค ์žฌ์ ๊ฒ€")
            actions.append("๋งˆ์ผ€ํŒ… ๊ฐ•ํ™”: ์‹ ๊ทœ ๊ณ ๊ฐ ์œ ์น˜ ์บ ํŽ˜์ธ")
            actions.append("์ฐจ๋ณ„ํ™” ์ „๋žต: ๊ฒฝ์Ÿ๋ ฅ ์žˆ๋Š” ์š”์†Œ ๋ฐœ๊ตด ๋ฐ ๊ฐ•ํ™”")
        else:
            actions.append("ํ˜„์žฌ ์ƒํƒœ ์œ ์ง€: ์ •๊ธฐ์ ์ธ ๋ชจ๋‹ˆํ„ฐ๋ง ์ง€์†")
            actions.append("์„ฑ์žฅ ๊ธฐํšŒ ํƒ์ƒ‰: ์ถ”๊ฐ€ ๋งค์ถœ์› ๋ฐœ๊ตด")
            actions.append("๊ณ ๊ฐ ์ถฉ์„ฑ๋„ ๊ฐ•ํ™”: ๋ฉค๋ฒ„์‹ญ ํ”„๋กœ๊ทธ๋žจ ๋“ฑ")

        return actions

    def _interpret_prediction(self, result: Dict) -> str:
        """์˜ˆ์ธก ๊ฒฐ๊ณผ ํ•ด์„"""
        risk_level = result['risk_level']
        risk_score = result['risk_score']

        if risk_level == '๋†’์Œ':
            return f"์œ„ํ—˜๋„๊ฐ€ ๋งค์šฐ ๋†’์Šต๋‹ˆ๋‹ค ({risk_score:.1f}์ ). ํ์—… ์œ„ํ—˜์ด ๋†’์œผ๋ฏ€๋กœ ์ฆ‰๊ฐ์ ์ธ ๋Œ€์‘์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค."
        elif risk_level == '๋ณดํ†ต':
            return f"์ฃผ์˜๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค ({risk_score:.1f}์ ). ๊ฐœ์„  ๋ฐฉ์•ˆ์„ ๋งˆ๋ จํ•˜์—ฌ ์œ„ํ—˜์„ ์ค„์ด์„ธ์š”."
        else:
            return f"์•ˆ์ •์ ์ž…๋‹ˆ๋‹ค ({risk_score:.1f}์ ). ํ˜„์žฌ์˜ ์šด์˜ ๋ฐฉ์‹์„ ์œ ์ง€ํ•˜๋ฉด์„œ ์ง€์†์ ์œผ๋กœ ๋ชจ๋‹ˆํ„ฐ๋งํ•˜์„ธ์š”."

    def get_model_info(self) -> Dict:
        """๋ชจ๋ธ ์ •๋ณด ๋ฐ˜ํ™˜"""
        return {
            'version': self.config.get('model_version', '2.0'),
            'n_features': self.config.get('n_features', 0),
            'performance': self.config.get('performance', {}),
            'ensemble_weights': self.config.get('ensemble_weights', []),
            'models': {
                'xgboost': self.xgb_model is not None,
                'lightgbm': self.lgb_model is not None,
                'catboost': self.catboost_model is not None
            }
        }


if __name__ == "__main__":
    # ์‚ฌ์šฉ ์˜ˆ์‹œ
    print("=" * 70)
    print("Early Warning Predictor v2.0 ํ…Œ์ŠคํŠธ")
    print("=" * 70)

    # ๋ชจ๋ธ ๋กœ๋“œ
    predictor = EarlyWarningPredictor(model_path='../model')

    try:
        predictor.load_model()

        # ํ…Œ์ŠคํŠธ ๋ฐ์ดํ„ฐ
        store_data = {
            'store_id': 'TEST_001',
            'industry': '์นดํŽ˜',
            'location': '์„œ์šธ ๊ฐ•๋‚จ๊ตฌ',
            'avg_sales': 45,
            'reuse_rate': 22.5,
            'operating_months': 18,
            'sales_trend': -0.05
        }

        # ์˜ˆ์ธก
        result = predictor.predict(store_data)

        print("\n์˜ˆ์ธก ๊ฒฐ๊ณผ:")
        print(f"  ์œ„ํ—˜๋„ ์ ์ˆ˜: {result['risk_score']}/100")
        print(f"  ์œ„ํ—˜ ๋“ฑ๊ธ‰: {result['risk_level']}")
        print(f"  ํ์—… ํ™•๋ฅ : {result['closure_probability']:.1%}")

        if 'risk_factors' in result:
            print("\n์ฃผ์š” ์œ„ํ—˜ ์š”์ธ:")
            for factor, score in result['risk_factors'].items():
                print(f"    - {factor}: {score:.1f}์ ")

        print("\n์•ก์…˜ ์•„์ดํ…œ:")
        for action in result['action_items']:
            print(f"    {action}")

    except FileNotFoundError:
        print("๋ชจ๋ธ ํŒŒ์ผ์ด ์—†์Šต๋‹ˆ๋‹ค. ๋จผ์ € ๋ชจ๋ธ์„ ํ•™์Šตํ•ด์ฃผ์„ธ์š”.")