bong9513 commited on
Commit
af35fae
·
1 Parent(s): f681006

checkpoint

Browse files
Analysis_code/6.optima_models_analysis/analysis_for_.ipynb DELETED
The diff for this file is too large to render. See raw diff
 
Analysis_code/6.optima_models_analysis/extract_result_from_omptimized_models.ipynb CHANGED
@@ -307,7 +307,7 @@
307
  },
308
  {
309
  "cell_type": "code",
310
- "execution_count": 11,
311
  "id": "580e5ae9",
312
  "metadata": {},
313
  "outputs": [
@@ -398,7 +398,7 @@
398
  },
399
  {
400
  "cell_type": "code",
401
- "execution_count": null,
402
  "id": "0469a132",
403
  "metadata": {},
404
  "outputs": [],
@@ -413,7 +413,7 @@
413
  },
414
  {
415
  "cell_type": "code",
416
- "execution_count": null,
417
  "id": "2a58dc99",
418
  "metadata": {},
419
  "outputs": [],
@@ -423,7 +423,7 @@
423
  },
424
  {
425
  "cell_type": "code",
426
- "execution_count": null,
427
  "id": "3545f217",
428
  "metadata": {},
429
  "outputs": [
@@ -839,19 +839,214 @@
839
  },
840
  {
841
  "cell_type": "code",
842
- "execution_count": null,
843
  "id": "676b7afb",
844
  "metadata": {},
845
  "outputs": [],
846
- "source": []
 
 
 
847
  },
848
  {
849
  "cell_type": "code",
850
- "execution_count": null,
851
  "id": "0002db33",
852
  "metadata": {},
853
- "outputs": [],
854
- "source": []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
855
  }
856
  ],
857
  "metadata": {
 
307
  },
308
  {
309
  "cell_type": "code",
310
+ "execution_count": 9,
311
  "id": "580e5ae9",
312
  "metadata": {},
313
  "outputs": [
 
398
  },
399
  {
400
  "cell_type": "code",
401
+ "execution_count": 10,
402
  "id": "0469a132",
403
  "metadata": {},
404
  "outputs": [],
 
413
  },
414
  {
415
  "cell_type": "code",
416
+ "execution_count": 11,
417
  "id": "2a58dc99",
418
  "metadata": {},
419
  "outputs": [],
 
423
  },
424
  {
425
  "cell_type": "code",
426
+ "execution_count": 12,
427
  "id": "3545f217",
428
  "metadata": {},
429
  "outputs": [
 
839
  },
840
  {
841
  "cell_type": "code",
842
+ "execution_count": 16,
843
  "id": "676b7afb",
844
  "metadata": {},
845
  "outputs": [],
846
+ "source": [
847
+ "df= df_best_samples.loc[df_best_samples.groupby(['region','optimization_library'])['best_csi'].idxmax(),:]\n",
848
+ "df.sort_values(by=['region','best_csi'], ascending=False, inplace=True)"
849
+ ]
850
  },
851
  {
852
  "cell_type": "code",
853
+ "execution_count": 17,
854
  "id": "0002db33",
855
  "metadata": {},
856
+ "outputs": [
857
+ {
858
+ "data": {
859
+ "text/html": [
860
+ "<div>\n",
861
+ "<style scoped>\n",
862
+ " .dataframe tbody tr th:only-of-type {\n",
863
+ " vertical-align: middle;\n",
864
+ " }\n",
865
+ "\n",
866
+ " .dataframe tbody tr th {\n",
867
+ " vertical-align: top;\n",
868
+ " }\n",
869
+ "\n",
870
+ " .dataframe thead th {\n",
871
+ " text-align: right;\n",
872
+ " }\n",
873
+ "</style>\n",
874
+ "<table border=\"1\" class=\"dataframe\">\n",
875
+ " <thead>\n",
876
+ " <tr style=\"text-align: right;\">\n",
877
+ " <th></th>\n",
878
+ " <th>model</th>\n",
879
+ " <th>data_sample</th>\n",
880
+ " <th>region</th>\n",
881
+ " <th>optimization_library</th>\n",
882
+ " <th>best_csi</th>\n",
883
+ " <th>n_trials</th>\n",
884
+ " <th>best_params</th>\n",
885
+ " </tr>\n",
886
+ " </thead>\n",
887
+ " <tbody>\n",
888
+ " <tr>\n",
889
+ " <th>26</th>\n",
890
+ " <td>ft_transformer</td>\n",
891
+ " <td>ctgan10000</td>\n",
892
+ " <td>seoul</td>\n",
893
+ " <td>optuna</td>\n",
894
+ " <td>0.593658</td>\n",
895
+ " <td>100</td>\n",
896
+ " <td>{'d_token': 224, 'n_blocks': 4, 'n_heads': 8, ...</td>\n",
897
+ " </tr>\n",
898
+ " <tr>\n",
899
+ " <th>29</th>\n",
900
+ " <td>xgb</td>\n",
901
+ " <td>smote</td>\n",
902
+ " <td>seoul</td>\n",
903
+ " <td>hyperopt</td>\n",
904
+ " <td>0.591400</td>\n",
905
+ " <td>100</td>\n",
906
+ " <td>{'colsample_bytree': 0.9204650350059359, 'gamm...</td>\n",
907
+ " </tr>\n",
908
+ " <tr>\n",
909
+ " <th>24</th>\n",
910
+ " <td>xgb</td>\n",
911
+ " <td>smote</td>\n",
912
+ " <td>incheon</td>\n",
913
+ " <td>hyperopt</td>\n",
914
+ " <td>0.600000</td>\n",
915
+ " <td>100</td>\n",
916
+ " <td>{'colsample_bytree': 0.8863531635625073, 'gamm...</td>\n",
917
+ " </tr>\n",
918
+ " <tr>\n",
919
+ " <th>23</th>\n",
920
+ " <td>resnet_like</td>\n",
921
+ " <td>ctgan10000</td>\n",
922
+ " <td>incheon</td>\n",
923
+ " <td>optuna</td>\n",
924
+ " <td>0.587620</td>\n",
925
+ " <td>100</td>\n",
926
+ " <td>{'d_main': 160, 'd_hidden': 192, 'n_blocks': 3...</td>\n",
927
+ " </tr>\n",
928
+ " <tr>\n",
929
+ " <th>19</th>\n",
930
+ " <td>xgb</td>\n",
931
+ " <td>smote</td>\n",
932
+ " <td>gwangju</td>\n",
933
+ " <td>hyperopt</td>\n",
934
+ " <td>0.530000</td>\n",
935
+ " <td>100</td>\n",
936
+ " <td>{'colsample_bytree': 0.7658195937298418, 'gamm...</td>\n",
937
+ " </tr>\n",
938
+ " <tr>\n",
939
+ " <th>15</th>\n",
940
+ " <td>deepgbm</td>\n",
941
+ " <td>ctgan10000</td>\n",
942
+ " <td>gwangju</td>\n",
943
+ " <td>optuna</td>\n",
944
+ " <td>0.520403</td>\n",
945
+ " <td>100</td>\n",
946
+ " <td>{'d_main': 128, 'd_hidden': 192, 'n_blocks': 6...</td>\n",
947
+ " </tr>\n",
948
+ " <tr>\n",
949
+ " <th>14</th>\n",
950
+ " <td>xgb</td>\n",
951
+ " <td>smote</td>\n",
952
+ " <td>daejeon</td>\n",
953
+ " <td>hyperopt</td>\n",
954
+ " <td>0.537100</td>\n",
955
+ " <td>100</td>\n",
956
+ " <td>{'colsample_bytree': 0.733236256331133, 'gamma...</td>\n",
957
+ " </tr>\n",
958
+ " <tr>\n",
959
+ " <th>13</th>\n",
960
+ " <td>resnet_like</td>\n",
961
+ " <td>ctgan10000</td>\n",
962
+ " <td>daejeon</td>\n",
963
+ " <td>optuna</td>\n",
964
+ " <td>0.510177</td>\n",
965
+ " <td>100</td>\n",
966
+ " <td>{'d_main': 128, 'd_hidden': 256, 'n_blocks': 5...</td>\n",
967
+ " </tr>\n",
968
+ " <tr>\n",
969
+ " <th>9</th>\n",
970
+ " <td>xgb</td>\n",
971
+ " <td>smote</td>\n",
972
+ " <td>daegu</td>\n",
973
+ " <td>hyperopt</td>\n",
974
+ " <td>0.467200</td>\n",
975
+ " <td>100</td>\n",
976
+ " <td>{'colsample_bytree': 0.8132816721507904, 'gamm...</td>\n",
977
+ " </tr>\n",
978
+ " <tr>\n",
979
+ " <th>8</th>\n",
980
+ " <td>resnet_like</td>\n",
981
+ " <td>ctgan10000</td>\n",
982
+ " <td>daegu</td>\n",
983
+ " <td>optuna</td>\n",
984
+ " <td>0.460863</td>\n",
985
+ " <td>100</td>\n",
986
+ " <td>{'d_main': 96, 'd_hidden': 256, 'n_blocks': 3,...</td>\n",
987
+ " </tr>\n",
988
+ " <tr>\n",
989
+ " <th>1</th>\n",
990
+ " <td>ft_transformer</td>\n",
991
+ " <td>ctgan10000</td>\n",
992
+ " <td>busan</td>\n",
993
+ " <td>optuna</td>\n",
994
+ " <td>0.496046</td>\n",
995
+ " <td>100</td>\n",
996
+ " <td>{'d_token': 224, 'n_blocks': 2, 'n_heads': 8, ...</td>\n",
997
+ " </tr>\n",
998
+ " <tr>\n",
999
+ " <th>4</th>\n",
1000
+ " <td>xgb</td>\n",
1001
+ " <td>pure</td>\n",
1002
+ " <td>busan</td>\n",
1003
+ " <td>hyperopt</td>\n",
1004
+ " <td>0.494900</td>\n",
1005
+ " <td>100</td>\n",
1006
+ " <td>{'colsample_bytree': 0.8651175745135303, 'gamm...</td>\n",
1007
+ " </tr>\n",
1008
+ " </tbody>\n",
1009
+ "</table>\n",
1010
+ "</div>"
1011
+ ],
1012
+ "text/plain": [
1013
+ " model data_sample region optimization_library best_csi \\\n",
1014
+ "26 ft_transformer ctgan10000 seoul optuna 0.593658 \n",
1015
+ "29 xgb smote seoul hyperopt 0.591400 \n",
1016
+ "24 xgb smote incheon hyperopt 0.600000 \n",
1017
+ "23 resnet_like ctgan10000 incheon optuna 0.587620 \n",
1018
+ "19 xgb smote gwangju hyperopt 0.530000 \n",
1019
+ "15 deepgbm ctgan10000 gwangju optuna 0.520403 \n",
1020
+ "14 xgb smote daejeon hyperopt 0.537100 \n",
1021
+ "13 resnet_like ctgan10000 daejeon optuna 0.510177 \n",
1022
+ "9 xgb smote daegu hyperopt 0.467200 \n",
1023
+ "8 resnet_like ctgan10000 daegu optuna 0.460863 \n",
1024
+ "1 ft_transformer ctgan10000 busan optuna 0.496046 \n",
1025
+ "4 xgb pure busan hyperopt 0.494900 \n",
1026
+ "\n",
1027
+ " n_trials best_params \n",
1028
+ "26 100 {'d_token': 224, 'n_blocks': 4, 'n_heads': 8, ... \n",
1029
+ "29 100 {'colsample_bytree': 0.9204650350059359, 'gamm... \n",
1030
+ "24 100 {'colsample_bytree': 0.8863531635625073, 'gamm... \n",
1031
+ "23 100 {'d_main': 160, 'd_hidden': 192, 'n_blocks': 3... \n",
1032
+ "19 100 {'colsample_bytree': 0.7658195937298418, 'gamm... \n",
1033
+ "15 100 {'d_main': 128, 'd_hidden': 192, 'n_blocks': 6... \n",
1034
+ "14 100 {'colsample_bytree': 0.733236256331133, 'gamma... \n",
1035
+ "13 100 {'d_main': 128, 'd_hidden': 256, 'n_blocks': 5... \n",
1036
+ "9 100 {'colsample_bytree': 0.8132816721507904, 'gamm... \n",
1037
+ "8 100 {'d_main': 96, 'd_hidden': 256, 'n_blocks': 3,... \n",
1038
+ "1 100 {'d_token': 224, 'n_blocks': 2, 'n_heads': 8, ... \n",
1039
+ "4 100 {'colsample_bytree': 0.8651175745135303, 'gamm... "
1040
+ ]
1041
+ },
1042
+ "execution_count": 17,
1043
+ "metadata": {},
1044
+ "output_type": "execute_result"
1045
+ }
1046
+ ],
1047
+ "source": [
1048
+ "df"
1049
+ ]
1050
  }
1051
  ],
1052
  "metadata": {
Analysis_code/6.optima_models_analysis/utils.py DELETED
@@ -1,1077 +0,0 @@
1
- from joblib import load
2
- import pandas as pd
3
- import numpy as np
4
- import matplotlib.pyplot as plt
5
- import os
6
- import sys
7
- from contextlib import contextmanager
8
- from io import StringIO
9
- from typing import Optional, Tuple, List, Dict, Any
10
- from sklearn.metrics import confusion_matrix
11
- from sklearn.preprocessing import LabelEncoder
12
- import shap
13
- import torch
14
- import warnings
15
- # 모든 경고 무시
16
- warnings.filterwarnings('ignore')
17
- # SHAP 관련 경고 무시 (LayerNorm 등 unrecognized nn.Module 경고)
18
- warnings.filterwarnings('ignore', category=UserWarning, message='.*unrecognized nn.Module.*')
19
- warnings.filterwarnings('ignore', category=UserWarning, message='.*LayerNorm.*')
20
- warnings.filterwarnings('ignore', category=UserWarning, message='.*unrecognized.*')
21
- # SHAP 모듈에서 발생하는 모든 경고 무시
22
- warnings.filterwarnings('ignore', module='shap.*')
23
-
24
- # 모델 클래스 import를 위한 경로 설정 (PyTorch 모델 로드를 위해 필요)
25
- # 노트북 환경에서도 작동하도록 여러 방법 시도
26
- try:
27
- # 방법 1: __file__ 사용 (일반 Python 스크립트)
28
- current_file_dir = os.path.dirname(os.path.abspath(__file__))
29
- models_path = os.path.abspath(os.path.join(current_file_dir, '../models'))
30
- except NameError:
31
- # 방법 2: __file__이 없는 경우 (노트북 환경) - 현재 작업 디렉토리 기준
32
- cwd = os.getcwd()
33
- # Analysis_code 디렉토리를 찾기
34
- if 'Analysis_code' in cwd:
35
- analysis_code_dir = cwd[:cwd.index('Analysis_code') + len('Analysis_code')]
36
- models_path = os.path.join(analysis_code_dir, 'models')
37
- else:
38
- # 방법 3: 절대 경로 사용
39
- models_path = '/workspace/visibility_prediction/Analysis_code/models'
40
-
41
-
42
- if models_path not in sys.path:
43
- sys.path.insert(0, models_path)
44
-
45
- from ft_transformer import FTTransformer
46
- from resnet_like import ResNetLike
47
- from deepgbm import DeepGBM
48
-
49
- # ==========================================
50
- # 상수 정의
51
- # ==========================================
52
- FOLD_YEARS = [[2018, 2019], [2018, 2019], [2019, 2020]]
53
- TEST_YEAR = 2021
54
- DROP_COLUMNS = ['multi_class', 'year']
55
- FEATURE_COLUMNS = [
56
- 'temp_C', 'precip_mm', 'wind_speed', 'wind_dir', 'hm',
57
- 'vap_pressure', 'dewpoint_C', 'loc_pressure', 'sea_pressure',
58
- 'solarRad', 'snow_cm', 'cloudcover', 'lm_cloudcover', 'low_cloudbase',
59
- 'groundtemp', 'O3', 'NO2', 'PM10', 'PM25', 'year',
60
- 'month', 'hour', 'ground_temp - temp_C', 'hour_sin', 'hour_cos',
61
- 'month_sin', 'month_cos', 'multi_class'
62
- ]
63
-
64
-
65
- # ==========================================
66
- # 유틸리티 함수
67
- # ==========================================
68
- def calculate_csi(y_true: np.ndarray, y_pred: np.ndarray) -> float:
69
- """CSI(Critical Success Index) 점수를 계산합니다.
70
-
71
- Args:
72
- y_true: 실제 레이블
73
- y_pred: 예측 레이블
74
-
75
- Returns:
76
- CSI 점수 (0~1 사이의 값)
77
- """
78
- cm = confusion_matrix(y_true, y_pred)
79
-
80
- # 혼동 행렬에서 H(Hit), F(False alarm), M(Miss) 추출
81
- H = cm[0, 0] + cm[1, 1]
82
- F = cm[1, 0] + cm[2, 0] + cm[0, 1] + cm[2, 1]
83
- M = cm[0, 2] + cm[1, 2]
84
-
85
- # CSI 계산
86
- csi = H / (H + F + M + 1e-10)
87
- return csi
88
-
89
-
90
- def csi_metric(y_true: np.ndarray, pred_prob: np.ndarray) -> Tuple[str, float, bool]:
91
- """LightGBM용 CSI 메트릭 함수.
92
-
93
- Args:
94
- y_true: 실제 레이블
95
- pred_prob: 예측 확률 (shape: [n_samples, n_classes])
96
-
97
- Returns:
98
- ('CSI', score, higher_better) 튜플
99
- """
100
- y_pred_binary = np.argmax(pred_prob, axis=1)
101
- score = calculate_csi(y_true, y_pred_binary)
102
- return 'CSI', score, True
103
-
104
-
105
- def eval_metric_csi(y_true: np.ndarray, pred_prob: np.ndarray) -> float:
106
- """XGBoost용 CSI 메트릭 함수.
107
-
108
- Args:
109
- y_true: 실제 레이블
110
- pred_prob: 예측 확률
111
-
112
- Returns:
113
- CSI 점수의 음수값
114
- """
115
- pred = np.argmax(pred_prob, axis=1)
116
- csi = calculate_csi(y_true, pred)
117
- return -1*csi
118
-
119
- def add_derived_features(df: pd.DataFrame) -> pd.DataFrame:
120
- """
121
- 제거했던 파생 변수들을 복구
122
-
123
- Args:
124
- df: 데이터프레임
125
-
126
- Returns:
127
- 파생 변수가 추가된 데이터프레임
128
- """
129
- df = df.copy()
130
- df['hour_sin'] = np.sin(2 * np.pi * df['hour'] / 24)
131
- df['hour_cos'] = np.cos(2 * np.pi * df['hour'] / 24)
132
- df['month_sin'] = np.sin(2 * np.pi * df['month'] / 12)
133
- df['month_cos'] = np.cos(2 * np.pi * df['month'] / 12)
134
- df['ground_temp - temp_C'] = df['groundtemp'] - df['temp_C']
135
- return df
136
-
137
- def preprocessing(df: pd.DataFrame) -> pd.DataFrame:
138
- """데이터 전처리 함수.
139
-
140
- Args:
141
- df: 원본 데이터프레임
142
-
143
- Returns:
144
- 전처리된 데이터프레임
145
- """
146
- df = df[df.columns].copy()
147
- df['year'] = df['year'].astype('int')
148
- df['month'] = df['month'].astype('int')
149
- df['hour'] = df['hour'].astype('int')
150
- df = add_derived_features(df).copy()
151
- df['multi_class'] = df['multi_class'].astype('int')
152
- df.loc[df['wind_dir']=='정온', 'wind_dir'] = "0"
153
- df['wind_dir'] = df['wind_dir'].astype('int')
154
- df = df[FEATURE_COLUMNS].copy()
155
- return df
156
-
157
- def make_dataset_for_boosting_models(
158
- region: str,
159
- data_sample: str,
160
- fold_num: int
161
- ) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
162
- train_data = pd.read_csv(f"../../data/data_oversampled/{data_sample}/{data_sample}_{fold_num+1}_{region}.csv")
163
- val_data = pd.read_csv(f"../../data/data_for_modeling/{region}_train.csv")
164
- test_data = pd.read_csv(f"../../data/data_for_modeling/{region}_test.csv")
165
-
166
- train_data = preprocessing(train_data).copy()
167
- val_data = preprocessing(val_data).copy()
168
- test_data = preprocessing(test_data).copy()
169
-
170
- train_data = train_data.loc[train_data['year'].isin(FOLD_YEARS[fold_num]), :]
171
- val_data = val_data.loc[~val_data['year'].isin(FOLD_YEARS[fold_num]), :]
172
- test_data = test_data.loc[test_data['year'].isin([TEST_YEAR]), :]
173
-
174
- return train_data, val_data, test_data
175
-
176
- def load_model(model_name: str, region: str, data_sample: str) -> List[Any]:
177
- model_path = f"../save_model/{model_name}_optima/{model_name}_{data_sample}_{region}.pkl"
178
- models = load(model_path)
179
- return models
180
-
181
-
182
- # ==========================================
183
- # Tree-based 모델 SHAP 분석 함수
184
- # ==========================================
185
- def analyze_shap_values_across_folds(
186
- model_name: str,
187
- region: str,
188
- data_sample: str,
189
- target_class: int = 0,
190
- n_folds: int = 3,
191
- figsize: Tuple[int, int] = (20, 10),
192
- show_plot: bool = True,
193
- show_train_plot: bool = True,
194
- show_test_plot: bool = True,
195
- suppress_warnings: bool = True,
196
- top_n: int = 3
197
- ) -> Dict[str, Any]:
198
- """
199
- 여러 Fold 모델에 대해 SHAP 값을 계산하고 시각화하며, 상위 3개 변수의 기여도를 분석하는 함수.
200
- """
201
-
202
- # 결과를 저장할 리스트
203
- oof_shap_values = []
204
- oof_X_data = []
205
- test_shap_values = []
206
-
207
- # 모델 로드
208
- models = load_model(model_name, region, data_sample)
209
-
210
- if len(models) != n_folds:
211
- raise ValueError(f"로드된 모델 개수({len(models)})가 n_folds({n_folds})와 일치하지 않습니다.")
212
-
213
- # 각 Fold에 대해 SHAP 값 계산
214
- for fold_idx in range(n_folds):
215
- # 각 Fold에 해당하는 데이터 로드
216
- _, val_data, test_data = make_dataset_for_boosting_models(
217
- region, data_sample, fold_idx
218
- )
219
-
220
- # 검증 데이터 준비
221
- X_val = val_data.drop(columns=DROP_COLUMNS)
222
-
223
- # 테스트 데이터 준비 (첫 번째 fold에서만 저장, 나머지는 동일)
224
- if fold_idx == 0:
225
- X_test = test_data.drop(columns=DROP_COLUMNS)
226
-
227
- # SHAP Explainer 생성
228
- if suppress_warnings:
229
- with warnings.catch_warnings():
230
- warnings.filterwarnings('ignore', category=UserWarning, message='.*deprecated binary model format.*')
231
- explainer = shap.TreeExplainer(models[fold_idx].get_booster())
232
- else:
233
- explainer = shap.TreeExplainer(models[fold_idx].get_booster())
234
-
235
- # 검증 데이터에 대한 SHAP 값 계산
236
- shap_val = explainer.shap_values(X_val)
237
-
238
- # 타겟 클래스에 대한 SHAP 값만 추출
239
- if isinstance(shap_val, list):
240
- oof_shap_values.append(shap_val[target_class])
241
- else:
242
- oof_shap_values.append(shap_val)
243
-
244
- oof_X_data.append(X_val)
245
-
246
- # 테스트 데이터에 대한 SHAP 값 계산
247
- shap_test = explainer.shap_values(X_test)
248
-
249
- # 타겟 클래스에 대한 SHAP 값만 추출
250
- if isinstance(shap_test, list):
251
- test_shap_values.append(shap_test[target_class])
252
- else:
253
- test_shap_values.append(shap_test)
254
-
255
- # ==========================================
256
- # 데이터 통합
257
- # ==========================================
258
- # 훈련 기간(Train) 통합
259
- all_shap_train = np.concatenate(oof_shap_values, axis=0)
260
- all_X_train = pd.concat(oof_X_data, axis=0)
261
-
262
- # 테스트 기간(Test, 2021) 통합: 평균 사용
263
- all_shap_test = np.mean(test_shap_values, axis=0)
264
-
265
- # ==========================================
266
- # 상위 N개 변수 기여도(Cumulative Share) 계산
267
- # ==========================================
268
- feature_names = all_X_train.columns
269
-
270
- # Train 데이터 중요도 계산
271
- importance_df_train, top_n_features_train, top_n_share_train = _calculate_cumulative_share(
272
- all_shap_train, feature_names, top_n, period_name='Train Period'
273
- )
274
-
275
- # Test 데이터 중요도 계산
276
- if all_shap_test is not None:
277
- importance_df_test, top_n_features_test, top_n_share_test = _calculate_cumulative_share(
278
- all_shap_test, feature_names, top_n, period_name='Test Period'
279
- )
280
- print() # 마지막에 빈 줄 추가
281
- else:
282
- importance_df_test = None
283
- top_n_share_test = None
284
- top_n_features_test = None
285
-
286
- # ==========================================
287
- # 통합 Feature Importance DataFrame 생성
288
- # ==========================================
289
- importance_df_combined = _create_combined_importance_df(
290
- importance_df_train, importance_df_test, feature_names
291
- )
292
-
293
- # ==========================================
294
- # 시각화
295
- # ==========================================
296
- if show_plot:
297
- _plot_shap_summary(
298
- all_shap_train, all_X_train, all_shap_test, X_test,
299
- list(all_X_train.columns), target_class, top_n,
300
- top_n_share_train=top_n_share_train, top_n_share_test=top_n_share_test,
301
- show_train_plot=show_train_plot, show_test_plot=show_test_plot, figsize=figsize,
302
- model_name=model_name, data_sample=data_sample, region=region
303
- )
304
-
305
- # 결과 반환
306
- return {
307
- 'shap_train': all_shap_train,
308
- 'X_train': all_X_train,
309
- 'shap_test': all_shap_test,
310
- 'X_test': X_test,
311
- 'top_n_features_train': top_n_features_train, # Train 상위 N개 변수 리스트
312
- 'top_n_share_train': top_n_share_train, # Train 상위 N개 누적 기여도(%)
313
- 'importance_df_train': importance_df_train, # Train 전체 중요도 순위표
314
- 'top_n_features_test': top_n_features_test, # Test 상위 N개 변수 리스트
315
- 'top_n_share_test': top_n_share_test, # Test 상위 N개 누적 기여도(%)
316
- 'importance_df_test': importance_df_test, # Test 전체 중요도 순위표
317
- 'importance_df_combined': importance_df_combined # Train/Test 통합 중요도 DataFrame
318
- }
319
-
320
-
321
- # ==========================================
322
- # 딥러닝 모델 SHAP 분석 헬퍼 클래스 및 함수
323
- # ==========================================
324
-
325
- @contextmanager
326
- def suppress_shap_output():
327
- """SHAP DeepExplainer의 출력을 억제하는 컨텍스트 매니저."""
328
- old_stdout = sys.stdout
329
- sys.stdout = StringIO()
330
- try:
331
- with warnings.catch_warnings():
332
- warnings.simplefilter('ignore')
333
- yield
334
- finally:
335
- sys.stdout = old_stdout
336
-
337
-
338
- class ModelWrapper(torch.nn.Module):
339
- """PyTorch 모델을 SHAP DeepExplainer에 맞게 래핑하는 클래스."""
340
-
341
- def __init__(self, base_model, numerical_cols):
342
- super().__init__()
343
- self.base_model = base_model
344
- self.num_features = len(numerical_cols)
345
-
346
- def forward(self, *inputs):
347
- """SHAP이 리스트로 전달하는 경우 처리"""
348
- if len(inputs) == 1 and isinstance(inputs[0], (list, tuple)):
349
- x_num, x_cat = inputs[0]
350
- elif len(inputs) == 2:
351
- x_num, x_cat = inputs
352
- else:
353
- # 단일 입력 (ResNet-like의 경우)
354
- x = inputs[0]
355
- x_num = x[:, :self.num_features]
356
- x_cat = x[:, self.num_features:].long()
357
- return self.base_model(x_num, x_cat)
358
-
359
- # categorical을 float로 받아서 long으로 변환 (SHAP gradient 계산을 위해)
360
- if x_cat.dtype != torch.long:
361
- x_cat = x_cat.long()
362
-
363
- return self.base_model(x_num, x_cat)
364
-
365
-
366
- def _create_shap_explainer(
367
- model_name: str,
368
- wrapped_model: torch.nn.Module,
369
- X_bg_num: torch.Tensor,
370
- X_bg_cat: torch.Tensor,
371
- device: str
372
- ) -> shap.DeepExplainer:
373
- """SHAP DeepExplainer를 생성하는 헬퍼 함수.
374
-
375
- Args:
376
- model_name: 모델 이름 ('ft_transformer', 'resnet_like', 'deepgbm')
377
- wrapped_model: 래핑된 PyTorch 모델
378
- X_bg_num: 배경 데이터 (numerical)
379
- X_bg_cat: 배경 데이터 (categorical)
380
- device: 연산 장치
381
-
382
- Returns:
383
- shap.DeepExplainer: 생성된 Explainer
384
- """
385
- with suppress_shap_output():
386
- if model_name in ('ft_transformer', 'deepgbm'):
387
- X_bg_cat_float = X_bg_cat.float()
388
- explainer = shap.DeepExplainer(wrapped_model, [X_bg_num, X_bg_cat_float])
389
- elif model_name == 'resnet_like':
390
- X_bg_combined = torch.cat([X_bg_num, X_bg_cat.float()], dim=1)
391
- explainer = shap.DeepExplainer(wrapped_model, X_bg_combined)
392
- else:
393
- raise ValueError(f"Unknown model_name: {model_name}")
394
-
395
- return explainer
396
-
397
-
398
- def _calculate_shap_values(
399
- explainer: shap.DeepExplainer,
400
- model_name: str,
401
- X_sample_num: torch.Tensor,
402
- X_sample_cat: torch.Tensor,
403
- device: str
404
- ) -> Any:
405
- """SHAP 값을 계산하는 헬퍼 함수.
406
-
407
- Args:
408
- explainer: SHAP DeepExplainer
409
- model_name: 모델 이름 ('ft_transformer', 'resnet_like', 'deepgbm')
410
- X_sample_num: 샘플 데이터 (numerical)
411
- X_sample_cat: 샘플 데이터 (categorical)
412
- device: 연산 장치
413
-
414
- Returns:
415
- SHAP 값 (다양한 형태 가능)
416
- """
417
- with suppress_shap_output():
418
- if model_name in ('ft_transformer', 'deepgbm'):
419
- X_sample_cat_float = X_sample_cat.float()
420
- shap_values = explainer.shap_values([X_sample_num, X_sample_cat_float])
421
- elif model_name == 'resnet_like':
422
- X_sample_combined = torch.cat([X_sample_num, X_sample_cat.float()], dim=1)
423
- shap_values = explainer.shap_values(X_sample_combined)
424
- else:
425
- raise ValueError(f"Unknown model_name: {model_name}")
426
-
427
- return shap_values
428
-
429
-
430
- def _calculate_cumulative_share(
431
- shap_values: np.ndarray,
432
- feature_names: List[str],
433
- top_n: int,
434
- period_name: str = ''
435
- ) -> Tuple[pd.DataFrame, List[str], float]:
436
- """누적 설명력(Cumulative Share)을 계산하는 헬퍼 함수.
437
-
438
- Args:
439
- shap_values: SHAP 값 배열
440
- feature_names: 피처 이름 리스트
441
- top_n: 상위 N개 변수
442
- period_name: 기간 이름 (콘솔 출력용, 기본값: '')
443
-
444
- Returns:
445
- tuple: (importance_df, top_n_features, top_n_share)
446
- """
447
- # 1. Global Importance 계산 (절대값의 평균)
448
- global_importances = np.abs(shap_values).mean(axis=0)
449
-
450
- # 2. DataFrame 생성 및 정렬
451
- importance_df = pd.DataFrame({
452
- 'feature': feature_names,
453
- 'importance': global_importances
454
- }).sort_values('importance', ascending=False)
455
-
456
- # 3. 전체 중요도 합계
457
- total_importance = importance_df['importance'].sum()
458
-
459
- # 4. 상위 N개 변수 추출 및 기여도 계산
460
- top_n_df = importance_df.head(top_n)
461
- top_n_importance = top_n_df['importance'].sum()
462
- top_n_share = (top_n_importance / total_importance) * 100
463
- top_n_features = top_n_df['feature'].tolist()
464
-
465
- # 5. 콘솔 출력
466
- if period_name:
467
- print(f"{period_name} - Top {top_n} Dominant Features: {top_n_features}")
468
- print(f"{period_name} - Cumulative Importance Share (Top {top_n}): {top_n_share:.2f}%")
469
- else:
470
- print(f"Top {top_n} Dominant Features: {top_n_features}")
471
- print(f"Cumulative Importance Share (Top {top_n}): {top_n_share:.2f}%")
472
- print(f"{'-'*40}")
473
-
474
- return importance_df, top_n_features, top_n_share
475
-
476
-
477
- def _create_combined_importance_df(
478
- importance_df_train: Optional[pd.DataFrame],
479
- importance_df_test: Optional[pd.DataFrame],
480
- feature_names: List[str]
481
- ) -> Optional[pd.DataFrame]:
482
- """Train과 Test 중요도 DataFrame을 통합하는 헬퍼 함수.
483
-
484
- Args:
485
- importance_df_train: Train 데이터 중요도 DataFrame
486
- importance_df_test: Test 데이터 중요도 DataFrame
487
- feature_names: 피처 이름 리스트
488
-
489
- Returns:
490
- 통합된 중요도 DataFrame 또는 None
491
- """
492
- if importance_df_train is None and importance_df_test is None:
493
- return None
494
-
495
- # Train 데이터 준비
496
- if importance_df_train is not None:
497
- train_df = importance_df_train[['feature', 'importance']].copy()
498
- train_df.columns = ['feature', 'importance_train']
499
- total_importance_train = train_df['importance_train'].sum()
500
- train_df['share_train'] = (train_df['importance_train'] / total_importance_train) * 100
501
- else:
502
- train_df = pd.DataFrame({'feature': feature_names})
503
- train_df['importance_train'] = np.nan
504
- train_df['share_train'] = np.nan
505
-
506
- # Test 데이터 준비
507
- if importance_df_test is not None:
508
- test_df = importance_df_test[['feature', 'importance']].copy()
509
- test_df.columns = ['feature', 'importance_test']
510
- total_importance_test = test_df['importance_test'].sum()
511
- test_df['share_test'] = (test_df['importance_test'] / total_importance_test) * 100
512
- else:
513
- test_df = pd.DataFrame({'feature': feature_names})
514
- test_df['importance_test'] = np.nan
515
- test_df['share_test'] = np.nan
516
-
517
- # Merge하여 통합 DataFrame 생성
518
- importance_df_combined = pd.merge(train_df, test_df, on='feature', how='outer')
519
-
520
- # 정렬
521
- if importance_df_train is not None:
522
- importance_df_combined = importance_df_combined.sort_values(
523
- 'importance_train', ascending=False
524
- ).reset_index(drop=True)
525
- elif importance_df_test is not None:
526
- importance_df_combined = importance_df_combined.sort_values(
527
- 'importance_test', ascending=False
528
- ).reset_index(drop=True)
529
- else:
530
- importance_df_combined = importance_df_combined.sort_values('feature').reset_index(drop=True)
531
-
532
- return importance_df_combined
533
-
534
-
535
- def _plot_shap_summary(
536
- shap_train: Optional[np.ndarray],
537
- X_train: Optional[pd.DataFrame],
538
- shap_test: Optional[np.ndarray],
539
- X_test: Optional[pd.DataFrame],
540
- feature_names: List[str],
541
- target_class: int,
542
- top_n: int,
543
- top_n_share_train: Optional[float] = None,
544
- top_n_share_test: Optional[float] = None,
545
- show_train_plot: bool = True,
546
- show_test_plot: bool = True,
547
- figsize: Tuple[int, int] = (12, 8),
548
- model_name: Optional[str] = None,
549
- data_sample: Optional[str] = None,
550
- region: Optional[str] = None
551
- ) -> None:
552
- """SHAP summary plot을 생성하는 헬퍼 함수.
553
-
554
- Args:
555
- shap_train: Train 데이터 SHAP 값
556
- X_train: Train 데이터
557
- shap_test: Test 데이터 SHAP 값
558
- X_test: Test 데이터
559
- feature_names: 피처 이름 리스트
560
- target_class: 타겟 클래스
561
- top_n: 상위 N개 변수
562
- top_n_share_train: Train 상위 N개 누적 기여도 (기본값: None)
563
- top_n_share_test: Test 상위 N개 누적 기여도 (기본값: None)
564
- show_train_plot: Train plot 표시 여부
565
- show_test_plot: Test plot 표시 여부
566
- figsize: 그림 크기
567
- model_name: 모델 이름 (기본값: None)
568
- data_sample: 데이터 샘플 타입 (기본값: None)
569
- region: 지역명 (기본값: None)
570
- """
571
- num_plots = int(show_train_plot and shap_train is not None) + int(show_test_plot and shap_test is not None)
572
- if num_plots == 0:
573
- return
574
-
575
- # Title prefix 생성 (모델명, 데이터 샘플, 지역 정보)
576
- title_parts = []
577
- if model_name is not None:
578
- title_parts.append(model_name.upper())
579
- if data_sample is not None:
580
- title_parts.append(data_sample)
581
- if region is not None:
582
- title_parts.append(region.upper())
583
-
584
- if title_parts:
585
- title_prefix = " - ".join(title_parts) + "\n"
586
- else:
587
- title_prefix = ""
588
-
589
- if num_plots == 2:
590
- plt.subplots(1, 2, figsize=figsize)
591
-
592
- if show_train_plot and shap_train is not None:
593
- plt.subplot(1, 2, 1)
594
- shap.summary_plot(shap_train, X_train[feature_names] if isinstance(X_train, pd.DataFrame) else X_train,
595
- show=False, plot_size=None)
596
- share_text = f"\nTop {top_n} Share: {top_n_share_train:.1f}%" if top_n_share_train is not None else ""
597
- plt.title(f"{title_prefix}Train Period (2018-20): Class {target_class}{share_text}")
598
-
599
- if show_test_plot and shap_test is not None:
600
- plt.subplot(1, 2, 2)
601
- shap.summary_plot(shap_test, X_test[feature_names] if isinstance(X_test, pd.DataFrame) else X_test,
602
- show=False, plot_size=None)
603
- share_text = f"\nTop {top_n} Share: {top_n_share_test:.1f}%" if top_n_share_test is not None else ""
604
- plt.title(f"{title_prefix}Test Period (2021): Class {target_class}{share_text}")
605
- else:
606
- plt.figure(figsize=(figsize[0]//2, figsize[1]))
607
- if show_train_plot and shap_train is not None:
608
- data = X_train[feature_names] if isinstance(X_train, pd.DataFrame) else X_train
609
- shap_v = shap_train
610
- share_text = f"\nTop {top_n} Share: {top_n_share_train:.1f}%" if top_n_share_train is not None else ""
611
- title = f"{title_prefix}Train Period (2018-20): Class {target_class}{share_text}"
612
- elif show_test_plot and shap_test is not None:
613
- data = X_test[feature_names] if isinstance(X_test, pd.DataFrame) else X_test
614
- shap_v = shap_test
615
- share_text = f"\nTop {top_n} Share: {top_n_share_test:.1f}%" if top_n_share_test is not None else ""
616
- title = f"{title_prefix}Test Period (2021): Class {target_class}{share_text}"
617
- else:
618
- return
619
-
620
- shap.summary_plot(shap_v, data, show=False)
621
- plt.title(title)
622
-
623
- plt.tight_layout()
624
- plt.show()
625
-
626
-
627
- def _to_numpy(value: Any) -> np.ndarray:
628
- """다양한 타입을 numpy array로 변환하는 헬퍼 함수."""
629
- if isinstance(value, torch.Tensor):
630
- return value.cpu().numpy()
631
- elif isinstance(value, list):
632
- return np.array(value)
633
- elif isinstance(value, np.ndarray):
634
- return value
635
- else:
636
- return np.array(value)
637
-
638
-
639
- def _combine_num_cat_shap(shap_num: Any, shap_cat: Any) -> np.ndarray:
640
- """Numerical과 categorical SHAP 값을 결합하는 헬퍼 함수."""
641
- shap_num = _to_numpy(shap_num)
642
- shap_cat = _to_numpy(shap_cat)
643
- return np.concatenate([shap_num, shap_cat], axis=-1)
644
-
645
-
646
- def _extract_from_list_of_tuples(shap_list: List[Tuple]) -> np.ndarray:
647
- """튜플 리스트에서 SHAP 값을 추출하는 헬퍼 함수."""
648
- combined = []
649
- for shap_item in shap_list:
650
- if isinstance(shap_item, tuple):
651
- combined.append(_combine_num_cat_shap(shap_item[0], shap_item[1]))
652
- else:
653
- combined.append(_to_numpy(shap_item))
654
- return np.array(combined)
655
-
656
-
657
- def _extract_from_list(shap_list: List[Any]) -> np.ndarray:
658
- """리스트에서 SHAP 값을 추출하는 헬퍼 함수."""
659
- if len(shap_list) == 0:
660
- return np.array([])
661
-
662
- # 튜플 리스트인 경우
663
- if isinstance(shap_list[0], tuple):
664
- return _extract_from_list_of_tuples(shap_list)
665
-
666
- # 길이가 2이고 각각이 numerical/categorical인 경우
667
- if len(shap_list) == 2:
668
- return _combine_num_cat_shap(shap_list[0], shap_list[1])
669
-
670
- # 일반 리스���인 경우
671
- try:
672
- return np.array([_to_numpy(item) for item in shap_list])
673
- except (ValueError, TypeError):
674
- # 형태가 일치하지 않는 경우, concatenate 시도
675
- converted = [_to_numpy(item) for item in shap_list]
676
- if len(converted) == 2:
677
- return np.concatenate(converted, axis=-1)
678
- else:
679
- return np.array(converted)
680
-
681
-
682
- def extract_shap_values(shap_values: Any, target_class: int = 0) -> np.ndarray:
683
- """SHAP 값을 추출하여 numpy array로 변환하는 헬퍼 함수.
684
-
685
- Args:
686
- shap_values: SHAP 라이브러리에서 반환된 SHAP 값 (다양한 형태 가능)
687
- target_class: 분석할 클래스 인덱스 (기본값: 0)
688
-
689
- Returns:
690
- numpy.ndarray: 변환된 SHAP 값
691
- """
692
- # 튜플인 경우 (numerical, categorical 분리)
693
- if isinstance(shap_values, tuple):
694
- return _combine_num_cat_shap(shap_values[0], shap_values[1])
695
-
696
- # 리스트인 경우 (클래스별 SHAP 값)
697
- if isinstance(shap_values, list):
698
- target_shap = shap_values[target_class]
699
-
700
- # 튜플인 경우
701
- if isinstance(target_shap, tuple):
702
- return _combine_num_cat_shap(target_shap[0], target_shap[1])
703
-
704
- # 리스트인 경우
705
- if isinstance(target_shap, list):
706
- return _extract_from_list(target_shap)
707
-
708
- # Tensor 또는 기타 타입
709
- return _to_numpy(target_shap)
710
-
711
- # numpy array인 경우
712
- if isinstance(shap_values, np.ndarray):
713
- if len(shap_values.shape) == 3:
714
- return shap_values[:, target_class, :]
715
- return shap_values
716
-
717
- # 기타 타입
718
- return _to_numpy(shap_values)
719
-
720
- # ==========================================
721
- # 딥러닝 모델 데이터 로드 및 전처리 함수
722
- # ==========================================
723
-
724
- def load_scaler(model_name: str, region: str, data_sample: str) -> List[Any]:
725
- """
726
- 각 fold의 scaler를 로드하는 함수.
727
-
728
- Args:
729
- model_name: 모델 이름 (예: "ft_transformer", "resnet_like", "deepgbm")
730
- region: 지역명 (예: "seoul", "busan")
731
- data_sample: 데이터 샘플 타입 (예: "smote", "ctgan10000")
732
-
733
- Returns:
734
- list: 각 fold의 scaler 리스트 (3개)
735
- """
736
- # 파일명 생성
737
- if data_sample == 'pure':
738
- scaler_filename = f'{model_name}_pure_{region}_scaler.pkl'
739
- else:
740
- scaler_filename = f'{model_name}_{data_sample}_{region}_scaler.pkl'
741
-
742
- scaler_path = f'../save_model/{model_name}_optima/scaler/{scaler_filename}'
743
- scalers = load(scaler_path)
744
- return scalers
745
-
746
-
747
- def prepare_dl_data_for_shap(
748
- region: str,
749
- data_sample: str,
750
- fold_idx: int,
751
- scaler: Any
752
- ) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.Index, pd.Index,
753
- torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
754
- """
755
- 딥러닝 모델용 데이터 전처리 (scaler 적용, 텐서 변환).
756
-
757
- Args:
758
- region: 지역명
759
- data_sample: 데이터 샘플 타입
760
- fold_idx: Fold 인덱스 (0, 1, 2)
761
- scaler: 해당 fold의 scaler (QuantileTransformer)
762
-
763
- Returns:
764
- tuple: (X_train, X_val, X_test, categorical_cols, numerical_cols,
765
- X_train_num, X_train_cat, X_val_num, X_val_cat, X_test_num, X_test_cat)
766
- """
767
- # 파일 경로 설정
768
- if data_sample == 'pure':
769
- dat_path = f"../../data/data_for_modeling/{region}_train.csv"
770
- train_data = preprocessing(pd.read_csv(dat_path, index_col=0))
771
- train_data = train_data.loc[~train_data['year'].isin([TEST_YEAR - (fold_idx + 1)]), :]
772
- else:
773
- train_data = pd.read_csv(f"../../data/data_oversampled/{data_sample}/{data_sample}_{fold_idx+1}_{region}.csv")
774
- train_data = preprocessing(train_data)
775
-
776
- val_data = pd.read_csv(f"../../data/data_for_modeling/{region}_train.csv")
777
- val_data = preprocessing(val_data)
778
- val_data = val_data.loc[val_data['year'].isin([TEST_YEAR - (fold_idx + 1)]), :]
779
-
780
- test_data = pd.read_csv(f"../../data/data_for_modeling/{region}_test.csv")
781
- test_data = preprocessing(test_data)
782
- test_data = test_data.loc[test_data['year'].isin([TEST_YEAR]), :]
783
-
784
- # 컬럼 정렬 (일관성 유지)
785
- common_columns = train_data.columns.to_list()
786
- train_data = train_data[common_columns]
787
- val_data = val_data[common_columns]
788
- test_data = test_data[common_columns]
789
-
790
- # 설명변수 & 타겟 분리
791
-
792
- X_train = train_data.drop(columns=DROP_COLUMNS)
793
- X_val = val_data.drop(columns=DROP_COLUMNS)
794
- X_test = test_data.drop(columns=DROP_COLUMNS)
795
-
796
- # 범주형 & 연속형 변수 분리
797
- categorical_cols = X_train.select_dtypes(include=['object', 'category', 'int64']).columns
798
- numerical_cols = X_train.select_dtypes(include=['float64']).columns
799
-
800
- # 범주형 변수 Label Encoding (train 데이터 기준으로 학습)
801
- label_encoders = {}
802
- for col in categorical_cols:
803
- le = LabelEncoder()
804
- le.fit(X_train[col])
805
- label_encoders[col] = le
806
-
807
- # 변환 적용
808
- for col in categorical_cols:
809
- X_train[col] = label_encoders[col].transform(X_train[col])
810
- X_val[col] = label_encoders[col].transform(X_val[col])
811
- X_test[col] = label_encoders[col].transform(X_test[col])
812
-
813
- # 연속형 변수 Scaler 변환 (저장된 scaler 사용)
814
- X_train[numerical_cols] = scaler.transform(X_train[numerical_cols])
815
- X_val[numerical_cols] = scaler.transform(X_val[numerical_cols])
816
- X_test[numerical_cols] = scaler.transform(X_test[numerical_cols])
817
-
818
- # 텐서 변환
819
- X_train_num = torch.tensor(X_train[numerical_cols].values, dtype=torch.float32)
820
- X_train_cat = torch.tensor(X_train[categorical_cols].values, dtype=torch.long)
821
-
822
- X_val_num = torch.tensor(X_val[numerical_cols].values, dtype=torch.float32)
823
- X_val_cat = torch.tensor(X_val[categorical_cols].values, dtype=torch.long)
824
-
825
- X_test_num = torch.tensor(X_test[numerical_cols].values, dtype=torch.float32)
826
- X_test_cat = torch.tensor(X_test[categorical_cols].values, dtype=torch.long)
827
-
828
- return (X_train, X_val, X_test, categorical_cols, numerical_cols,
829
- X_train_num, X_train_cat, X_val_num, X_val_cat, X_test_num, X_test_cat)
830
-
831
-
832
- # ==========================================
833
- # 딥러닝 모델 SHAP 분석 메인 함수
834
- # ==========================================
835
-
836
- def analyze_dl_model_shap(
837
- model_name: str,
838
- region: str,
839
- data_sample: str,
840
- target_class: int = 0,
841
- n_folds: int = 3,
842
- n_background_samples: int = 200,
843
- n_test_samples: int = 500,
844
- device: str = 'cpu',
845
- figsize: Tuple[int, int] = (12, 8),
846
- show_plot: bool = True,
847
- show_train_plot: bool = True,
848
- show_test_plot: bool = True,
849
- top_n: int = 3
850
- ) -> Optional[Dict[str, Any]]:
851
- """
852
- 딥러닝 모델의 SHAP 값을 계산하고 시각화하는 함수.
853
-
854
- Args:
855
- model_name: 모델 이름 ('ft_transformer', 'resnet_like', 'deepgbm')
856
- region: 지역명
857
- data_sample: 데이터 샘플 타입
858
- target_class: 분석할 클래스 인덱스 (기본값: 0)
859
- n_folds: Fold 개수 (기본값: 3)
860
- n_background_samples: 배경 데이터 샘플 수 (기본값: 200)
861
- n_test_samples: 테스트 데이터 샘플 수 (기본값: 500)
862
- device: 연산 장치 ('cpu' 또는 'cuda', 기본값: 'cpu')
863
- figsize: 그림 크기 (기본값: (12, 8))
864
- show_plot: 시각화 표시 여부 (기본값: True)
865
- show_train_plot: Train(validation) 데이터 시각화 표시 여부 (기본값: True)
866
- show_test_plot: Test 데이터 시각화 표시 여부 (기본값: True)
867
- top_n: 상위 N개 변수 기여도 계산 (기본값: 3)
868
-
869
- Returns:
870
- dict: SHAP 값 및 관련 정보
871
- - shap_train: Train 데이터 SHAP 값
872
- - X_train: Train 데이터
873
- - shap_test: Test 데이터 SHAP 값
874
- - X_test: Test 데이터
875
- - feature_names: 피처 이름 리스트
876
- - model_name: 모델 이름
877
- - region: 지역명
878
- - data_sample: 데이터 샘플 타입
879
- - top_n_features_train: Train 상위 N개 변수 리스트
880
- - top_n_share_train: Train 상위 N개 누적 기여도(%)
881
- - importance_df_train: Train 전체 중요도 순위표
882
- - top_n_features_test: Test 상위 N개 변수 리스트
883
- - top_n_share_test: Test 상위 N개 누적 기여도(%)
884
- - importance_df_test: Test 전체 중요도 순위표
885
- - importance_df_combined: Train/Test 통합 중요도 DataFrame
886
- """
887
- print(f"[{model_name.upper()}] {region} - {data_sample} SHAP Analysis Start...")
888
-
889
- # 모델 및 scaler 로드
890
- try:
891
- models = load_model(model_name, region, data_sample)
892
- scalers = load_scaler(model_name, region, data_sample)
893
- except Exception as e:
894
- print(f"모델 또는 scaler 로드 실패: {e}")
895
- return None
896
-
897
- if len(models) != n_folds or len(scalers) != n_folds:
898
- raise ValueError(f"모델 개수({len(models)}) 또는 scaler 개수({len(scalers)})가 n_folds({n_folds})와 일치하지 않습니다.")
899
-
900
- # 각 fold의 SHAP 값 저장 (train과 test 분리)
901
- all_shap_train = []
902
- all_shap_test = []
903
- all_train_data = []
904
- all_test_data = []
905
- feature_names = None
906
-
907
- for fold_idx in range(n_folds):
908
- print(f" Processing Fold {fold_idx + 1}...")
909
-
910
- try:
911
- # 데이터 전처리
912
- (X_train, X_val, X_test, categorical_cols, numerical_cols,
913
- X_train_num, X_train_cat, X_val_num, X_val_cat, X_test_num, X_test_cat) = \
914
- prepare_dl_data_for_shap(region, data_sample, fold_idx, scalers[fold_idx])
915
-
916
- # Feature names 저장 (첫 번째 fold에서만)
917
- if feature_names is None:
918
- feature_names = list(numerical_cols) + list(categorical_cols)
919
-
920
- # 모델 준비
921
- model = models[fold_idx]
922
- model.to(device)
923
- model.eval()
924
-
925
- # 배경 데이터 샘플링 (validation 데이터 사용)
926
- n_bg = min(n_background_samples, len(X_val_num))
927
- bg_indices = np.random.choice(len(X_val_num), n_bg, replace=False)
928
- X_bg_num = X_val_num[bg_indices].to(device)
929
- X_bg_cat = X_val_cat[bg_indices].to(device)
930
-
931
- # Validation 데이터 샘플링 (train plot용)
932
- n_train = min(n_test_samples, len(X_val_num))
933
- # 배경 데이터와 겹치지 않도록 샘플링
934
- available_indices = np.setdiff1d(np.arange(len(X_val_num)), bg_indices)
935
- if len(available_indices) < n_train:
936
- train_indices = available_indices
937
- else:
938
- train_indices = np.random.choice(available_indices, n_train, replace=False)
939
- X_train_sample_num = X_val_num[train_indices].to(device)
940
- X_train_sample_cat = X_val_cat[train_indices].to(device)
941
-
942
- # 테스트 데이터 샘플링
943
- n_test = min(n_test_samples, len(X_test_num))
944
- test_indices = np.random.choice(len(X_test_num), n_test, replace=False)
945
- X_test_sample_num = X_test_num[test_indices].to(device)
946
- X_test_sample_cat = X_test_cat[test_indices].to(device)
947
-
948
- # SHAP Explainer 생성 및 계산
949
- try:
950
- # 모델 래핑
951
- wrapped_model = ModelWrapper(model, numerical_cols)
952
- wrapped_model.to(device)
953
- wrapped_model.eval()
954
-
955
- # Explainer 생성
956
- explainer = _create_shap_explainer(model_name, wrapped_model, X_bg_num, X_bg_cat, device)
957
-
958
- # Validation 데이터에 대한 SHAP 값 계산
959
- shap_values_train = _calculate_shap_values(
960
- explainer, model_name, X_train_sample_num, X_train_sample_cat, device
961
- )
962
- shap_val_train = extract_shap_values(shap_values_train, target_class)
963
- all_shap_train.append(shap_val_train)
964
- X_train_original = X_val.iloc[train_indices].copy()
965
- all_train_data.append(X_train_original)
966
-
967
- # Test 데이터에 대한 SHAP 값 계산
968
- shap_values_test = _calculate_shap_values(
969
- explainer, model_name, X_test_sample_num, X_test_sample_cat, device
970
- )
971
- shap_val_test = extract_shap_values(shap_values_test, target_class)
972
- all_shap_test.append(shap_val_test)
973
- X_test_original = X_test.iloc[test_indices].copy()
974
- all_test_data.append(X_test_original)
975
-
976
- except Exception as e:
977
- print(f" Warning: Fold {fold_idx + 1} SHAP 계산 실패: {e}")
978
- continue
979
- except Exception as e:
980
- print(f" Warning: Fold {fold_idx + 1} 처리 실패: {e}")
981
- continue
982
-
983
- if len(all_shap_train) == 0 and len(all_shap_test) == 0:
984
- print(" 모든 fold에서 SHAP 계산 실패")
985
- return None
986
-
987
- # ==========================================
988
- # 데이터 통합
989
- # ==========================================
990
- # Train(validation) 데이터 통합
991
- all_shap_train_combined = np.concatenate(all_shap_train, axis=0) if len(all_shap_train) > 0 else None
992
- all_train_data_combined = pd.concat(all_train_data, axis=0).reset_index(drop=True) if len(all_train_data) > 0 else None
993
-
994
- # Test 데이터 통합: 평균 사용
995
- if len(all_shap_test) > 0:
996
- all_shap_test_combined = np.mean(all_shap_test, axis=0)
997
- # Test 데이터는 첫 번째 fold만 사용
998
- all_test_data_combined = all_test_data[0] if len(all_test_data) > 0 else None
999
- else:
1000
- all_shap_test_combined = None
1001
- all_test_data_combined = None
1002
-
1003
- # ==========================================
1004
- # Train 데이터 상위 N개 변수 기여도(Cumulative Share) 계산
1005
- # ==========================================
1006
- if all_shap_train_combined is not None:
1007
- importance_df_train, top_n_features_train, top_n_share_train = _calculate_cumulative_share(
1008
- all_shap_train_combined, feature_names, top_n, period_name='Train Period'
1009
- )
1010
- else:
1011
- importance_df_train = None
1012
- top_n_share_train = None
1013
- top_n_features_train = None
1014
-
1015
- # ==========================================
1016
- # Test 데이터 상위 N개 변수 기여도(Cumulative Share) 계산
1017
- # ==========================================
1018
- if all_shap_test_combined is not None:
1019
- importance_df_test, top_n_features_test, top_n_share_test = _calculate_cumulative_share(
1020
- all_shap_test_combined, feature_names, top_n, period_name='Test Period'
1021
- )
1022
- print() # 마지막에 빈 줄 추가
1023
- else:
1024
- importance_df_test = None
1025
- top_n_share_test = None
1026
- top_n_features_test = None
1027
-
1028
- # ==========================================
1029
- # 통합 Feature Importance DataFrame 생성
1030
- # ==========================================
1031
- importance_df_combined = _create_combined_importance_df(
1032
- importance_df_train, importance_df_test, feature_names
1033
- )
1034
-
1035
- # ==========================================
1036
- # 시각화
1037
- # ==========================================
1038
- if show_plot:
1039
- _plot_shap_summary(
1040
- all_shap_train_combined, all_train_data_combined, all_shap_test_combined, all_test_data_combined,
1041
- feature_names, target_class, top_n,
1042
- top_n_share_train=top_n_share_train, top_n_share_test=top_n_share_test,
1043
- show_train_plot=show_train_plot, show_test_plot=show_test_plot, figsize=figsize,
1044
- model_name=model_name, data_sample=data_sample, region=region
1045
- )
1046
-
1047
- print(f" [{model_name.upper()}] SHAP Analysis Complete!\n")
1048
-
1049
- return {
1050
- 'shap_train': all_shap_train_combined,
1051
- 'X_train': all_train_data_combined[feature_names] if all_train_data_combined is not None else None,
1052
- 'shap_test': all_shap_test_combined,
1053
- 'X_test': all_test_data_combined[feature_names] if all_test_data_combined is not None else None,
1054
- 'feature_names': feature_names,
1055
- 'model_name': model_name,
1056
- 'region': region,
1057
- 'data_sample': data_sample,
1058
- 'top_n_features_train': top_n_features_train, # Train 상위 N개 변수 리스트
1059
- 'top_n_share_train': top_n_share_train, # Train 상위 N개 누적 기여도(%)
1060
- 'importance_df_train': importance_df_train, # Train 전체 중요도 순위표
1061
- 'top_n_features_test': top_n_features_test, # Test 상위 N개 변수 리스트
1062
- 'top_n_share_test': top_n_share_test, # Test 상위 N개 누적 기여도(%)
1063
- 'importance_df_test': importance_df_test, # Test 전체 중요도 순위표
1064
- 'importance_df_combined': importance_df_combined # Train/Test 통합 중요도 DataFrame
1065
- }
1066
-
1067
- def elbow_plot(result: Dict[str, Any]) -> None:
1068
- elbow = result['importance_df_combined'].loc[:,['feature','importance_train','share_train']]
1069
- elbow = elbow.sort_values('importance_train', ascending=False)
1070
- plt.figure(figsize=(8, 5))
1071
- plt.plot(range(1, len(elbow) + 1), elbow['share_train'].values, marker='o')
1072
- plt.xlabel('Feature Rank')
1073
- plt.ylabel('Share Train (%)')
1074
- plt.title('Elbow Plot for Feature Importance (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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "a19bb535",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "# utils.py는 같은 디렉토리에 있으므로 직접 import 가능\n",
11
+ "from utils import predict_test_proba, calculate_csi\n",
12
+ "import numpy as np\n",
13
+ "import pandas as pd"
14
+ ]
15
+ },
16
+ {
17
+ "cell_type": "code",
18
+ "execution_count": 2,
19
+ "id": "1048a139",
20
+ "metadata": {},
21
+ "outputs": [],
22
+ "source": [
23
+ "df= pd.read_csv(\"../6.optima_models_analysis/best_samples_best_datasample_per_model_per_region.csv\")\n",
24
+ "df= df.loc[df.groupby(['region','optimization_library'])['best_csi'].idxmax(),:]\n",
25
+ "df.sort_values(by=['region','best_csi'], ascending=False, inplace=True)"
26
+ ]
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "execution_count": 3,
31
+ "id": "67d96046",
32
+ "metadata": {},
33
+ "outputs": [
34
+ {
35
+ "data": {
36
+ "text/html": [
37
+ "<div>\n",
38
+ "<style scoped>\n",
39
+ " .dataframe tbody tr th:only-of-type {\n",
40
+ " vertical-align: middle;\n",
41
+ " }\n",
42
+ "\n",
43
+ " .dataframe tbody tr th {\n",
44
+ " vertical-align: top;\n",
45
+ " }\n",
46
+ "\n",
47
+ " .dataframe thead th {\n",
48
+ " text-align: right;\n",
49
+ " }\n",
50
+ "</style>\n",
51
+ "<table border=\"1\" class=\"dataframe\">\n",
52
+ " <thead>\n",
53
+ " <tr style=\"text-align: right;\">\n",
54
+ " <th></th>\n",
55
+ " <th>model</th>\n",
56
+ " <th>data_sample</th>\n",
57
+ " <th>region</th>\n",
58
+ " <th>optimization_library</th>\n",
59
+ " <th>best_csi</th>\n",
60
+ " <th>n_trials</th>\n",
61
+ " <th>best_params</th>\n",
62
+ " </tr>\n",
63
+ " </thead>\n",
64
+ " <tbody>\n",
65
+ " <tr>\n",
66
+ " <th>0</th>\n",
67
+ " <td>ft_transformer</td>\n",
68
+ " <td>ctgan10000</td>\n",
69
+ " <td>seoul</td>\n",
70
+ " <td>optuna</td>\n",
71
+ " <td>0.593658</td>\n",
72
+ " <td>100</td>\n",
73
+ " <td>{'d_token': 224, 'n_blocks': 4, 'n_heads': 8, ...</td>\n",
74
+ " </tr>\n",
75
+ " <tr>\n",
76
+ " <th>1</th>\n",
77
+ " <td>xgb</td>\n",
78
+ " <td>smote</td>\n",
79
+ " <td>seoul</td>\n",
80
+ " <td>hyperopt</td>\n",
81
+ " <td>0.591400</td>\n",
82
+ " <td>100</td>\n",
83
+ " <td>{'colsample_bytree': 0.9204650350059359, 'gamm...</td>\n",
84
+ " </tr>\n",
85
+ " <tr>\n",
86
+ " <th>5</th>\n",
87
+ " <td>xgb</td>\n",
88
+ " <td>smote</td>\n",
89
+ " <td>incheon</td>\n",
90
+ " <td>hyperopt</td>\n",
91
+ " <td>0.600000</td>\n",
92
+ " <td>100</td>\n",
93
+ " <td>{'colsample_bytree': 0.8863531635625073, 'gamm...</td>\n",
94
+ " </tr>\n",
95
+ " <tr>\n",
96
+ " <th>7</th>\n",
97
+ " <td>resnet_like</td>\n",
98
+ " <td>ctgan10000</td>\n",
99
+ " <td>incheon</td>\n",
100
+ " <td>optuna</td>\n",
101
+ " <td>0.587620</td>\n",
102
+ " <td>100</td>\n",
103
+ " <td>{'d_main': 160, 'd_hidden': 192, 'n_blocks': 3...</td>\n",
104
+ " </tr>\n",
105
+ " <tr>\n",
106
+ " <th>10</th>\n",
107
+ " <td>xgb</td>\n",
108
+ " <td>smote</td>\n",
109
+ " <td>gwangju</td>\n",
110
+ " <td>hyperopt</td>\n",
111
+ " <td>0.530000</td>\n",
112
+ " <td>100</td>\n",
113
+ " <td>{'colsample_bytree': 0.7658195937298418, 'gamm...</td>\n",
114
+ " </tr>\n",
115
+ " <tr>\n",
116
+ " <th>12</th>\n",
117
+ " <td>deepgbm</td>\n",
118
+ " <td>ctgan10000</td>\n",
119
+ " <td>gwangju</td>\n",
120
+ " <td>optuna</td>\n",
121
+ " <td>0.520403</td>\n",
122
+ " <td>100</td>\n",
123
+ " <td>{'d_main': 128, 'd_hidden': 192, 'n_blocks': 6...</td>\n",
124
+ " </tr>\n",
125
+ " <tr>\n",
126
+ " <th>15</th>\n",
127
+ " <td>xgb</td>\n",
128
+ " <td>smote</td>\n",
129
+ " <td>daejeon</td>\n",
130
+ " <td>hyperopt</td>\n",
131
+ " <td>0.537100</td>\n",
132
+ " <td>100</td>\n",
133
+ " <td>{'colsample_bytree': 0.733236256331133, 'gamma...</td>\n",
134
+ " </tr>\n",
135
+ " <tr>\n",
136
+ " <th>17</th>\n",
137
+ " <td>resnet_like</td>\n",
138
+ " <td>ctgan10000</td>\n",
139
+ " <td>daejeon</td>\n",
140
+ " <td>optuna</td>\n",
141
+ " <td>0.510177</td>\n",
142
+ " <td>100</td>\n",
143
+ " <td>{'d_main': 128, 'd_hidden': 256, 'n_blocks': 5...</td>\n",
144
+ " </tr>\n",
145
+ " <tr>\n",
146
+ " <th>20</th>\n",
147
+ " <td>xgb</td>\n",
148
+ " <td>smote</td>\n",
149
+ " <td>daegu</td>\n",
150
+ " <td>hyperopt</td>\n",
151
+ " <td>0.467200</td>\n",
152
+ " <td>100</td>\n",
153
+ " <td>{'colsample_bytree': 0.8132816721507904, 'gamm...</td>\n",
154
+ " </tr>\n",
155
+ " <tr>\n",
156
+ " <th>22</th>\n",
157
+ " <td>resnet_like</td>\n",
158
+ " <td>ctgan10000</td>\n",
159
+ " <td>daegu</td>\n",
160
+ " <td>optuna</td>\n",
161
+ " <td>0.460863</td>\n",
162
+ " <td>100</td>\n",
163
+ " <td>{'d_main': 96, 'd_hidden': 256, 'n_blocks': 3,...</td>\n",
164
+ " </tr>\n",
165
+ " <tr>\n",
166
+ " <th>25</th>\n",
167
+ " <td>ft_transformer</td>\n",
168
+ " <td>ctgan10000</td>\n",
169
+ " <td>busan</td>\n",
170
+ " <td>optuna</td>\n",
171
+ " <td>0.496046</td>\n",
172
+ " <td>100</td>\n",
173
+ " <td>{'d_token': 224, 'n_blocks': 2, 'n_heads': 8, ...</td>\n",
174
+ " </tr>\n",
175
+ " <tr>\n",
176
+ " <th>26</th>\n",
177
+ " <td>xgb</td>\n",
178
+ " <td>pure</td>\n",
179
+ " <td>busan</td>\n",
180
+ " <td>hyperopt</td>\n",
181
+ " <td>0.494900</td>\n",
182
+ " <td>100</td>\n",
183
+ " <td>{'colsample_bytree': 0.8651175745135303, 'gamm...</td>\n",
184
+ " </tr>\n",
185
+ " </tbody>\n",
186
+ "</table>\n",
187
+ "</div>"
188
+ ],
189
+ "text/plain": [
190
+ " model data_sample region optimization_library best_csi \\\n",
191
+ "0 ft_transformer ctgan10000 seoul optuna 0.593658 \n",
192
+ "1 xgb smote seoul hyperopt 0.591400 \n",
193
+ "5 xgb smote incheon hyperopt 0.600000 \n",
194
+ "7 resnet_like ctgan10000 incheon optuna 0.587620 \n",
195
+ "10 xgb smote gwangju hyperopt 0.530000 \n",
196
+ "12 deepgbm ctgan10000 gwangju optuna 0.520403 \n",
197
+ "15 xgb smote daejeon hyperopt 0.537100 \n",
198
+ "17 resnet_like ctgan10000 daejeon optuna 0.510177 \n",
199
+ "20 xgb smote daegu hyperopt 0.467200 \n",
200
+ "22 resnet_like ctgan10000 daegu optuna 0.460863 \n",
201
+ "25 ft_transformer ctgan10000 busan optuna 0.496046 \n",
202
+ "26 xgb pure busan hyperopt 0.494900 \n",
203
+ "\n",
204
+ " n_trials best_params \n",
205
+ "0 100 {'d_token': 224, 'n_blocks': 4, 'n_heads': 8, ... \n",
206
+ "1 100 {'colsample_bytree': 0.9204650350059359, 'gamm... \n",
207
+ "5 100 {'colsample_bytree': 0.8863531635625073, 'gamm... \n",
208
+ "7 100 {'d_main': 160, 'd_hidden': 192, 'n_blocks': 3... \n",
209
+ "10 100 {'colsample_bytree': 0.7658195937298418, 'gamm... \n",
210
+ "12 100 {'d_main': 128, 'd_hidden': 192, 'n_blocks': 6... \n",
211
+ "15 100 {'colsample_bytree': 0.733236256331133, 'gamma... \n",
212
+ "17 100 {'d_main': 128, 'd_hidden': 256, 'n_blocks': 5... \n",
213
+ "20 100 {'colsample_bytree': 0.8132816721507904, 'gamm... \n",
214
+ "22 100 {'d_main': 96, 'd_hidden': 256, 'n_blocks': 3,... \n",
215
+ "25 100 {'d_token': 224, 'n_blocks': 2, 'n_heads': 8, ... \n",
216
+ "26 100 {'colsample_bytree': 0.8651175745135303, 'gamm... "
217
+ ]
218
+ },
219
+ "execution_count": 3,
220
+ "metadata": {},
221
+ "output_type": "execute_result"
222
+ }
223
+ ],
224
+ "source": [
225
+ "df"
226
+ ]
227
+ },
228
+ {
229
+ "cell_type": "markdown",
230
+ "id": "791fe38f",
231
+ "metadata": {},
232
+ "source": [
233
+ "## 1. Seoul\n"
234
+ ]
235
+ },
236
+ {
237
+ "cell_type": "code",
238
+ "execution_count": 4,
239
+ "id": "998634af",
240
+ "metadata": {},
241
+ "outputs": [
242
+ {
243
+ "data": {
244
+ "text/plain": [
245
+ "0.3371710526315512"
246
+ ]
247
+ },
248
+ "execution_count": 4,
249
+ "metadata": {},
250
+ "output_type": "execute_result"
251
+ }
252
+ ],
253
+ "source": [
254
+ "probs, y_test = predict_test_proba(\n",
255
+ " model_name='ft_transformer',\n",
256
+ " region='seoul',\n",
257
+ " data_sample='ctgan10000',\n",
258
+ " device='cuda', # Tree-based 모델은 device 파라미터가 사용되지 않음\n",
259
+ " n_folds=3\n",
260
+ ")\n",
261
+ "probs_1 = np.mean(probs, axis=0)\n",
262
+ "calculate_csi(np.argmax(probs_1, axis=1), y_test)"
263
+ ]
264
+ },
265
+ {
266
+ "cell_type": "code",
267
+ "execution_count": 5,
268
+ "id": "a4f94ce4",
269
+ "metadata": {},
270
+ "outputs": [
271
+ {
272
+ "data": {
273
+ "text/plain": [
274
+ "0.3431294678315851"
275
+ ]
276
+ },
277
+ "execution_count": 5,
278
+ "metadata": {},
279
+ "output_type": "execute_result"
280
+ }
281
+ ],
282
+ "source": [
283
+ "probs, y_test = predict_test_proba(\n",
284
+ " model_name='xgb',\n",
285
+ " region='seoul',\n",
286
+ " data_sample='smote',\n",
287
+ " device='cuda', # Tree-based 모델은 device 파라미터가 사용되지 않음\n",
288
+ " n_folds=3\n",
289
+ ")\n",
290
+ "probs_2= np.mean(probs, axis=0)\n",
291
+ "calculate_csi(np.argmax(probs_2, axis=1), y_test)"
292
+ ]
293
+ },
294
+ {
295
+ "cell_type": "code",
296
+ "execution_count": 6,
297
+ "id": "69421641",
298
+ "metadata": {},
299
+ "outputs": [
300
+ {
301
+ "data": {
302
+ "text/plain": [
303
+ "0.35207823960877327"
304
+ ]
305
+ },
306
+ "execution_count": 6,
307
+ "metadata": {},
308
+ "output_type": "execute_result"
309
+ }
310
+ ],
311
+ "source": [
312
+ "final_pred = np.array([probs_1, probs_2])\n",
313
+ "final_pred = np.mean(final_pred, axis=0)\n",
314
+ "final_pred = np.argmax(final_pred, axis=1)\n",
315
+ "calculate_csi(final_pred, y_test)"
316
+ ]
317
+ },
318
+ {
319
+ "cell_type": "markdown",
320
+ "id": "586f2131",
321
+ "metadata": {},
322
+ "source": [
323
+ "## 2. Incheon"
324
+ ]
325
+ },
326
+ {
327
+ "cell_type": "code",
328
+ "execution_count": 7,
329
+ "id": "8518d772",
330
+ "metadata": {},
331
+ "outputs": [
332
+ {
333
+ "data": {
334
+ "text/plain": [
335
+ "0.5848329048842812"
336
+ ]
337
+ },
338
+ "execution_count": 7,
339
+ "metadata": {},
340
+ "output_type": "execute_result"
341
+ }
342
+ ],
343
+ "source": [
344
+ "probs, y_test = predict_test_proba(\n",
345
+ " model_name='xgb',\n",
346
+ " region='incheon',\n",
347
+ " data_sample='smote',\n",
348
+ " device='cuda', # Tree-based 모델은 device 파라미터가 사용되지 않음\n",
349
+ " n_folds=3\n",
350
+ ")\n",
351
+ "probs_1 = np.mean(probs, axis=0)\n",
352
+ "calculate_csi(np.argmax(probs_1, axis=1), y_test)\n"
353
+ ]
354
+ },
355
+ {
356
+ "cell_type": "code",
357
+ "execution_count": 8,
358
+ "metadata": {},
359
+ "outputs": [
360
+ {
361
+ "data": {
362
+ "text/plain": [
363
+ "0.5070785070784745"
364
+ ]
365
+ },
366
+ "execution_count": 8,
367
+ "metadata": {},
368
+ "output_type": "execute_result"
369
+ }
370
+ ],
371
+ "source": [
372
+ "probs, y_test = predict_test_proba(\n",
373
+ " model_name='resnet_like',\n",
374
+ " region='incheon',\n",
375
+ " data_sample='ctgan10000',\n",
376
+ " device='cuda', # Tree-based 모델은 device 파라미터가 사용되지 않음\n",
377
+ " n_folds=3\n",
378
+ ")\n",
379
+ "probs_2= np.mean(probs, axis=0)\n",
380
+ "calculate_csi(np.argmax(probs_2, axis=1), y_test)"
381
+ ]
382
+ },
383
+ {
384
+ "cell_type": "code",
385
+ "execution_count": 9,
386
+ "id": "1e156a8b",
387
+ "metadata": {},
388
+ "outputs": [
389
+ {
390
+ "data": {
391
+ "text/plain": [
392
+ "0.56152849740929"
393
+ ]
394
+ },
395
+ "execution_count": 9,
396
+ "metadata": {},
397
+ "output_type": "execute_result"
398
+ }
399
+ ],
400
+ "source": [
401
+ "final_pred = np.array([probs_1, probs_2])\n",
402
+ "final_pred = np.mean(final_pred, axis=0)\n",
403
+ "final_pred = np.argmax(final_pred, axis=1)\n",
404
+ "calculate_csi(final_pred, y_test)"
405
+ ]
406
+ },
407
+ {
408
+ "cell_type": "markdown",
409
+ "id": "41a294ed",
410
+ "metadata": {},
411
+ "source": [
412
+ "## 3. Gwangju"
413
+ ]
414
+ },
415
+ {
416
+ "cell_type": "code",
417
+ "execution_count": 10,
418
+ "id": "e3d931c2",
419
+ "metadata": {},
420
+ "outputs": [
421
+ {
422
+ "data": {
423
+ "text/plain": [
424
+ "0.49895397489534526"
425
+ ]
426
+ },
427
+ "execution_count": 10,
428
+ "metadata": {},
429
+ "output_type": "execute_result"
430
+ }
431
+ ],
432
+ "source": [
433
+ "probs, y_test = predict_test_proba(\n",
434
+ " model_name='xgb',\n",
435
+ " region='gwangju',\n",
436
+ " data_sample='smote',\n",
437
+ " device='cuda', # Tree-based 모델은 device 파라미터가 사용되지 않음\n",
438
+ " n_folds=3\n",
439
+ ")\n",
440
+ "probs_1 = np.mean(probs, axis=0)\n",
441
+ "calculate_csi(np.argmax(probs_1, axis=1), y_test)\n"
442
+ ]
443
+ },
444
+ {
445
+ "cell_type": "code",
446
+ "execution_count": 11,
447
+ "id": "35e6a123",
448
+ "metadata": {},
449
+ "outputs": [
450
+ {
451
+ "data": {
452
+ "text/plain": [
453
+ "0.4685314685314217"
454
+ ]
455
+ },
456
+ "execution_count": 11,
457
+ "metadata": {},
458
+ "output_type": "execute_result"
459
+ }
460
+ ],
461
+ "source": [
462
+ "probs, y_test = predict_test_proba(\n",
463
+ " model_name='deepgbm',\n",
464
+ " region='gwangju',\n",
465
+ " data_sample='ctgan10000',\n",
466
+ " device='cuda', # Tree-based 모델은 device 파라미터가 사용되지 않음\n",
467
+ " n_folds=3\n",
468
+ ")\n",
469
+ "probs_2= np.mean(probs, axis=0)\n",
470
+ "calculate_csi(np.argmax(probs_2, axis=1), y_test)"
471
+ ]
472
+ },
473
+ {
474
+ "cell_type": "code",
475
+ "execution_count": 12,
476
+ "id": "281bec8d",
477
+ "metadata": {},
478
+ "outputs": [
479
+ {
480
+ "data": {
481
+ "text/plain": [
482
+ "0.5052192066805318"
483
+ ]
484
+ },
485
+ "execution_count": 12,
486
+ "metadata": {},
487
+ "output_type": "execute_result"
488
+ }
489
+ ],
490
+ "source": [
491
+ "final_pred = np.array([probs_1, probs_2])\n",
492
+ "final_pred = np.mean(final_pred, axis=0)\n",
493
+ "final_pred = np.argmax(final_pred, axis=1)\n",
494
+ "calculate_csi(final_pred, y_test)"
495
+ ]
496
+ },
497
+ {
498
+ "cell_type": "markdown",
499
+ "id": "48178b79",
500
+ "metadata": {},
501
+ "source": [
502
+ "## 4. Daejeon"
503
+ ]
504
+ },
505
+ {
506
+ "cell_type": "code",
507
+ "execution_count": 13,
508
+ "id": "6531212c",
509
+ "metadata": {},
510
+ "outputs": [
511
+ {
512
+ "data": {
513
+ "text/plain": [
514
+ "0.394344069128013"
515
+ ]
516
+ },
517
+ "execution_count": 13,
518
+ "metadata": {},
519
+ "output_type": "execute_result"
520
+ }
521
+ ],
522
+ "source": [
523
+ "probs, y_test = predict_test_proba(\n",
524
+ " model_name='xgb',\n",
525
+ " region='daejeon',\n",
526
+ " data_sample='smote',\n",
527
+ " device='cuda', # Tree-based 모델은 device 파라미터가 사용되지 않음\n",
528
+ " n_folds=3\n",
529
+ ")\n",
530
+ "probs_1 = np.mean(probs, axis=0)\n",
531
+ "calculate_csi(np.argmax(probs_1, axis=1), y_test)\n"
532
+ ]
533
+ },
534
+ {
535
+ "cell_type": "code",
536
+ "execution_count": 14,
537
+ "id": "c7cdb38b",
538
+ "metadata": {},
539
+ "outputs": [
540
+ {
541
+ "data": {
542
+ "text/plain": [
543
+ "0.37882352941173497"
544
+ ]
545
+ },
546
+ "execution_count": 14,
547
+ "metadata": {},
548
+ "output_type": "execute_result"
549
+ }
550
+ ],
551
+ "source": [
552
+ "probs, y_test = predict_test_proba(\n",
553
+ " model_name='resnet_like',\n",
554
+ " region='daejeon',\n",
555
+ " data_sample='ctgan10000',\n",
556
+ " device='cuda', # Tree-based 모델은 device 파라미터가 사용되지 않음\n",
557
+ " n_folds=3\n",
558
+ ")\n",
559
+ "probs_2= np.mean(probs, axis=0)\n",
560
+ "calculate_csi(np.argmax(probs_2, axis=1), y_test)"
561
+ ]
562
+ },
563
+ {
564
+ "cell_type": "code",
565
+ "execution_count": 15,
566
+ "id": "be501df7",
567
+ "metadata": {},
568
+ "outputs": [
569
+ {
570
+ "data": {
571
+ "text/plain": [
572
+ "0.40776699029122915"
573
+ ]
574
+ },
575
+ "execution_count": 15,
576
+ "metadata": {},
577
+ "output_type": "execute_result"
578
+ }
579
+ ],
580
+ "source": [
581
+ "final_pred = np.array([probs_1, probs_2])\n",
582
+ "final_pred = np.mean(final_pred, axis=0)\n",
583
+ "final_pred = np.argmax(final_pred, axis=1)\n",
584
+ "calculate_csi(final_pred, y_test)"
585
+ ]
586
+ },
587
+ {
588
+ "cell_type": "markdown",
589
+ "id": "e2ccc35e",
590
+ "metadata": {},
591
+ "source": [
592
+ "## 5. Daegu"
593
+ ]
594
+ },
595
+ {
596
+ "cell_type": "code",
597
+ "execution_count": 16,
598
+ "id": "1f971cb1",
599
+ "metadata": {},
600
+ "outputs": [
601
+ {
602
+ "data": {
603
+ "text/plain": [
604
+ "0.2303523035229728"
605
+ ]
606
+ },
607
+ "execution_count": 16,
608
+ "metadata": {},
609
+ "output_type": "execute_result"
610
+ }
611
+ ],
612
+ "source": [
613
+ "probs, y_test = predict_test_proba(\n",
614
+ " model_name='xgb',\n",
615
+ " region='daegu',\n",
616
+ " data_sample='smote',\n",
617
+ " device='cuda', # Tree-based 모델은 device 파라미터가 사용되지 않음\n",
618
+ " n_folds=3\n",
619
+ ")\n",
620
+ "probs_1 = np.mean(probs, axis=0)\n",
621
+ "calculate_csi(np.argmax(probs_1, axis=1), y_test)\n"
622
+ ]
623
+ },
624
+ {
625
+ "cell_type": "code",
626
+ "execution_count": 17,
627
+ "id": "da36de77",
628
+ "metadata": {},
629
+ "outputs": [
630
+ {
631
+ "data": {
632
+ "text/plain": [
633
+ "0.27622377622367966"
634
+ ]
635
+ },
636
+ "execution_count": 17,
637
+ "metadata": {},
638
+ "output_type": "execute_result"
639
+ }
640
+ ],
641
+ "source": [
642
+ "probs, y_test = predict_test_proba(\n",
643
+ " model_name='resnet_like',\n",
644
+ " region='daegu',\n",
645
+ " data_sample='ctgan10000',\n",
646
+ " device='cuda', # Tree-based 모델은 device 파라미터가 사용되지 않음\n",
647
+ " n_folds=3\n",
648
+ ")\n",
649
+ "probs_2= np.mean(probs, axis=0)\n",
650
+ "calculate_csi(np.argmax(probs_2, axis=1), y_test)"
651
+ ]
652
+ },
653
+ {
654
+ "cell_type": "code",
655
+ "execution_count": 18,
656
+ "id": "500f73e4",
657
+ "metadata": {},
658
+ "outputs": [
659
+ {
660
+ "data": {
661
+ "text/plain": [
662
+ "0.2738853503183841"
663
+ ]
664
+ },
665
+ "execution_count": 18,
666
+ "metadata": {},
667
+ "output_type": "execute_result"
668
+ }
669
+ ],
670
+ "source": [
671
+ "final_pred = np.array([probs_1, probs_2])\n",
672
+ "final_pred = np.mean(final_pred, axis=0)\n",
673
+ "final_pred = np.argmax(final_pred, axis=1)\n",
674
+ "calculate_csi(final_pred, y_test)"
675
+ ]
676
+ },
677
+ {
678
+ "cell_type": "markdown",
679
+ "id": "8b22a8da",
680
+ "metadata": {},
681
+ "source": [
682
+ "## 6. Busan"
683
+ ]
684
+ },
685
+ {
686
+ "cell_type": "code",
687
+ "execution_count": 19,
688
+ "id": "74bfd797",
689
+ "metadata": {},
690
+ "outputs": [
691
+ {
692
+ "data": {
693
+ "text/plain": [
694
+ "0.441005802707845"
695
+ ]
696
+ },
697
+ "execution_count": 19,
698
+ "metadata": {},
699
+ "output_type": "execute_result"
700
+ }
701
+ ],
702
+ "source": [
703
+ "probs, y_test = predict_test_proba(\n",
704
+ " model_name='ft_transformer',\n",
705
+ " region='busan',\n",
706
+ " data_sample='ctgan10000',\n",
707
+ " device='cuda', # Tree-based 모델은 device 파라미터가 사용되지 않음\n",
708
+ " n_folds=3\n",
709
+ ")\n",
710
+ "probs_1 = np.mean(probs, axis=0)\n",
711
+ "calculate_csi(np.argmax(probs_1, axis=1), y_test)\n"
712
+ ]
713
+ },
714
+ {
715
+ "cell_type": "code",
716
+ "execution_count": 20,
717
+ "id": "66fc12e7",
718
+ "metadata": {},
719
+ "outputs": [
720
+ {
721
+ "data": {
722
+ "text/plain": [
723
+ "0.49767441860453543"
724
+ ]
725
+ },
726
+ "execution_count": 20,
727
+ "metadata": {},
728
+ "output_type": "execute_result"
729
+ }
730
+ ],
731
+ "source": [
732
+ "probs, y_test = predict_test_proba(\n",
733
+ " model_name='xgb',\n",
734
+ " region='busan',\n",
735
+ " data_sample='pure',\n",
736
+ " device='cuda', # Tree-based 모델은 device 파라미터가 사용되지 않음\n",
737
+ " n_folds=3\n",
738
+ ")\n",
739
+ "probs_2= np.mean(probs, axis=0)\n",
740
+ "calculate_csi(np.argmax(probs_2, axis=1), y_test)"
741
+ ]
742
+ },
743
+ {
744
+ "cell_type": "code",
745
+ "execution_count": 21,
746
+ "id": "78b1b5f8",
747
+ "metadata": {},
748
+ "outputs": [
749
+ {
750
+ "data": {
751
+ "text/plain": [
752
+ "0.4711934156377631"
753
+ ]
754
+ },
755
+ "execution_count": 21,
756
+ "metadata": {},
757
+ "output_type": "execute_result"
758
+ }
759
+ ],
760
+ "source": [
761
+ "final_pred = np.array([probs_1, probs_2])\n",
762
+ "final_pred = np.mean(final_pred, axis=0)\n",
763
+ "final_pred = np.argmax(final_pred, axis=1)\n",
764
+ "calculate_csi(final_pred, y_test)"
765
+ ]
766
+ }
767
+ ],
768
+ "metadata": {
769
+ "kernelspec": {
770
+ "display_name": "py39",
771
+ "language": "python",
772
+ "name": "python3"
773
+ },
774
+ "language_info": {
775
+ "codemirror_mode": {
776
+ "name": "ipython",
777
+ "version": 3
778
+ },
779
+ "file_extension": ".py",
780
+ "mimetype": "text/x-python",
781
+ "name": "python",
782
+ "nbconvert_exporter": "python",
783
+ "pygments_lexer": "ipython3",
784
+ "version": "3.9.18"
785
+ }
786
+ },
787
+ "nbformat": 4,
788
+ "nbformat_minor": 5
789
+ }
Analysis_code/7.ensemble/shap_utils.py ADDED
@@ -0,0 +1,1260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from joblib import load
2
+ import pandas as pd
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import os
6
+ import sys
7
+ from contextlib import contextmanager
8
+ from io import StringIO
9
+ from typing import Optional, Tuple, List, Dict, Any
10
+ from dataclasses import dataclass
11
+ from abc import ABC, abstractmethod
12
+ from sklearn.metrics import confusion_matrix
13
+ from sklearn.preprocessing import LabelEncoder
14
+ from scipy.stats import wasserstein_distance
15
+ import shap
16
+ import torch
17
+ import warnings
18
+
19
+ # 모든 경고 무시
20
+ warnings.filterwarnings('ignore')
21
+ warnings.filterwarnings('ignore', category=UserWarning, message='.*unrecognized nn.Module.*')
22
+ warnings.filterwarnings('ignore', category=UserWarning, message='.*LayerNorm.*')
23
+ warnings.filterwarnings('ignore', category=UserWarning, message='.*unrecognized.*')
24
+ warnings.filterwarnings('ignore', module='shap.*')
25
+
26
+ # 모델 클래스 import를 위한 경로 설정
27
+ try:
28
+ current_file_dir = os.path.dirname(os.path.abspath(__file__))
29
+ models_path = os.path.abspath(os.path.join(current_file_dir, '../models'))
30
+ except NameError:
31
+ cwd = os.getcwd()
32
+ if 'Analysis_code' in cwd:
33
+ analysis_code_dir = cwd[:cwd.index('Analysis_code') + len('Analysis_code')]
34
+ models_path = os.path.join(analysis_code_dir, 'models')
35
+ else:
36
+ models_path = '/workspace/visibility_prediction/Analysis_code/models'
37
+
38
+ if models_path not in sys.path:
39
+ sys.path.insert(0, models_path)
40
+
41
+ from ft_transformer import FTTransformer
42
+ from resnet_like import ResNetLike
43
+ from deepgbm import DeepGBM
44
+
45
+
46
+ # ==========================================
47
+ # 1. Config 클래스
48
+ # ==========================================
49
+
50
+ class SHAPConfig:
51
+ """SHAP 분석 설정을 관리하는 클래스."""
52
+
53
+ # 상수 정의
54
+ FOLD_YEARS = [[2018, 2019], [2018, 2019], [2019, 2020]]
55
+ TEST_YEAR = 2021
56
+ DROP_COLUMNS = ['multi_class', 'year']
57
+ FEATURE_COLUMNS = [
58
+ 'temp_C', 'precip_mm', 'wind_speed', 'wind_dir', 'hm',
59
+ 'vap_pressure', 'dewpoint_C', 'loc_pressure', 'sea_pressure',
60
+ 'solarRad', 'snow_cm', 'cloudcover', 'lm_cloudcover', 'low_cloudbase',
61
+ 'groundtemp', 'O3', 'NO2', 'PM10', 'PM25', 'year',
62
+ 'month', 'hour', 'ground_temp - temp_C', 'hour_sin', 'hour_cos',
63
+ 'month_sin', 'month_cos', 'multi_class'
64
+ ]
65
+
66
+ # 기본 설정값
67
+ DEFAULT_N_FOLDS = 3
68
+ DEFAULT_N_BACKGROUND_SAMPLES = 200
69
+ DEFAULT_N_TEST_SAMPLES = 500
70
+ DEFAULT_FIGSIZE = (20, 8)
71
+ DEFAULT_TOP_N = 3
72
+ DEFAULT_TARGET_CLASS = 0
73
+ DEFAULT_DEVICE = 'cpu'
74
+ DEFAULT_PLOT_MARGIN = 0.05
75
+
76
+ def __init__(
77
+ self,
78
+ n_folds: int = DEFAULT_N_FOLDS,
79
+ n_background_samples: int = DEFAULT_N_BACKGROUND_SAMPLES,
80
+ n_test_samples: int = DEFAULT_N_TEST_SAMPLES,
81
+ figsize: Tuple[int, int] = DEFAULT_FIGSIZE,
82
+ top_n: int = DEFAULT_TOP_N,
83
+ target_class: int = DEFAULT_TARGET_CLASS,
84
+ device: str = DEFAULT_DEVICE
85
+ ):
86
+ self.n_folds = n_folds
87
+ self.n_background_samples = n_background_samples
88
+ self.n_test_samples = n_test_samples
89
+ self.figsize = figsize
90
+ self.top_n = top_n
91
+ self.target_class = target_class
92
+ self.device = device
93
+ self._validate()
94
+
95
+ def _validate(self):
96
+ """설정값 검증."""
97
+ if self.n_folds <= 0:
98
+ raise ValueError("n_folds must be positive")
99
+ if self.n_background_samples <= 0:
100
+ raise ValueError("n_background_samples must be positive")
101
+ if self.n_test_samples <= 0:
102
+ raise ValueError("n_test_samples must be positive")
103
+ if self.top_n <= 0:
104
+ raise ValueError("top_n must be positive")
105
+
106
+
107
+ # ==========================================
108
+ # 2. 결과 데이터 클래스
109
+ # ==========================================
110
+
111
+ @dataclass
112
+ class ImportanceData:
113
+ """Feature importance 데이터를 담는 클래스."""
114
+ df: pd.DataFrame
115
+ top_n_features: List[str]
116
+ top_n_share: float
117
+
118
+
119
+ @dataclass
120
+ class SHAPResult:
121
+ """SHAP 분석 결과를 담는 클래스."""
122
+ shap_train: Optional[np.ndarray]
123
+ X_train: Optional[pd.DataFrame]
124
+ shap_test: Optional[np.ndarray]
125
+ X_test: Optional[pd.DataFrame]
126
+ feature_names: List[str]
127
+ importance_train: Optional[ImportanceData]
128
+ importance_test: Optional[ImportanceData]
129
+ importance_df_combined: Optional[pd.DataFrame]
130
+ metadata: Dict[str, Any]
131
+
132
+ def to_dict(self) -> Dict[str, Any]:
133
+ """기존 dict 형태로 변환 (하위 호환성)."""
134
+ return {
135
+ 'shap_train': self.shap_train,
136
+ 'X_train': self.X_train,
137
+ 'shap_test': self.shap_test,
138
+ 'X_test': self.X_test,
139
+ 'feature_names': self.feature_names,
140
+ 'top_n_features_train': self.importance_train.top_n_features if self.importance_train else None,
141
+ 'top_n_share_train': self.importance_train.top_n_share if self.importance_train else None,
142
+ 'importance_df_train': self.importance_train.df if self.importance_train else None,
143
+ 'top_n_features_test': self.importance_test.top_n_features if self.importance_test else None,
144
+ 'top_n_share_test': self.importance_test.top_n_share if self.importance_test else None,
145
+ 'importance_df_test': self.importance_test.df if self.importance_test else None,
146
+ 'importance_df_combined': self.importance_df_combined,
147
+ **self.metadata
148
+ }
149
+
150
+
151
+ # ==========================================
152
+ # 3. 헬퍼 클래스들
153
+ # ==========================================
154
+
155
+ class PreprocessingUtils:
156
+ """전처리 유틸리티 클래스."""
157
+
158
+ @staticmethod
159
+ def add_derived_features(df: pd.DataFrame) -> pd.DataFrame:
160
+ """파생 변수 추가."""
161
+ df = df.copy()
162
+ df['hour_sin'] = np.sin(2 * np.pi * df['hour'] / 24)
163
+ df['hour_cos'] = np.cos(2 * np.pi * df['hour'] / 24)
164
+ df['month_sin'] = np.sin(2 * np.pi * df['month'] / 12)
165
+ df['month_cos'] = np.cos(2 * np.pi * df['month'] / 12)
166
+ df['ground_temp - temp_C'] = df['groundtemp'] - df['temp_C']
167
+ return df
168
+
169
+ @staticmethod
170
+ def preprocessing(df: pd.DataFrame, config: SHAPConfig) -> pd.DataFrame:
171
+ """데이터 전처리."""
172
+ df = df[df.columns].copy()
173
+ df['year'] = df['year'].astype('int')
174
+ df['month'] = df['month'].astype('int')
175
+ df['hour'] = df['hour'].astype('int')
176
+ df = PreprocessingUtils.add_derived_features(df).copy()
177
+ df['multi_class'] = df['multi_class'].astype('int')
178
+ df.loc[df['wind_dir'] == '정온', 'wind_dir'] = "0"
179
+ df['wind_dir'] = df['wind_dir'].astype('int')
180
+ df = df[config.FEATURE_COLUMNS].copy()
181
+ return df
182
+
183
+
184
+ class ShapValueExtractor:
185
+ """SHAP 값 추출 및 변환 유틸리티 클래스."""
186
+
187
+ @staticmethod
188
+ def _to_numpy(value: Any) -> np.ndarray:
189
+ """다양한 타입을 numpy array로 변환."""
190
+ if isinstance(value, torch.Tensor):
191
+ return value.cpu().numpy()
192
+ elif isinstance(value, list):
193
+ return np.array(value)
194
+ elif isinstance(value, np.ndarray):
195
+ return value
196
+ else:
197
+ return np.array(value)
198
+
199
+ @staticmethod
200
+ def _combine_num_cat_shap(shap_num: Any, shap_cat: Any) -> np.ndarray:
201
+ """Numerical과 categorical SHAP 값을 결합."""
202
+ shap_num = ShapValueExtractor._to_numpy(shap_num)
203
+ shap_cat = ShapValueExtractor._to_numpy(shap_cat)
204
+ return np.concatenate([shap_num, shap_cat], axis=-1)
205
+
206
+ @staticmethod
207
+ def _extract_from_list_of_tuples(shap_list: List[Tuple]) -> np.ndarray:
208
+ """튜플 리스트에서 SHAP 값을 추출."""
209
+ combined = []
210
+ for shap_item in shap_list:
211
+ if isinstance(shap_item, tuple):
212
+ combined.append(ShapValueExtractor._combine_num_cat_shap(shap_item[0], shap_item[1]))
213
+ else:
214
+ combined.append(ShapValueExtractor._to_numpy(shap_item))
215
+ return np.array(combined)
216
+
217
+ @staticmethod
218
+ def _extract_from_list(shap_list: List[Any]) -> np.ndarray:
219
+ """리스트에서 SHAP 값을 추출."""
220
+ if len(shap_list) == 0:
221
+ return np.array([])
222
+
223
+ if isinstance(shap_list[0], tuple):
224
+ return ShapValueExtractor._extract_from_list_of_tuples(shap_list)
225
+
226
+ if len(shap_list) == 2:
227
+ return ShapValueExtractor._combine_num_cat_shap(shap_list[0], shap_list[1])
228
+
229
+ try:
230
+ return np.array([ShapValueExtractor._to_numpy(item) for item in shap_list])
231
+ except (ValueError, TypeError):
232
+ converted = [ShapValueExtractor._to_numpy(item) for item in shap_list]
233
+ if len(converted) == 2:
234
+ return np.concatenate(converted, axis=-1)
235
+ else:
236
+ return np.array(converted)
237
+
238
+ @staticmethod
239
+ def extract(shap_values: Any, target_class: int = 0) -> np.ndarray:
240
+ """SHAP 값을 추출하여 numpy array로 변환."""
241
+ # 튜플인 경우
242
+ if isinstance(shap_values, tuple):
243
+ return ShapValueExtractor._combine_num_cat_shap(shap_values[0], shap_values[1])
244
+
245
+ # 리스트인 경우
246
+ if isinstance(shap_values, list):
247
+ target_shap = shap_values[target_class]
248
+
249
+ if isinstance(target_shap, tuple):
250
+ return ShapValueExtractor._combine_num_cat_shap(target_shap[0], target_shap[1])
251
+
252
+ if isinstance(target_shap, list):
253
+ return ShapValueExtractor._extract_from_list(target_shap)
254
+
255
+ return ShapValueExtractor._to_numpy(target_shap)
256
+
257
+ # numpy array인 경우
258
+ if isinstance(shap_values, np.ndarray):
259
+ if len(shap_values.shape) == 3:
260
+ return shap_values[:, target_class, :]
261
+ return shap_values
262
+
263
+ # 기타 타입
264
+ return ShapValueExtractor._to_numpy(shap_values)
265
+
266
+
267
+ @contextmanager
268
+ def suppress_shap_output():
269
+ """SHAP DeepExplainer의 출력을 억제하는 컨텍스트 매니저."""
270
+ old_stdout = sys.stdout
271
+ sys.stdout = StringIO()
272
+ try:
273
+ with warnings.catch_warnings():
274
+ warnings.simplefilter('ignore')
275
+ yield
276
+ finally:
277
+ sys.stdout = old_stdout
278
+
279
+
280
+ class ModelWrapper(torch.nn.Module):
281
+ """PyTorch 모델을 SHAP DeepExplainer에 맞게 래핑하는 클래스."""
282
+
283
+ def __init__(self, base_model, numerical_cols):
284
+ super().__init__()
285
+ self.base_model = base_model
286
+ self.num_features = len(numerical_cols)
287
+
288
+ def forward(self, *inputs):
289
+ """SHAP이 리스트로 전달하는 경우 처리"""
290
+ if len(inputs) == 1 and isinstance(inputs[0], (list, tuple)):
291
+ x_num, x_cat = inputs[0]
292
+ elif len(inputs) == 2:
293
+ x_num, x_cat = inputs
294
+ else:
295
+ x = inputs[0]
296
+ x_num = x[:, :self.num_features]
297
+ x_cat = x[:, self.num_features:].long()
298
+ return self.base_model(x_num, x_cat)
299
+
300
+ if x_cat.dtype != torch.long:
301
+ x_cat = x_cat.long()
302
+
303
+ return self.base_model(x_num, x_cat)
304
+
305
+
306
+ # ==========================================
307
+ # 4. DataLoader 클래스
308
+ # ==========================================
309
+
310
+ class DataLoader:
311
+ """데이터 로딩 및 전처리를 담당하는 클래스."""
312
+
313
+ def __init__(self, config: SHAPConfig):
314
+ self.config = config
315
+
316
+ def load_raw_data(
317
+ self,
318
+ region: str,
319
+ data_sample: str,
320
+ fold_idx: int
321
+ ) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
322
+ """원본 데이터 로드 (전처리만 적용)."""
323
+ if data_sample == 'pure':
324
+ dat_path = f"../../data/data_for_modeling/{region}_train.csv"
325
+ train_data = PreprocessingUtils.preprocessing(
326
+ pd.read_csv(dat_path, index_col=0), self.config
327
+ )
328
+ train_data = train_data.loc[
329
+ ~train_data['year'].isin([self.config.TEST_YEAR - (fold_idx + 1)]), :
330
+ ]
331
+ else:
332
+ train_data = pd.read_csv(
333
+ f"../../data/data_oversampled/{data_sample}/{data_sample}_{fold_idx+1}_{region}.csv"
334
+ )
335
+ train_data = PreprocessingUtils.preprocessing(train_data, self.config)
336
+
337
+ val_data = pd.read_csv(f"../../data/data_for_modeling/{region}_train.csv")
338
+ val_data = PreprocessingUtils.preprocessing(val_data, self.config)
339
+ val_data = val_data.loc[
340
+ val_data['year'].isin([self.config.TEST_YEAR - (fold_idx + 1)]), :
341
+ ]
342
+
343
+ test_data = pd.read_csv(f"../../data/data_for_modeling/{region}_test.csv")
344
+ test_data = PreprocessingUtils.preprocessing(test_data, self.config)
345
+ test_data = test_data.loc[test_data['year'].isin([self.config.TEST_YEAR]), :]
346
+
347
+ # 컬럼 정렬
348
+ common_columns = train_data.columns.to_list()
349
+ train_data = train_data[common_columns]
350
+ val_data = val_data[common_columns]
351
+ test_data = test_data[common_columns]
352
+
353
+ return train_data, val_data, test_data
354
+
355
+ def prepare_for_tree_model(
356
+ self,
357
+ region: str,
358
+ data_sample: str,
359
+ fold_idx: int
360
+ ) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
361
+ """Tree 모델용 데이터 준비."""
362
+ train_data = pd.read_csv(
363
+ f"../../data/data_oversampled/{data_sample}/{data_sample}_{fold_idx+1}_{region}.csv"
364
+ )
365
+ val_data = pd.read_csv(f"../../data/data_for_modeling/{region}_train.csv")
366
+ test_data = pd.read_csv(f"../../data/data_for_modeling/{region}_test.csv")
367
+
368
+ train_data = PreprocessingUtils.preprocessing(train_data, self.config).copy()
369
+ val_data = PreprocessingUtils.preprocessing(val_data, self.config).copy()
370
+ test_data = PreprocessingUtils.preprocessing(test_data, self.config).copy()
371
+
372
+ train_data = train_data.loc[
373
+ train_data['year'].isin(self.config.FOLD_YEARS[fold_idx]), :
374
+ ]
375
+ val_data = val_data.loc[
376
+ ~val_data['year'].isin(self.config.FOLD_YEARS[fold_idx]), :
377
+ ]
378
+ test_data = test_data.loc[test_data['year'].isin([self.config.TEST_YEAR]), :]
379
+
380
+ return train_data, val_data, test_data
381
+
382
+ def prepare_for_dl_model(
383
+ self,
384
+ region: str,
385
+ data_sample: str,
386
+ fold_idx: int,
387
+ scaler: Any
388
+ ) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.Index, pd.Index,
389
+ torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
390
+ """Deep Learning 모델용 데이터 준비 (scaler 적용, 텐서 변환)."""
391
+ train_data, val_data, test_data = self.load_raw_data(region, data_sample, fold_idx)
392
+
393
+ X_train = train_data.drop(columns=self.config.DROP_COLUMNS)
394
+ X_val = val_data.drop(columns=self.config.DROP_COLUMNS)
395
+ X_test = test_data.drop(columns=self.config.DROP_COLUMNS)
396
+
397
+ # 범주형 & 연속형 변수 분리
398
+ categorical_cols = X_train.select_dtypes(include=['object', 'category', 'int64']).columns
399
+ numerical_cols = X_train.select_dtypes(include=['float64']).columns
400
+
401
+ # Label Encoding
402
+ label_encoders = {}
403
+ for col in categorical_cols:
404
+ le = LabelEncoder()
405
+ le.fit(X_train[col])
406
+ label_encoders[col] = le
407
+
408
+ for col in categorical_cols:
409
+ X_train[col] = label_encoders[col].transform(X_train[col])
410
+ X_val[col] = label_encoders[col].transform(X_val[col])
411
+ X_test[col] = label_encoders[col].transform(X_test[col])
412
+
413
+ # Scaler 변환
414
+ X_train[numerical_cols] = scaler.transform(X_train[numerical_cols])
415
+ X_val[numerical_cols] = scaler.transform(X_val[numerical_cols])
416
+ X_test[numerical_cols] = scaler.transform(X_test[numerical_cols])
417
+
418
+ # 텐서 변환
419
+ X_train_num = torch.tensor(X_train[numerical_cols].values, dtype=torch.float32)
420
+ X_train_cat = torch.tensor(X_train[categorical_cols].values, dtype=torch.long)
421
+ X_val_num = torch.tensor(X_val[numerical_cols].values, dtype=torch.float32)
422
+ X_val_cat = torch.tensor(X_val[categorical_cols].values, dtype=torch.long)
423
+ X_test_num = torch.tensor(X_test[numerical_cols].values, dtype=torch.float32)
424
+ X_test_cat = torch.tensor(X_test[categorical_cols].values, dtype=torch.long)
425
+
426
+ return (X_train, X_val, X_test, categorical_cols, numerical_cols,
427
+ X_train_num, X_train_cat, X_val_num, X_val_cat, X_test_num, X_test_cat)
428
+
429
+
430
+ # ==========================================
431
+ # 5. SHAPAnalyzer 베이스 클래스
432
+ # ==========================================
433
+
434
+ class SHAPAnalyzer(ABC):
435
+ """SHAP 분석을 위한 추상 베이스 클래스."""
436
+
437
+ def __init__(self, config: SHAPConfig, data_loader: DataLoader):
438
+ self.config = config
439
+ self.data_loader = data_loader
440
+
441
+ @abstractmethod
442
+ def create_explainer(self, model: Any, background_data: Any) -> Any:
443
+ """SHAP Explainer 생성."""
444
+ pass
445
+
446
+ @abstractmethod
447
+ def calculate_shap_values(self, explainer: Any, sample_data: Any) -> Any:
448
+ """SHAP 값 계산."""
449
+ pass
450
+
451
+ def _calculate_importance(
452
+ self,
453
+ shap_values: np.ndarray,
454
+ feature_names: List[str],
455
+ period_name: str = ''
456
+ ) -> ImportanceData:
457
+ """누적 설명력(Cumulative Share) 계산."""
458
+ global_importances = np.abs(shap_values).mean(axis=0)
459
+
460
+ importance_df = pd.DataFrame({
461
+ 'feature': feature_names,
462
+ 'importance': global_importances
463
+ }).sort_values('importance', ascending=False)
464
+
465
+ total_importance = importance_df['importance'].sum()
466
+ top_n_df = importance_df.head(self.config.top_n)
467
+ top_n_importance = top_n_df['importance'].sum()
468
+ top_n_share = (top_n_importance / total_importance) * 100
469
+ top_n_features = top_n_df['feature'].tolist()
470
+
471
+ if period_name:
472
+ print(f"{period_name} - Top {self.config.top_n} Dominant Features: {top_n_features}")
473
+ print(f"{period_name} - Cumulative Importance Share (Top {self.config.top_n}): {top_n_share:.2f}%")
474
+ else:
475
+ print(f"Top {self.config.top_n} Dominant Features: {top_n_features}")
476
+ print(f"Cumulative Importance Share (Top {self.config.top_n}): {top_n_share:.2f}%")
477
+ print(f"{'-'*40}")
478
+
479
+ return ImportanceData(
480
+ df=importance_df,
481
+ top_n_features=top_n_features,
482
+ top_n_share=top_n_share
483
+ )
484
+
485
+ def _create_combined_importance_df(
486
+ self,
487
+ importance_train: Optional[ImportanceData],
488
+ importance_test: Optional[ImportanceData],
489
+ feature_names: List[str]
490
+ ) -> Optional[pd.DataFrame]:
491
+ """Train과 Test 중요도 DataFrame 통합."""
492
+ if importance_train is None and importance_test is None:
493
+ return None
494
+
495
+ if importance_train is not None:
496
+ train_df = importance_train.df[['feature', 'importance']].copy()
497
+ train_df.columns = ['feature', 'importance_train']
498
+ total_importance_train = train_df['importance_train'].sum()
499
+ train_df['share_train'] = (train_df['importance_train'] / total_importance_train) * 100
500
+ else:
501
+ train_df = pd.DataFrame({'feature': feature_names})
502
+ train_df['importance_train'] = np.nan
503
+ train_df['share_train'] = np.nan
504
+
505
+ if importance_test is not None:
506
+ test_df = importance_test.df[['feature', 'importance']].copy()
507
+ test_df.columns = ['feature', 'importance_test']
508
+ total_importance_test = test_df['importance_test'].sum()
509
+ test_df['share_test'] = (test_df['importance_test'] / total_importance_test) * 100
510
+ else:
511
+ test_df = pd.DataFrame({'feature': feature_names})
512
+ test_df['importance_test'] = np.nan
513
+ test_df['share_test'] = np.nan
514
+
515
+ importance_df_combined = pd.merge(train_df, test_df, on='feature', how='outer')
516
+
517
+ if importance_train is not None:
518
+ importance_df_combined = importance_df_combined.sort_values(
519
+ 'importance_train', ascending=False
520
+ ).reset_index(drop=True)
521
+ elif importance_test is not None:
522
+ importance_df_combined = importance_df_combined.sort_values(
523
+ 'importance_test', ascending=False
524
+ ).reset_index(drop=True)
525
+ else:
526
+ importance_df_combined = importance_df_combined.sort_values('feature').reset_index(drop=True)
527
+
528
+ return importance_df_combined
529
+
530
+
531
+ # ==========================================
532
+ # 6. TreeSHAPAnalyzer 구현
533
+ # ==========================================
534
+
535
+ class TreeSHAPAnalyzer(SHAPAnalyzer):
536
+ """Tree 기반 모델(XGBoost, LightGBM) SHAP 분석 클래스."""
537
+
538
+ def create_explainer(self, model: Any, background_data: Any = None) -> shap.TreeExplainer:
539
+ """TreeExplainer 생성."""
540
+ with warnings.catch_warnings():
541
+ warnings.filterwarnings('ignore', category=UserWarning, message='.*deprecated binary model format.*')
542
+ return shap.TreeExplainer(model.get_booster())
543
+
544
+ def calculate_shap_values(self, explainer: shap.TreeExplainer, sample_data: pd.DataFrame) -> np.ndarray:
545
+ """Tree SHAP 값 계산."""
546
+ shap_values = explainer.shap_values(sample_data)
547
+ if isinstance(shap_values, list):
548
+ return shap_values[self.config.target_class]
549
+ return shap_values
550
+
551
+ def analyze(
552
+ self,
553
+ model_name: str,
554
+ region: str,
555
+ data_sample: str,
556
+ show_plot: bool = True,
557
+ show_train_plot: bool = True,
558
+ show_test_plot: bool = True,
559
+ suppress_warnings: bool = True
560
+ ) -> SHAPResult:
561
+ """Tree 모델 SHAP 분석 수행."""
562
+ # 모델 로드
563
+ model_path = f"../save_model/{model_name}_optima/{model_name}_{data_sample}_{region}.pkl"
564
+ models = load(model_path)
565
+
566
+ if len(models) != self.config.n_folds:
567
+ raise ValueError(f"로드된 모델 개수({len(models)})가 n_folds({self.config.n_folds})와 일치하지 않습니다.")
568
+
569
+ # 각 Fold에 대해 SHAP 값 계산
570
+ oof_shap_values = []
571
+ oof_X_data = []
572
+ test_shap_values = []
573
+
574
+ for fold_idx in range(self.config.n_folds):
575
+ _, val_data, test_data = self.data_loader.prepare_for_tree_model(
576
+ region, data_sample, fold_idx
577
+ )
578
+
579
+ X_val = val_data.drop(columns=self.config.DROP_COLUMNS)
580
+ if fold_idx == 0:
581
+ X_test = test_data.drop(columns=self.config.DROP_COLUMNS)
582
+
583
+ explainer = self.create_explainer(models[fold_idx])
584
+ shap_val = self.calculate_shap_values(explainer, X_val)
585
+ oof_shap_values.append(shap_val)
586
+ oof_X_data.append(X_val)
587
+
588
+ shap_test = self.calculate_shap_values(explainer, X_test)
589
+ test_shap_values.append(shap_test)
590
+
591
+ # 데이터 통합
592
+ all_shap_train = np.concatenate(oof_shap_values, axis=0)
593
+ all_X_train = pd.concat(oof_X_data, axis=0)
594
+ all_shap_test = np.mean(test_shap_values, axis=0)
595
+ feature_names = list(all_X_train.columns)
596
+
597
+ # 중요도 계산
598
+ importance_train = self._calculate_importance(
599
+ all_shap_train, feature_names, period_name='Train Period'
600
+ )
601
+ importance_test = self._calculate_importance(
602
+ all_shap_test, feature_names, period_name='Test Period'
603
+ )
604
+ print()
605
+
606
+ importance_df_combined = self._create_combined_importance_df(
607
+ importance_train, importance_test, feature_names
608
+ )
609
+
610
+ # 시각화
611
+ if show_plot:
612
+ visualizer = SHAPVisualizer(self.config)
613
+ visualizer.plot_summary(
614
+ all_shap_train, all_X_train, all_shap_test, X_test,
615
+ feature_names, importance_train, importance_test,
616
+ show_train_plot=show_train_plot, show_test_plot=show_test_plot,
617
+ model_name=model_name, data_sample=data_sample, region=region
618
+ )
619
+
620
+ return SHAPResult(
621
+ shap_train=all_shap_train,
622
+ X_train=all_X_train,
623
+ shap_test=all_shap_test,
624
+ X_test=X_test,
625
+ feature_names=feature_names,
626
+ importance_train=importance_train,
627
+ importance_test=importance_test,
628
+ importance_df_combined=importance_df_combined,
629
+ metadata={'model_name': model_name, 'region': region, 'data_sample': data_sample}
630
+ )
631
+
632
+
633
+ # ==========================================
634
+ # 7. DeepSHAPAnalyzer 구현
635
+ # ==========================================
636
+
637
+ class DeepSHAPAnalyzer(SHAPAnalyzer):
638
+ """Deep Learning 모델 SHAP 분석 클래스."""
639
+
640
+ def __init__(self, config: SHAPConfig, data_loader: DataLoader, device: str = 'cpu'):
641
+ super().__init__(config, data_loader)
642
+ self.device = device
643
+
644
+ def create_explainer(
645
+ self,
646
+ model: torch.nn.Module,
647
+ background_data: Tuple[torch.Tensor, torch.Tensor, pd.Index],
648
+ model_name: str
649
+ ) -> shap.DeepExplainer:
650
+ """DeepExplainer 생성."""
651
+ X_bg_num, X_bg_cat, numerical_cols = background_data
652
+ wrapped_model = ModelWrapper(model, numerical_cols)
653
+ wrapped_model.to(self.device)
654
+ wrapped_model.eval()
655
+
656
+ with suppress_shap_output():
657
+ if model_name in ('ft_transformer', 'deepgbm'):
658
+ X_bg_cat_float = X_bg_cat.float()
659
+ explainer = shap.DeepExplainer(wrapped_model, [X_bg_num, X_bg_cat_float])
660
+ elif model_name == 'resnet_like':
661
+ X_bg_combined = torch.cat([X_bg_num, X_bg_cat.float()], dim=1)
662
+ explainer = shap.DeepExplainer(wrapped_model, X_bg_combined)
663
+ else:
664
+ raise ValueError(f"Unknown model_name: {model_name}")
665
+
666
+ return explainer
667
+
668
+ def calculate_shap_values(
669
+ self,
670
+ explainer: shap.DeepExplainer,
671
+ sample_data: Tuple[torch.Tensor, torch.Tensor],
672
+ model_name: str
673
+ ) -> Any:
674
+ """Deep SHAP 값 계산."""
675
+ X_sample_num, X_sample_cat = sample_data
676
+
677
+ with suppress_shap_output():
678
+ if model_name in ('ft_transformer', 'deepgbm'):
679
+ X_sample_cat_float = X_sample_cat.float()
680
+ shap_values = explainer.shap_values([X_sample_num, X_sample_cat_float])
681
+ elif model_name == 'resnet_like':
682
+ X_sample_combined = torch.cat([X_sample_num, X_sample_cat.float()], dim=1)
683
+ shap_values = explainer.shap_values(X_sample_combined)
684
+ else:
685
+ raise ValueError(f"Unknown model_name: {model_name}")
686
+
687
+ return shap_values
688
+
689
+ def analyze(
690
+ self,
691
+ model_name: str,
692
+ region: str,
693
+ data_sample: str,
694
+ show_plot: bool = True,
695
+ show_train_plot: bool = True,
696
+ show_test_plot: bool = True
697
+ ) -> Optional[SHAPResult]:
698
+ """Deep Learning 모델 SHAP 분석 수행."""
699
+ print(f"[{model_name.upper()}] {region} - {data_sample} SHAP Analysis Start...")
700
+
701
+ # 모델 및 scaler 로드
702
+ try:
703
+ model_path = f"../save_model/{model_name}_optima/{model_name}_{data_sample}_{region}.pkl"
704
+ models = load(model_path)
705
+
706
+ if data_sample == 'pure':
707
+ scaler_filename = f'{model_name}_pure_{region}_scaler.pkl'
708
+ else:
709
+ scaler_filename = f'{model_name}_{data_sample}_{region}_scaler.pkl'
710
+ scaler_path = f'../save_model/{model_name}_optima/scaler/{scaler_filename}'
711
+ scalers = load(scaler_path)
712
+ except Exception as e:
713
+ print(f"모델 또는 scaler 로드 실패: {e}")
714
+ return None
715
+
716
+ if len(models) != self.config.n_folds or len(scalers) != self.config.n_folds:
717
+ raise ValueError(
718
+ f"모델 개수({len(models)}) 또는 scaler 개수({len(scalers)})가 "
719
+ f"n_folds({self.config.n_folds})와 일치하지 않습니다."
720
+ )
721
+
722
+ # 각 fold의 SHAP 값 저장
723
+ all_shap_train = []
724
+ all_shap_test = []
725
+ all_train_data = []
726
+ all_test_data = []
727
+ feature_names = None
728
+
729
+ for fold_idx in range(self.config.n_folds):
730
+ print(f" Processing Fold {fold_idx + 1}...")
731
+
732
+ try:
733
+ (X_train, X_val, X_test, categorical_cols, numerical_cols,
734
+ X_train_num, X_train_cat, X_val_num, X_val_cat, X_test_num, X_test_cat) = \
735
+ self.data_loader.prepare_for_dl_model(region, data_sample, fold_idx, scalers[fold_idx])
736
+
737
+ if feature_names is None:
738
+ feature_names = list(numerical_cols) + list(categorical_cols)
739
+
740
+ model = models[fold_idx]
741
+ model.to(self.device)
742
+ model.eval()
743
+
744
+ # 배경 데이터 샘플링
745
+ n_bg = min(self.config.n_background_samples, len(X_val_num))
746
+ bg_indices = np.random.choice(len(X_val_num), n_bg, replace=False)
747
+ X_bg_num = X_val_num[bg_indices].to(self.device)
748
+ X_bg_cat = X_val_cat[bg_indices].to(self.device)
749
+
750
+ # Validation 데이터 샘플링
751
+ n_train = min(self.config.n_test_samples, len(X_val_num))
752
+ available_indices = np.setdiff1d(np.arange(len(X_val_num)), bg_indices)
753
+ if len(available_indices) < n_train:
754
+ train_indices = available_indices
755
+ else:
756
+ train_indices = np.random.choice(available_indices, n_train, replace=False)
757
+ X_train_sample_num = X_val_num[train_indices].to(self.device)
758
+ X_train_sample_cat = X_val_cat[train_indices].to(self.device)
759
+
760
+ # 테스트 데이터 샘플링
761
+ n_test = min(self.config.n_test_samples, len(X_test_num))
762
+ test_indices = np.random.choice(len(X_test_num), n_test, replace=False)
763
+ X_test_sample_num = X_test_num[test_indices].to(self.device)
764
+ X_test_sample_cat = X_test_cat[test_indices].to(self.device)
765
+
766
+ # SHAP Explainer 생성 및 계산
767
+ try:
768
+ explainer = self.create_explainer(
769
+ model, (X_bg_num, X_bg_cat, numerical_cols), model_name
770
+ )
771
+
772
+ shap_values_train = self.calculate_shap_values(
773
+ explainer, (X_train_sample_num, X_train_sample_cat), model_name
774
+ )
775
+ shap_val_train = ShapValueExtractor.extract(shap_values_train, self.config.target_class)
776
+ all_shap_train.append(shap_val_train)
777
+ X_train_original = X_val.iloc[train_indices].copy()
778
+ all_train_data.append(X_train_original)
779
+
780
+ shap_values_test = self.calculate_shap_values(
781
+ explainer, (X_test_sample_num, X_test_sample_cat), model_name
782
+ )
783
+ shap_val_test = ShapValueExtractor.extract(shap_values_test, self.config.target_class)
784
+ all_shap_test.append(shap_val_test)
785
+ X_test_original = X_test.iloc[test_indices].copy()
786
+ all_test_data.append(X_test_original)
787
+
788
+ except Exception as e:
789
+ print(f" Warning: Fold {fold_idx + 1} SHAP 계산 실패: {e}")
790
+ continue
791
+ except Exception as e:
792
+ print(f" Warning: Fold {fold_idx + 1} 처리 실패: {e}")
793
+ continue
794
+
795
+ if len(all_shap_train) == 0 and len(all_shap_test) == 0:
796
+ print(" 모든 fold에서 SHAP 계산 실패")
797
+ return None
798
+
799
+ # 데이터 통합
800
+ all_shap_train_combined = np.concatenate(all_shap_train, axis=0) if len(all_shap_train) > 0 else None
801
+ all_train_data_combined = pd.concat(all_train_data, axis=0).reset_index(drop=True) if len(all_train_data) > 0 else None
802
+
803
+ if len(all_shap_test) > 0:
804
+ all_shap_test_combined = np.mean(all_shap_test, axis=0)
805
+ all_test_data_combined = all_test_data[0] if len(all_test_data) > 0 else None
806
+ else:
807
+ all_shap_test_combined = None
808
+ all_test_data_combined = None
809
+
810
+ # 중요도 계산
811
+ if all_shap_train_combined is not None:
812
+ importance_train = self._calculate_importance(
813
+ all_shap_train_combined, feature_names, period_name='Train Period'
814
+ )
815
+ else:
816
+ importance_train = None
817
+
818
+ if all_shap_test_combined is not None:
819
+ importance_test = self._calculate_importance(
820
+ all_shap_test_combined, feature_names, period_name='Test Period'
821
+ )
822
+ print()
823
+ else:
824
+ importance_test = None
825
+
826
+ importance_df_combined = self._create_combined_importance_df(
827
+ importance_train, importance_test, feature_names
828
+ )
829
+
830
+ # 시각화
831
+ if show_plot:
832
+ visualizer = SHAPVisualizer(self.config)
833
+ visualizer.plot_summary(
834
+ all_shap_train_combined, all_train_data_combined,
835
+ all_shap_test_combined, all_test_data_combined,
836
+ feature_names, importance_train, importance_test,
837
+ show_train_plot=show_train_plot, show_test_plot=show_test_plot,
838
+ model_name=model_name, data_sample=data_sample, region=region
839
+ )
840
+
841
+ print(f" [{model_name.upper()}] SHAP Analysis Complete!\n")
842
+
843
+ return SHAPResult(
844
+ shap_train=all_shap_train_combined,
845
+ X_train=all_train_data_combined[feature_names] if all_train_data_combined is not None else None,
846
+ shap_test=all_shap_test_combined,
847
+ X_test=all_test_data_combined[feature_names] if all_test_data_combined is not None else None,
848
+ feature_names=feature_names,
849
+ importance_train=importance_train,
850
+ importance_test=importance_test,
851
+ importance_df_combined=importance_df_combined,
852
+ metadata={'model_name': model_name, 'region': region, 'data_sample': data_sample}
853
+ )
854
+
855
+
856
+ # ==========================================
857
+ # 8. SHAPVisualizer 클래스
858
+ # ==========================================
859
+
860
+ class SHAPVisualizer:
861
+ """SHAP 시각화를 담당하는 클래스."""
862
+
863
+ def __init__(self, config: SHAPConfig):
864
+ self.config = config
865
+
866
+ def _calculate_xlim(
867
+ self,
868
+ shap_train: Optional[np.ndarray],
869
+ shap_test: Optional[np.ndarray]
870
+ ) -> Tuple[Optional[float], Optional[float]]:
871
+ """x축 범위 계산."""
872
+ if shap_train is not None and shap_test is not None:
873
+ x_min = min(shap_train.min(), shap_test.min())
874
+ x_max = max(shap_train.max(), shap_test.max())
875
+ elif shap_train is not None:
876
+ x_min, x_max = shap_train.min(), shap_train.max()
877
+ elif shap_test is not None:
878
+ x_min, x_max = shap_test.min(), shap_test.max()
879
+ else:
880
+ return None, None
881
+
882
+ margin = (x_max - x_min) * self.config.DEFAULT_PLOT_MARGIN
883
+ x_min -= margin
884
+ x_max += margin
885
+ return x_min, x_max
886
+
887
+ def plot_summary(
888
+ self,
889
+ shap_train: Optional[np.ndarray],
890
+ X_train: Optional[pd.DataFrame],
891
+ shap_test: Optional[np.ndarray],
892
+ X_test: Optional[pd.DataFrame],
893
+ feature_names: List[str],
894
+ importance_train: Optional[ImportanceData],
895
+ importance_test: Optional[ImportanceData],
896
+ show_train_plot: bool = True,
897
+ show_test_plot: bool = True,
898
+ model_name: Optional[str] = None,
899
+ data_sample: Optional[str] = None,
900
+ region: Optional[str] = None
901
+ ) -> None:
902
+ """SHAP summary plot 생성."""
903
+ num_plots = int(show_train_plot and shap_train is not None) + int(show_test_plot and shap_test is not None)
904
+ if num_plots == 0:
905
+ return
906
+
907
+ x_min, x_max = self._calculate_xlim(shap_train, shap_test)
908
+
909
+ # Title prefix 생성
910
+ title_parts = []
911
+ if model_name is not None:
912
+ title_parts.append(model_name.upper())
913
+ if data_sample is not None:
914
+ title_parts.append(data_sample)
915
+ if region is not None:
916
+ title_parts.append(region.upper())
917
+
918
+ title_prefix = " - ".join(title_parts) + "\n" if title_parts else ""
919
+
920
+ if num_plots == 2:
921
+ fig, axes = plt.subplots(1, 2, figsize=self.config.figsize)
922
+
923
+ if show_train_plot and shap_train is not None:
924
+ plt.sca(axes[0])
925
+ shap.summary_plot(
926
+ shap_train,
927
+ X_train[feature_names] if isinstance(X_train, pd.DataFrame) else X_train,
928
+ show=False, plot_size=None
929
+ )
930
+ if x_min is not None and x_max is not None:
931
+ plt.xlim(x_min, x_max)
932
+ share_text = (
933
+ f"\nTop {self.config.top_n} Share: {importance_train.top_n_share:.1f}%"
934
+ if importance_train else ""
935
+ )
936
+ plt.title(f"{title_prefix}Train Period (2018-20): Class {self.config.target_class}{share_text}")
937
+
938
+ if show_test_plot and shap_test is not None:
939
+ plt.sca(axes[1])
940
+ shap.summary_plot(
941
+ shap_test,
942
+ X_test[feature_names] if isinstance(X_test, pd.DataFrame) else X_test,
943
+ show=False, plot_size=None
944
+ )
945
+ if x_min is not None and x_max is not None:
946
+ plt.xlim(x_min, x_max)
947
+ share_text = (
948
+ f"\nTop {self.config.top_n} Share: {importance_test.top_n_share:.1f}%"
949
+ if importance_test else ""
950
+ )
951
+ plt.title(f"{title_prefix}Test Period (2021): Class {self.config.target_class}{share_text}")
952
+ else:
953
+ plt.figure(figsize=(self.config.figsize[0]//2, self.config.figsize[1]))
954
+ if show_train_plot and shap_train is not None:
955
+ data = X_train[feature_names] if isinstance(X_train, pd.DataFrame) else X_train
956
+ shap_v = shap_train
957
+ share_text = (
958
+ f"\nTop {self.config.top_n} Share: {importance_train.top_n_share:.1f}%"
959
+ if importance_train else ""
960
+ )
961
+ title = f"{title_prefix}Train Period (2018-20): Class {self.config.target_class}{share_text}"
962
+ elif show_test_plot and shap_test is not None:
963
+ data = X_test[feature_names] if isinstance(X_test, pd.DataFrame) else X_test
964
+ shap_v = shap_test
965
+ share_text = (
966
+ f"\nTop {self.config.top_n} Share: {importance_test.top_n_share:.1f}%"
967
+ if importance_test else ""
968
+ )
969
+ title = f"{title_prefix}Test Period (2021): Class {self.config.target_class}{share_text}"
970
+ else:
971
+ return
972
+
973
+ shap.summary_plot(shap_v, data, show=False)
974
+ if x_min is not None and x_max is not None:
975
+ plt.xlim(x_min, x_max)
976
+ plt.title(title)
977
+
978
+ plt.tight_layout()
979
+ plt.show()
980
+
981
+ def plot_elbow(self, importance_df_combined: pd.DataFrame) -> None:
982
+ """Elbow plot 생성."""
983
+ elbow = importance_df_combined.loc[:, ['feature', 'importance_train', 'share_train']]
984
+ elbow = elbow.sort_values('importance_train', ascending=False)
985
+ plt.figure(figsize=(8, 5))
986
+ plt.plot(range(1, len(elbow) + 1), elbow['share_train'].values, marker='o')
987
+ plt.xlabel('Feature Rank')
988
+ plt.ylabel('Share Train (%)')
989
+ plt.title('Elbow Plot for Feature Importance (share_train)')
990
+ plt.xticks(range(1, len(elbow) + 1))
991
+ plt.grid(True, linestyle='--', alpha=0.5)
992
+ plt.show()
993
+
994
+
995
+ # ==========================================
996
+ # 9. WassersteinCalculator 클래스
997
+ # ==========================================
998
+
999
+ class WassersteinCalculator:
1000
+ """Wasserstein Distance 계산을 담당하는 클래스."""
1001
+
1002
+ def __init__(self, config: SHAPConfig, data_loader: DataLoader):
1003
+ self.config = config
1004
+ self.data_loader = data_loader
1005
+
1006
+ def _compute_wd_for_feature(
1007
+ self,
1008
+ train_dist: np.ndarray,
1009
+ test_dist: np.ndarray
1010
+ ) -> Dict[str, float]:
1011
+ """단일 feature에 대한 WD 계산."""
1012
+ wd_val = wasserstein_distance(train_dist, test_dist)
1013
+ return {
1014
+ 'WD_Score': wd_val,
1015
+ 'Train_Mean': np.mean(train_dist),
1016
+ 'Test_Mean': np.mean(test_dist),
1017
+ 'Train_Std': np.std(train_dist),
1018
+ 'Test_Std': np.std(test_dist),
1019
+ 'Train_Count': len(train_dist),
1020
+ 'Test_Count': len(test_dist)
1021
+ }
1022
+
1023
+ def calculate(
1024
+ self,
1025
+ region: str,
1026
+ data_sample: str,
1027
+ top_features: List[str],
1028
+ model_type: str = 'tree',
1029
+ fold_idx: int = 0
1030
+ ) -> pd.DataFrame:
1031
+ """Wasserstein Distance 계산."""
1032
+ # 데이터 로드
1033
+ if model_type == 'tree':
1034
+ train_df, val_df, test_df = self.data_loader.prepare_for_tree_model(
1035
+ region, data_sample, fold_idx
1036
+ )
1037
+ elif model_type == 'dl':
1038
+ train_df, val_df, test_df = self.data_loader.load_raw_data(
1039
+ region, data_sample, fold_idx
1040
+ )
1041
+ else:
1042
+ raise ValueError(f"Unknown model_type: {model_type}. Must be 'tree' or 'dl'")
1043
+
1044
+ train_period = pd.concat([train_df, val_df], axis=0)
1045
+ test_period = test_df
1046
+
1047
+ results = []
1048
+
1049
+ print(f"[{region.upper()}] Wasserstein Distance Analysis")
1050
+ print(f"Model Type: {model_type.upper()}, Data Sample: {data_sample}")
1051
+ print(f"{'-'*60}")
1052
+
1053
+ for feature in top_features:
1054
+ if feature in train_period.columns:
1055
+ dist_train = train_period[feature].dropna().values
1056
+ dist_test = test_period[feature].dropna().values
1057
+
1058
+ if len(dist_train) == 0 or len(dist_test) == 0:
1059
+ print(f"Warning: {feature} 변수에 유효한 데이터가 없습니다.")
1060
+ continue
1061
+
1062
+ wd_metrics = self._compute_wd_for_feature(dist_train, dist_test)
1063
+ results.append({
1064
+ 'Region': region,
1065
+ 'Feature': feature,
1066
+ **wd_metrics
1067
+ })
1068
+ print(f"Feature: {feature:20} | WD: {wd_metrics['WD_Score']:.4f} | "
1069
+ f"Train Mean: {wd_metrics['Train_Mean']:.4f} | Test Mean: {wd_metrics['Test_Mean']:.4f}")
1070
+ else:
1071
+ print(f"Warning: {feature} 변수를 찾을 수 없습니다.")
1072
+
1073
+ print()
1074
+ return pd.DataFrame(results)
1075
+
1076
+ def calculate_from_shap_result(
1077
+ self,
1078
+ shap_result: Dict[str, Any],
1079
+ top_n: int = 3,
1080
+ use_train_features: bool = True,
1081
+ model_type: str = 'tree',
1082
+ fold_idx: int = 0
1083
+ ) -> pd.DataFrame:
1084
+ """SHAP 분석 결과에서 상위 변수를 자동 추출하여 WD 계산."""
1085
+ # 상위 변수 추출
1086
+ if use_train_features:
1087
+ if 'top_n_features_train' in shap_result and shap_result['top_n_features_train'] is not None:
1088
+ top_features = shap_result['top_n_features_train'][:top_n]
1089
+ elif 'importance_df_train' in shap_result and shap_result['importance_df_train'] is not None:
1090
+ top_features = shap_result['importance_df_train'].head(top_n)['feature'].tolist()
1091
+ else:
1092
+ raise ValueError("SHAP 결과에서 Train 상위 변수를 찾을 수 없습니다.")
1093
+ else:
1094
+ if 'top_n_features_test' in shap_result and shap_result['top_n_features_test'] is not None:
1095
+ top_features = shap_result['top_n_features_test'][:top_n]
1096
+ elif 'importance_df_test' in shap_result and shap_result['importance_df_test'] is not None:
1097
+ top_features = shap_result['importance_df_test'].head(top_n)['feature'].tolist()
1098
+ else:
1099
+ raise ValueError("SHAP 결과에서 Test 상위 변수를 찾을 수 없습니다.")
1100
+
1101
+ region = shap_result.get('region', 'unknown')
1102
+ data_sample = shap_result.get('data_sample', 'unknown')
1103
+
1104
+ return self.calculate(region, data_sample, top_features, model_type, fold_idx)
1105
+
1106
+
1107
+ # ==========================================
1108
+ # 10. 하위 호환성 레이어
1109
+ # ==========================================
1110
+
1111
+ def analyze_shap_values_across_folds(
1112
+ model_name: str,
1113
+ region: str,
1114
+ data_sample: str,
1115
+ target_class: int = 0,
1116
+ n_folds: int = 3,
1117
+ figsize: Tuple[int, int] = (20, 10),
1118
+ show_plot: bool = True,
1119
+ show_train_plot: bool = True,
1120
+ show_test_plot: bool = True,
1121
+ suppress_warnings: bool = True,
1122
+ top_n: int = 3
1123
+ ) -> Dict[str, Any]:
1124
+ """Tree 모델 SHAP 분석 (하위 호환성 래퍼 함수).
1125
+
1126
+ Deprecated: Use TreeSHAPAnalyzer instead.
1127
+ """
1128
+ config = SHAPConfig(
1129
+ n_folds=n_folds,
1130
+ figsize=figsize,
1131
+ top_n=top_n,
1132
+ target_class=target_class
1133
+ )
1134
+ data_loader = DataLoader(config)
1135
+ analyzer = TreeSHAPAnalyzer(config, data_loader)
1136
+ result = analyzer.analyze(
1137
+ model_name, region, data_sample,
1138
+ show_plot=show_plot,
1139
+ show_train_plot=show_train_plot,
1140
+ show_test_plot=show_test_plot
1141
+ )
1142
+ return result.to_dict()
1143
+
1144
+
1145
+ def analyze_dl_model_shap(
1146
+ model_name: str,
1147
+ region: str,
1148
+ data_sample: str,
1149
+ target_class: int = 0,
1150
+ n_folds: int = 3,
1151
+ n_background_samples: int = 200,
1152
+ n_test_samples: int = 500,
1153
+ device: str = 'cpu',
1154
+ figsize: Tuple[int, int] = (20, 8),
1155
+ show_plot: bool = True,
1156
+ show_train_plot: bool = True,
1157
+ show_test_plot: bool = True,
1158
+ top_n: int = 3
1159
+ ) -> Optional[Dict[str, Any]]:
1160
+ """Deep Learning 모델 SHAP 분석 (하위 호환성 래퍼 함수).
1161
+
1162
+ Deprecated: Use DeepSHAPAnalyzer instead.
1163
+ """
1164
+ config = SHAPConfig(
1165
+ n_folds=n_folds,
1166
+ n_background_samples=n_background_samples,
1167
+ n_test_samples=n_test_samples,
1168
+ figsize=figsize,
1169
+ top_n=top_n,
1170
+ target_class=target_class,
1171
+ device=device
1172
+ )
1173
+ data_loader = DataLoader(config)
1174
+ analyzer = DeepSHAPAnalyzer(config, data_loader, device=device)
1175
+ result = analyzer.analyze(
1176
+ model_name, region, data_sample,
1177
+ show_plot=show_plot,
1178
+ show_train_plot=show_train_plot,
1179
+ show_test_plot=show_test_plot
1180
+ )
1181
+ return result.to_dict() if result else None
1182
+
1183
+
1184
+ def calculate_wasserstein_distance(
1185
+ region: str,
1186
+ data_sample: str,
1187
+ top_features: List[str],
1188
+ model_type: str = 'tree',
1189
+ fold_idx: int = 0
1190
+ ) -> pd.DataFrame:
1191
+ """Wasserstein Distance 계산 (하위 호환성 래퍼 함수).
1192
+
1193
+ Deprecated: Use WassersteinCalculator instead.
1194
+ """
1195
+ config = SHAPConfig()
1196
+ data_loader = DataLoader(config)
1197
+ calculator = WassersteinCalculator(config, data_loader)
1198
+ return calculator.calculate(region, data_sample, top_features, model_type, fold_idx)
1199
+
1200
+
1201
+ def calculate_wd_from_shap_result(
1202
+ shap_result: Dict[str, Any],
1203
+ top_n: int = 3,
1204
+ use_train_features: bool = True,
1205
+ model_type: str = 'tree',
1206
+ fold_idx: int = 0
1207
+ ) -> pd.DataFrame:
1208
+ """SHAP 결과에서 WD 계산 (하위 호환성 래퍼 함수).
1209
+
1210
+ Deprecated: Use WassersteinCalculator instead.
1211
+ """
1212
+ config = SHAPConfig()
1213
+ data_loader = DataLoader(config)
1214
+ calculator = WassersteinCalculator(config, data_loader)
1215
+ return calculator.calculate_from_shap_result(
1216
+ shap_result, top_n, use_train_features, model_type, fold_idx
1217
+ )
1218
+
1219
+
1220
+ def elbow_plot(result: Dict[str, Any]) -> None:
1221
+ """Elbow plot 생성 (하위 호환성 래퍼 함수)."""
1222
+ config = SHAPConfig()
1223
+ visualizer = SHAPVisualizer(config)
1224
+ if 'importance_df_combined' in result:
1225
+ visualizer.plot_elbow(result['importance_df_combined'])
1226
+
1227
+
1228
+ # ==========================================
1229
+ # 유틸리티 함수 (기존 호환성 유지)
1230
+ # ==========================================
1231
+
1232
+ def calculate_csi(y_true: np.ndarray, y_pred: np.ndarray) -> float:
1233
+ """CSI(Critical Success Index) 점수를 계산합니다."""
1234
+ cm = confusion_matrix(y_true, y_pred)
1235
+ H = cm[0, 0] + cm[1, 1]
1236
+ F = cm[1, 0] + cm[2, 0] + cm[0, 1] + cm[2, 1]
1237
+ M = cm[0, 2] + cm[1, 2]
1238
+ csi = H / (H + F + M + 1e-10)
1239
+ return csi
1240
+
1241
+
1242
+ def csi_metric(y_true: np.ndarray, pred_prob: np.ndarray) -> Tuple[str, float, bool]:
1243
+ """LightGBM용 CSI 메트릭 함수."""
1244
+ y_pred_binary = np.argmax(pred_prob, axis=1)
1245
+ score = calculate_csi(y_true, y_pred_binary)
1246
+ return 'CSI', score, True
1247
+
1248
+
1249
+ def eval_metric_csi(y_true: np.ndarray, pred_prob: np.ndarray) -> float:
1250
+ """XGBoost용 CSI 메트릭 함��."""
1251
+ pred = np.argmax(pred_prob, axis=1)
1252
+ csi = calculate_csi(y_true, pred)
1253
+ return -1 * csi
1254
+
1255
+
1256
+ # 기존 상수들 (하위 호환성)
1257
+ FOLD_YEARS = SHAPConfig.FOLD_YEARS
1258
+ TEST_YEAR = SHAPConfig.TEST_YEAR
1259
+ DROP_COLUMNS = SHAPConfig.DROP_COLUMNS
1260
+ FEATURE_COLUMNS = SHAPConfig.FEATURE_COLUMNS
Analysis_code/7.ensemble/utils.py ADDED
@@ -0,0 +1,512 @@
 
 
 
 
 
 
 
 
 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2
+ import os
3
+ import sys
4
+ import warnings
5
+ from typing import List, Tuple, Any
6
+
7
+ # 서드파티 라이브러리
8
+ import numpy as np
9
+ import pandas as pd
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from joblib import load
13
+ from sklearn.metrics import confusion_matrix
14
+ from sklearn.preprocessing import LabelEncoder
15
+
16
+ # 경고 무시
17
+ warnings.filterwarnings('ignore')
18
+
19
+ # ==========================================
20
+ # 상수 정의
21
+ # ==========================================
22
+ TEST_YEAR = 2021
23
+ DROP_COLUMNS = ['multi_class', 'year']
24
+ FEATURE_COLUMNS = [
25
+ 'temp_C', 'precip_mm', 'wind_speed', 'wind_dir', 'hm',
26
+ 'vap_pressure', 'dewpoint_C', 'loc_pressure', 'sea_pressure',
27
+ 'solarRad', 'snow_cm', 'cloudcover', 'lm_cloudcover', 'low_cloudbase',
28
+ 'groundtemp', 'O3', 'NO2', 'PM10', 'PM25', 'year',
29
+ 'month', 'hour', 'ground_temp - temp_C', 'hour_sin', 'hour_cos',
30
+ 'month_sin', 'month_cos', 'multi_class'
31
+ ]
32
+
33
+ # 모델 타입 상수
34
+ TREE_MODELS = ['xgb', 'lgb']
35
+ DL_MODELS = ['ft_transformer', 'resnet_like', 'deepgbm']
36
+
37
+ # ==========================================
38
+ # 경로 설정
39
+ # ==========================================
40
+ def _setup_model_path() -> str:
41
+ """모델 클래스 import를 위한 경로를 설정하고 반환합니다.
42
+
43
+ Returns:
44
+ models 디렉토리의 절대 경로
45
+ """
46
+ try:
47
+ current_file_dir = os.path.dirname(os.path.abspath(__file__))
48
+ models_path = os.path.abspath(os.path.join(current_file_dir, '../models'))
49
+ except NameError:
50
+ # 노트북 환경에서 __file__이 없는 경우
51
+ cwd = os.getcwd()
52
+ if 'Analysis_code' in cwd:
53
+ analysis_code_dir = cwd[:cwd.index('Analysis_code') + len('Analysis_code')]
54
+ models_path = os.path.join(analysis_code_dir, 'models')
55
+ else:
56
+ models_path = '/workspace/visibility_prediction/Analysis_code/models'
57
+
58
+ if models_path not in sys.path:
59
+ sys.path.insert(0, models_path)
60
+
61
+ return models_path
62
+
63
+ # 모델 경로 설정 및 import
64
+ _setup_model_path()
65
+ from ft_transformer import FTTransformer
66
+ from resnet_like import ResNetLike
67
+ from deepgbm import DeepGBM
68
+
69
+ # ==========================================
70
+ # 메트릭 함수 (pickle 호환성)
71
+ # ==========================================
72
+ def calculate_csi(y_true: np.ndarray, y_pred: np.ndarray) -> float:
73
+ """CSI(Critical Success Index) 점수를 계산합니다.
74
+
75
+ Args:
76
+ y_true: 실제 레이블
77
+ y_pred: 예측 레이블
78
+
79
+ Returns:
80
+ CSI 점수 (0~1 사이의 값)
81
+ """
82
+ cm = confusion_matrix(y_true, y_pred)
83
+
84
+ # 혼동 행렬에서 H(Hit), F(False alarm), M(Miss) 추출
85
+ H = cm[0, 0] + cm[1, 1]
86
+ F = cm[1, 0] + cm[2, 0] + cm[0, 1] + cm[2, 1]
87
+ M = cm[0, 2] + cm[1, 2]
88
+
89
+ # CSI 계산
90
+ csi = H / (H + F + M + 1e-10)
91
+ return csi
92
+
93
+ def eval_metric_csi(y_true: np.ndarray, pred_prob: np.ndarray) -> float:
94
+ """XGBoost용 CSI 메트릭 함수.
95
+
96
+ Args:
97
+ y_true: 실제 레이블
98
+ pred_prob: 예측 확률
99
+
100
+ Returns:
101
+ CSI 점수의 음수값
102
+ """
103
+ pred = np.argmax(pred_prob, axis=1)
104
+ csi = calculate_csi(y_true, pred)
105
+ return -1 * csi
106
+
107
+ def csi_metric(y_true: np.ndarray, pred_prob: np.ndarray) -> Tuple[str, float, bool]:
108
+ """LightGBM용 CSI 메트릭 함수.
109
+
110
+ Args:
111
+ y_true: 실제 레이블
112
+ pred_prob: 예측 확률 (shape: [n_samples, n_classes])
113
+
114
+ Returns:
115
+ ('CSI', score, higher_better) 튜플
116
+ """
117
+ y_pred_binary = np.argmax(pred_prob, axis=1)
118
+ score = calculate_csi(y_true, y_pred_binary)
119
+ return 'CSI', score, True
120
+
121
+ # ==========================================
122
+ # Pickle 호환성 함수 등록
123
+ # ==========================================
124
+ def _register_pickle_functions(model_name: str) -> None:
125
+ """모델 로드를 위해 __main__ 모듈에 필요한 함수를 등록합니다.
126
+
127
+ 모델이 저장될 때 __main__ 모듈에서 정의된 함수를 참조했을 수 있으므로,
128
+ pickle이 모델을 로드할 때 함수를 찾을 수 있도록 등록합니다.
129
+
130
+ Args:
131
+ model_name: 모델 이름 ('xgb' 또는 'lgb')
132
+ """
133
+ if '__main__' not in sys.modules:
134
+ return
135
+
136
+ main_module = sys.modules['__main__']
137
+ main_module.calculate_csi = calculate_csi
138
+
139
+ if model_name == 'xgb':
140
+ main_module.eval_metric_csi = eval_metric_csi
141
+ elif model_name == 'lgb':
142
+ main_module.csi_metric = csi_metric
143
+
144
+ # ==========================================
145
+ # 데이터 전처리 함수
146
+ # ==========================================
147
+ def add_derived_features(df: pd.DataFrame) -> pd.DataFrame:
148
+ """제거했던 파생 변수들을 복구합니다.
149
+
150
+ Args:
151
+ df: 원본 데이터프레임
152
+
153
+ Returns:
154
+ 파생 변수가 추가된 데이터프레임
155
+ """
156
+ df = df.copy()
157
+ df['hour_sin'] = np.sin(2 * np.pi * df['hour'] / 24)
158
+ df['hour_cos'] = np.cos(2 * np.pi * df['hour'] / 24)
159
+ df['month_sin'] = np.sin(2 * np.pi * df['month'] / 12)
160
+ df['month_cos'] = np.cos(2 * np.pi * df['month'] / 12)
161
+ df['ground_temp - temp_C'] = df['groundtemp'] - df['temp_C']
162
+ return df
163
+
164
+ def preprocessing(df: pd.DataFrame) -> pd.DataFrame:
165
+ """데이터 전처리 함수.
166
+
167
+ Args:
168
+ df: 원본 데이터프레임
169
+
170
+ Returns:
171
+ 전처리된 데이터프레임
172
+ """
173
+ df = df[df.columns].copy()
174
+ df['year'] = df['year'].astype('int')
175
+ df['month'] = df['month'].astype('int')
176
+ df['hour'] = df['hour'].astype('int')
177
+ df = add_derived_features(df).copy()
178
+ df['multi_class'] = df['multi_class'].astype('int')
179
+ df.loc[df['wind_dir'] == '정온', 'wind_dir'] = "0"
180
+ df['wind_dir'] = df['wind_dir'].astype('int')
181
+ df = df[FEATURE_COLUMNS].copy()
182
+ return df
183
+
184
+ # ==========================================
185
+ # 모델 로드 함수
186
+ # ==========================================
187
+ def load_model(model_name: str, region: str, data_sample: str) -> List[Any]:
188
+ """모델을 로드하는 함수.
189
+
190
+ Args:
191
+ model_name: 모델 이름 ('xgb', 'lgb', 'ft_transformer', 'resnet_like', 'deepgbm')
192
+ region: 지역명 (예: 'seoul', 'busan')
193
+ data_sample: 데이터 샘플 타입 (예: 'pure', 'smote', 'ctgan10000')
194
+
195
+ Returns:
196
+ 로드된 모델 리스트 (각 fold별 모델)
197
+
198
+ Raises:
199
+ FileNotFoundError: 모델 파일을 찾을 수 없는 경우
200
+ ValueError: 모델 이름이 유효하지 않은 경우
201
+ """
202
+ if model_name not in TREE_MODELS + DL_MODELS:
203
+ raise ValueError(
204
+ f"Unknown model_name: {model_name}. "
205
+ f"Must be one of {TREE_MODELS + DL_MODELS}"
206
+ )
207
+
208
+ # Tree-based 모델의 경우 pickle 호환성 함수 등록
209
+ if model_name in TREE_MODELS:
210
+ _register_pickle_functions(model_name)
211
+
212
+ model_path = f"../save_model/{model_name}_optima/{model_name}_{data_sample}_{region}.pkl"
213
+
214
+ if not os.path.exists(model_path):
215
+ raise FileNotFoundError(
216
+ f"모델 파일을 찾을 수 없습니다: {model_path}"
217
+ )
218
+
219
+ try:
220
+ models = load(model_path)
221
+ except Exception as e:
222
+ raise FileNotFoundError(f"모델 로드 실패 ({model_path}): {e}")
223
+
224
+ return models
225
+
226
+ def load_scaler(model_name: str, region: str, data_sample: str) -> List[Any]:
227
+ """각 fold의 scaler를 로드하는 함수.
228
+
229
+ Args:
230
+ model_name: 모델 이름
231
+ region: 지역명
232
+ data_sample: 데이터 샘플 타입
233
+
234
+ Returns:
235
+ 로드된 scaler 리스트 (각 fold별 scaler)
236
+
237
+ Raises:
238
+ FileNotFoundError: Scaler 파일을 찾을 수 없는 경우
239
+ """
240
+ if data_sample == 'pure':
241
+ scaler_filename = f'{model_name}_pure_{region}_scaler.pkl'
242
+ else:
243
+ scaler_filename = f'{model_name}_{data_sample}_{region}_scaler.pkl'
244
+
245
+ scaler_path = f'../save_model/{model_name}_optima/scaler/{scaler_filename}'
246
+
247
+ if not os.path.exists(scaler_path):
248
+ raise FileNotFoundError(
249
+ f"Scaler 파일을 찾을 수 없습니다: {scaler_path}"
250
+ )
251
+
252
+ try:
253
+ scalers = load(scaler_path)
254
+ except Exception as e:
255
+ raise FileNotFoundError(f"Scaler 로드 실패 ({scaler_path}): {e}")
256
+
257
+ return scalers
258
+
259
+ # ==========================================
260
+ # Tree-based 모델용 헬퍼 함수
261
+ # ==========================================
262
+ def _prepare_test_data_tree(region: str) -> Tuple[pd.DataFrame, np.ndarray]:
263
+ """Tree-based 모델용 test 데이터를 준비합니다.
264
+
265
+ Args:
266
+ region: 지역명
267
+
268
+ Returns:
269
+ tuple: (X_test, y_test)
270
+ - X_test: 전처리된 test 데이터 (설명변수만)
271
+ - y_test: test 데이터의 target 값 (multi_class)
272
+ """
273
+ test_data = pd.read_csv(f"../../data/data_for_modeling/{region}_test.csv")
274
+ test_data = preprocessing(test_data)
275
+ test_data = test_data.loc[test_data['year'].isin([TEST_YEAR]), :]
276
+ X_test = test_data.drop(columns=DROP_COLUMNS)
277
+ y_test = test_data['multi_class'].values
278
+ return X_test, y_test
279
+
280
+ def _predict_tree_model(model: Any, X_test: pd.DataFrame) -> np.ndarray:
281
+ """Tree-based 모델로 예측을 수행합니다.
282
+
283
+ Args:
284
+ model: 학습된 모델 (XGBoost 또는 LightGBM)
285
+ X_test: Test 데이터
286
+
287
+ Returns:
288
+ 예측 확률 (n_samples, n_classes)
289
+ """
290
+ return model.predict_proba(X_test)
291
+
292
+ # ==========================================
293
+ # Deep Learning 모델용 헬퍼 함수
294
+ # ==========================================
295
+ def _prepare_test_data_dl(
296
+ region: str,
297
+ data_sample: str,
298
+ fold_idx: int,
299
+ scaler: Any
300
+ ) -> Tuple[torch.Tensor, torch.Tensor, pd.Index, pd.Index, np.ndarray]:
301
+ """Deep learning 모델용 test 데이터를 준비합니다.
302
+
303
+ Args:
304
+ region: 지역명
305
+ data_sample: 데이터 샘플 타입
306
+ fold_idx: Fold 인덱스 (0, 1, 2)
307
+ scaler: 해당 fold의 scaler (QuantileTransformer)
308
+
309
+ Returns:
310
+ tuple: (X_test_num, X_test_cat, categorical_cols, numerical_cols, y_test)
311
+ - X_test_num: Numerical features tensor
312
+ - X_test_cat: Categorical features tensor
313
+ - categorical_cols: 범주형 변수 컬럼명
314
+ - numerical_cols: 연속형 변수 컬럼명
315
+ - y_test: test 데이터의 target 값 (multi_class)
316
+ """
317
+ # Train 데이터 로드 (Label Encoder 학습용)
318
+ if data_sample == 'pure':
319
+ train_path = f"../../data/data_for_modeling/{region}_train.csv"
320
+ train_data = preprocessing(pd.read_csv(train_path, index_col=0))
321
+ train_data = train_data.loc[
322
+ ~train_data['year'].isin([TEST_YEAR - (fold_idx + 1)]), :
323
+ ]
324
+ else:
325
+ train_data = pd.read_csv(
326
+ f"../../data/data_oversampled/{data_sample}/"
327
+ f"{data_sample}_{fold_idx+1}_{region}.csv"
328
+ )
329
+ train_data = preprocessing(train_data)
330
+
331
+ # Test 데이터 로드
332
+ test_data = pd.read_csv(f"../../data/data_for_modeling/{region}_test.csv")
333
+ test_data = preprocessing(test_data)
334
+ test_data = test_data.loc[test_data['year'].isin([TEST_YEAR]), :]
335
+
336
+ # 컬럼 정렬 (일관성 유지)
337
+ common_columns = train_data.columns.to_list()
338
+ train_data = train_data[common_columns]
339
+ test_data = test_data[common_columns]
340
+
341
+ # 설명변수 분리
342
+ X_train = train_data.drop(columns=DROP_COLUMNS)
343
+ X_test = test_data.drop(columns=DROP_COLUMNS)
344
+
345
+ # 범주형 & 연속형 변수 분리
346
+ categorical_cols = X_train.select_dtypes(
347
+ include=['object', 'category', 'int64']
348
+ ).columns
349
+ numerical_cols = X_train.select_dtypes(include=['float64']).columns
350
+
351
+ # 범주형 변수 Label Encoding (train 데이터 기준으로 학습)
352
+ label_encoders = {}
353
+ for col in categorical_cols:
354
+ le = LabelEncoder()
355
+ le.fit(X_train[col])
356
+ label_encoders[col] = le
357
+
358
+ # 변환 적용
359
+ for col in categorical_cols:
360
+ X_test[col] = label_encoders[col].transform(X_test[col])
361
+
362
+ # 연속형 변수 Scaler 변환
363
+ X_test[numerical_cols] = scaler.transform(X_test[numerical_cols])
364
+
365
+ # 텐서 변환
366
+ X_test_num = torch.tensor(
367
+ X_test[numerical_cols].values, dtype=torch.float32
368
+ )
369
+ X_test_cat = torch.tensor(
370
+ X_test[categorical_cols].values, dtype=torch.long
371
+ )
372
+
373
+ # Target 값 추출
374
+ y_test = test_data['multi_class'].values
375
+
376
+ return X_test_num, X_test_cat, categorical_cols, numerical_cols, y_test
377
+
378
+ def _predict_dl_model(
379
+ model: torch.nn.Module,
380
+ X_test_num: torch.Tensor,
381
+ X_test_cat: torch.Tensor,
382
+ model_name: str,
383
+ device: str,
384
+ batch_size: int = 1024
385
+ ) -> np.ndarray:
386
+ """Deep learning 모델로 예측을 수행합니다.
387
+
388
+ Args:
389
+ model: PyTorch 모델
390
+ X_test_num: Numerical features tensor
391
+ X_test_cat: Categorical features tensor
392
+ model_name: 모델 이름 ('ft_transformer', 'resnet_like', 'deepgbm')
393
+ device: 연산 장치 ('cpu' 또는 'cuda')
394
+ batch_size: 배치 크기 (메모리 효율을 위해, 기본값: 1024)
395
+
396
+ Returns:
397
+ 예측 확률 (n_samples, n_classes)
398
+
399
+ Raises:
400
+ ValueError: 알 수 없는 모델 이름인 경우
401
+ """
402
+ model.eval()
403
+ model.to(device)
404
+
405
+ n_samples = X_test_num.shape[0]
406
+ all_probs = []
407
+
408
+ with torch.no_grad():
409
+ for i in range(0, n_samples, batch_size):
410
+ end_idx = min(i + batch_size, n_samples)
411
+ batch_num = X_test_num[i:end_idx].to(device)
412
+ batch_cat = X_test_cat[i:end_idx].to(device)
413
+
414
+ # 모델별 입력 형식 처리
415
+ # 모든 딥러닝 모델이 (x_num, x_cat) 두 개의 텐서를 받음
416
+ # resnet_like는 내부에서 torch.cat으로 결합함
417
+ if model_name in DL_MODELS:
418
+ output = model(batch_num, batch_cat)
419
+ else:
420
+ raise ValueError(
421
+ f"Unknown model_name: {model_name}. "
422
+ f"Must be one of {DL_MODELS}"
423
+ )
424
+
425
+ # Softmax 적용하여 확률 변환
426
+ probs = F.softmax(output, dim=1)
427
+ all_probs.append(probs.cpu().numpy())
428
+
429
+ return np.vstack(all_probs)
430
+
431
+ # ==========================================
432
+ # 메인 함수
433
+ # ==========================================
434
+ def predict_test_proba(
435
+ model_name: str,
436
+ region: str,
437
+ data_sample: str,
438
+ device: str = 'cpu',
439
+ n_folds: int = 3
440
+ ) -> Tuple[np.ndarray, np.ndarray]:
441
+ """Test 데이터에 대한 예측 확률과 target 값을 반환하는 함수.
442
+
443
+ Args:
444
+ model_name: 모델 이름 ('xgb', 'lgb', 'ft_transformer', 'resnet_like', 'deepgbm')
445
+ region: 지역명 (예: 'seoul', 'busan')
446
+ data_sample: 데이터 샘플 타입 (예: 'pure', 'smote', 'ctgan10000')
447
+ device: 연산 장치 ('cpu' 또는 'cuda', 기본값: 'cpu')
448
+ n_folds: Fold 개수 (기본값: 3)
449
+
450
+ Returns:
451
+ tuple: (probs, y_test)
452
+ - probs: shape (n_folds, n_samples, n_classes) - 각 fold별 예측 확률
453
+ - y_test: shape (n_samples,) - test 데이터의 target 값 (multi_class)
454
+
455
+ Raises:
456
+ ValueError: 모델 이름이 유효하지 않거나 fold 개수가 일치하지 않는 경우
457
+ FileNotFoundError: 모델 또는 scaler 파일을 찾을 수 없는 경우
458
+ """
459
+ # 모델 타입 확인
460
+ if model_name not in TREE_MODELS + DL_MODELS:
461
+ raise ValueError(
462
+ f"Unknown model_name: {model_name}. "
463
+ f"Must be one of {TREE_MODELS + DL_MODELS}"
464
+ )
465
+
466
+ # 모델 로드
467
+ models = load_model(model_name, region, data_sample)
468
+
469
+ if len(models) != n_folds:
470
+ raise ValueError(
471
+ f"로드된 모델 개수({len(models)})가 "
472
+ f"n_folds({n_folds})와 일치하지 않습니다."
473
+ )
474
+
475
+ # Tree-based 모델 처리
476
+ if model_name in TREE_MODELS:
477
+ X_test, y_test = _prepare_test_data_tree(region)
478
+ all_probs = []
479
+
480
+ for fold_idx in range(n_folds):
481
+ prob = _predict_tree_model(models[fold_idx], X_test)
482
+ all_probs.append(prob)
483
+
484
+ return np.array(all_probs), y_test
485
+
486
+ # Deep learning 모델 처리
487
+ else:
488
+ # Scaler 로드
489
+ scalers = load_scaler(model_name, region, data_sample)
490
+
491
+ if len(scalers) != n_folds:
492
+ raise ValueError(
493
+ f"로드된 scaler 개수({len(scalers)})가 "
494
+ f"n_folds({n_folds})와 일치하지 않습니다."
495
+ )
496
+
497
+ all_probs = []
498
+ y_test = None
499
+
500
+ for fold_idx in range(n_folds):
501
+ # Test 데이터 준비
502
+ X_test_num, X_test_cat, _, _, y_test = _prepare_test_data_dl(
503
+ region, data_sample, fold_idx, scalers[fold_idx]
504
+ )
505
+
506
+ # 예측
507
+ prob = _predict_dl_model(
508
+ models[fold_idx], X_test_num, X_test_cat, model_name, device
509
+ )
510
+ all_probs.append(prob)
511
+
512
+ return np.array(all_probs), y_test
Analysis_code/final_test/final.ipynb DELETED
@@ -1,1143 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "code",
5
- "execution_count": null,
6
- "metadata": {},
7
- "outputs": [],
8
- "source": [
9
- "import pandas as pd\n",
10
- "import numpy as np\n",
11
- "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
12
- "import torch\n",
13
- "from torch.utils.data import DataLoader, TensorDataset\n",
14
- "import random\n",
15
- "from collections import Counter\n",
16
- "import sys\n",
17
- "sys.path.append('../../../../../../../../mnt/workspace/LightGBM/python-package')\n",
18
- "from lightgbm import LGBMClassifier\n",
19
- "import numpy as np\n",
20
- "from sklearn.model_selection import train_test_split\n",
21
- "from sklearn.inspection import permutation_importance\n",
22
- "from sklearn.metrics import confusion_matrix,accuracy_score, recall_score, precision_score\n",
23
- "from sklearn.model_selection import StratifiedKFold\n",
24
- "from xgboost import XGBClassifier\n",
25
- "from warnings import filterwarnings\n",
26
- "filterwarnings('ignore')\n",
27
- "import sys\n",
28
- "sys.path.append('../../')\n",
29
- "import torch\n",
30
- "import torch.nn as nn\n",
31
- "import torch.optim as optim\n",
32
- "import optuna\n",
33
- "import pandas as pd\n",
34
- "import numpy as np\n",
35
- "import random\n",
36
- "from models.ft_transformer import FTTransformer\n",
37
- "from models.resnet_like import ResNetLike\n",
38
- "from models.deepgbm import DeepGBM\n",
39
- "from pytorch_tabnet.tab_model import TabNetClassifier\n",
40
- "from sklearn.metrics import accuracy_score, f1_score, roc_auc_score, confusion_matrix"
41
- ]
42
- },
43
- {
44
- "cell_type": "code",
45
- "execution_count": 2,
46
- "metadata": {},
47
- "outputs": [],
48
- "source": [
49
- "# Python 및 Numpy 시드 고정\n",
50
- "seed = 42\n",
51
- "random.seed(seed)\n",
52
- "np.random.seed(seed)\n",
53
- "\n",
54
- "# PyTorch 시드 고정\n",
55
- "torch.manual_seed(seed)\n",
56
- "torch.cuda.manual_seed(seed)\n",
57
- "torch.cuda.manual_seed_all(seed) # Multi-GPU 환경에서 동일한 시드 적용\n",
58
- "\n",
59
- "# PyTorch 연산의 결정적 모드 설정\n",
60
- "torch.backends.cudnn.deterministic = True # 실행마다 동일한 결과를 보장\n",
61
- "torch.backends.cudnn.benchmark = True # 성능 최적화를 활성화 (가능한 한 빠른 연산 수행)\n",
62
- "\n",
63
- "# 전처리 함수\n",
64
- "def preprocessing(df):\n",
65
- " df = df[df.columns].copy()\n",
66
- " df.loc[df['wind_dir']=='정온', 'wind_dir'] = \"0\"\n",
67
- " df['wind_dir'] = df['wind_dir'].astype('int')\n",
68
- " df['lm_cloudcover'] = df['lm_cloudcover'].astype('int')\n",
69
- " df['cloudcover'] = df['cloudcover'].astype('int')\n",
70
- " return df\n",
71
- "\n",
72
- "# 데이터셋 준비 함수\n",
73
- "def prepare_dataset(region, data_sample='pure', target='multi', fold=3):\n",
74
- "\n",
75
- " # 데이터 경로 지정\n",
76
- " dat_path = f\"../../data/data_for_modeling/{region}_train.csv\"\n",
77
- " if data_sample == 'pure':\n",
78
- " train_path = dat_path\n",
79
- " else:\n",
80
- " train_path = f'../../data/data_oversampled/{data_sample}/{data_sample}_{fold}_{region}.csv'\n",
81
- " train_path = f'../../data/data_oversampled/{data_sample}/{data_sample}_{fold}_{region}.csv'\n",
82
- " test_path = f\"../../data/data_for_modeling/{region}_test.csv\"\n",
83
- " drop_col = ['binary_class','multi_class','visi','year']\n",
84
- " target_col = f'{target}_class'\n",
85
- " \n",
86
- " # 데이터 로드\n",
87
- " region_dat = preprocessing(pd.read_csv(dat_path, index_col=0))\n",
88
- " if data_sample == 'pure':\n",
89
- " region_train = region_dat.loc[~region_dat['year'].isin([2021-fold]), :]\n",
90
- " else:\n",
91
- " region_train = preprocessing(pd.read_csv(train_path))\n",
92
- " region_val = region_dat.loc[region_dat['year'].isin([2021-fold]), :]\n",
93
- " region_test = preprocessing(pd.read_csv(test_path))\n",
94
- "\n",
95
- " # 컬럼 정렬 (일관성 유지)\n",
96
- " common_columns = region_train.columns.to_list()\n",
97
- " train_data = region_train[common_columns]\n",
98
- " val_data = region_val[common_columns]\n",
99
- " test_data = region_test[common_columns]\n",
100
- "\n",
101
- " # 설명변수 & 타겟 분리\n",
102
- " X_train = train_data.drop(columns=drop_col)\n",
103
- " y_train = train_data[target_col]\n",
104
- " X_val = val_data.drop(columns=drop_col)\n",
105
- " y_val = val_data[target_col]\n",
106
- " X_test = test_data.drop(columns=drop_col)\n",
107
- " y_test = test_data[target_col]\n",
108
- "\n",
109
- " # 범주형 & 연속형 변수 분리\n",
110
- " categorical_cols = X_train.select_dtypes(include=['object', 'category', 'int64']).columns\n",
111
- " numerical_cols = X_train.select_dtypes(include=['float64']).columns\n",
112
- "\n",
113
- " # 범주형 변수 Label Encoding\n",
114
- " label_encoders = {}\n",
115
- " for col in categorical_cols:\n",
116
- " le = LabelEncoder()\n",
117
- " le.fit(X_train[col]) # Train 데이터 기준으로 학습\n",
118
- " label_encoders[col] = le\n",
119
- "\n",
120
- " # 변환 적용\n",
121
- " for col in categorical_cols:\n",
122
- " X_train[col] = label_encoders[col].transform(X_train[col])\n",
123
- " X_val[col] = label_encoders[col].transform(X_val[col])\n",
124
- " X_test[col] = label_encoders[col].transform(X_test[col])\n",
125
- "\n",
126
- " # 연속형 변수 Standard Scaling\n",
127
- " scaler = StandardScaler()\n",
128
- " scaler.fit(X_train[numerical_cols]) # Train 데이터 기준으로 학습\n",
129
- "\n",
130
- " # 변환 적용\n",
131
- " X_train[numerical_cols] = scaler.transform(X_train[numerical_cols])\n",
132
- " X_val[numerical_cols] = scaler.transform(X_val[numerical_cols])\n",
133
- " X_test[numerical_cols] = scaler.transform(X_test[numerical_cols])\n",
134
- "\n",
135
- " return X_train, X_val, X_test, y_train, y_val, y_test, categorical_cols, numerical_cols\n",
136
- "\n",
137
- "# 데이터 변환 및 dataloader 생성 함수\n",
138
- "def prepare_dataloader(region, data_sample='pure', target='multi', fold=3, random_state=None):\n",
139
- "\n",
140
- " # 데이터 경로 지정\n",
141
- " dat_path = f\"../../data/data_for_modeling/{region}_train.csv\"\n",
142
- " if data_sample == 'pure':\n",
143
- " train_path = dat_path\n",
144
- " else:\n",
145
- " train_path = f'../../data/data_oversampled/{data_sample}/{data_sample}_{fold}_{region}.csv'\n",
146
- " train_path = f'../../data/data_oversampled/{data_sample}/{data_sample}_{fold}_{region}.csv'\n",
147
- " test_path = f\"../../data/data_for_modeling/{region}_test.csv\"\n",
148
- " drop_col = ['binary_class','multi_class','visi','year']\n",
149
- " target_col = f'{target}_class'\n",
150
- " \n",
151
- " # 데이터 로드\n",
152
- " region_dat = preprocessing(pd.read_csv(dat_path, index_col=0))\n",
153
- " if data_sample == 'pure':\n",
154
- " region_train = region_dat.loc[~region_dat['year'].isin([2021-fold]), :]\n",
155
- " else:\n",
156
- " region_train = preprocessing(pd.read_csv(train_path))\n",
157
- " region_val = region_dat.loc[region_dat['year'].isin([2021-fold]), :]\n",
158
- " region_test = preprocessing(pd.read_csv(test_path))\n",
159
- "\n",
160
- " # 컬럼 정렬 (일관성 유지)\n",
161
- " common_columns = region_train.columns.to_list()\n",
162
- " train_data = region_train[common_columns]\n",
163
- " val_data = region_val[common_columns]\n",
164
- " test_data = region_test[common_columns]\n",
165
- "\n",
166
- " # 설명변수 & 타겟 분리\n",
167
- " X_train = train_data.drop(columns=drop_col)\n",
168
- " y_train = train_data[target_col]\n",
169
- " X_val = val_data.drop(columns=drop_col)\n",
170
- " y_val = val_data[target_col]\n",
171
- " X_test = test_data.drop(columns=drop_col)\n",
172
- " y_test = test_data[target_col]\n",
173
- "\n",
174
- " # 범주형 & 연속형 변수 분리\n",
175
- " categorical_cols = X_train.select_dtypes(include=['object', 'category', 'int64']).columns\n",
176
- " numerical_cols = X_train.select_dtypes(include=['float64']).columns\n",
177
- "\n",
178
- " # 범주형 변수 Label Encoding\n",
179
- " label_encoders = {}\n",
180
- " for col in categorical_cols:\n",
181
- " le = LabelEncoder()\n",
182
- " le.fit(X_train[col]) # Train 데이터 기준으로 학습\n",
183
- " label_encoders[col] = le\n",
184
- "\n",
185
- " # 변환 적용\n",
186
- " for col in categorical_cols:\n",
187
- " X_train[col] = label_encoders[col].transform(X_train[col])\n",
188
- " X_val[col] = label_encoders[col].transform(X_val[col])\n",
189
- " X_test[col] = label_encoders[col].transform(X_test[col])\n",
190
- "\n",
191
- " # 연속형 변수 Standard Scaling\n",
192
- " scaler = StandardScaler()\n",
193
- " scaler.fit(X_train[numerical_cols]) # Train 데이터 기준으로 학습\n",
194
- "\n",
195
- " # 변환 적용\n",
196
- " X_train[numerical_cols] = scaler.transform(X_train[numerical_cols])\n",
197
- " X_val[numerical_cols] = scaler.transform(X_val[numerical_cols])\n",
198
- " X_test[numerical_cols] = scaler.transform(X_test[numerical_cols])\n",
199
- "\n",
200
- " # 연속형 변수와 범주형 변수 분리\n",
201
- " X_train_num = torch.tensor(X_train[numerical_cols].values, dtype=torch.float32)\n",
202
- " X_train_cat = torch.tensor(X_train[categorical_cols].values, dtype=torch.long)\n",
203
- "\n",
204
- " X_val_num = torch.tensor(X_val[numerical_cols].values, dtype=torch.float32)\n",
205
- " X_val_cat = torch.tensor(X_val[categorical_cols].values, dtype=torch.long)\n",
206
- "\n",
207
- " X_test_num = torch.tensor(X_test[numerical_cols].values, dtype=torch.float32)\n",
208
- " X_test_cat = torch.tensor(X_test[categorical_cols].values, dtype=torch.long)\n",
209
- "\n",
210
- " # 레이블 변환\n",
211
- " if target == \"binary\":\n",
212
- " y_train_tensor = torch.tensor(y_train.values, dtype=torch.float32) # 이진 분류 → float32\n",
213
- " y_val_tensor = torch.tensor(y_val.values, dtype=torch.float32)\n",
214
- " y_test_tensor = torch.tensor(y_test.values, dtype=torch.float32)\n",
215
- " elif target == \"multi\":\n",
216
- " y_train_tensor = torch.tensor(y_train.values, dtype=torch.long) # 다중 분류 → long\n",
217
- " y_val_tensor = torch.tensor(y_val.values, dtype=torch.long)\n",
218
- " y_test_tensor = torch.tensor(y_test.values, dtype=torch.long)\n",
219
- " else:\n",
220
- " raise ValueError(\"target must be 'binary' or 'multi'\")\n",
221
- "\n",
222
- " # TensorDataset 생성\n",
223
- " train_dataset = TensorDataset(X_train_num, X_train_cat, y_train_tensor)\n",
224
- " val_dataset = TensorDataset(X_val_num, X_val_cat, y_val_tensor)\n",
225
- " test_dataset = TensorDataset(X_test_num, X_test_cat, y_test_tensor)\n",
226
- "\n",
227
- " # DataLoader 생성\n",
228
- " if random_state == None:\n",
229
- " train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)\n",
230
- " else:\n",
231
- " train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True, generator=torch.Generator().manual_seed(random_state))\n",
232
- " val_loader = DataLoader(val_dataset, batch_size=64, shuffle=False)\n",
233
- " test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)\n",
234
- " \n",
235
- " return X_train, categorical_cols, numerical_cols, train_loader, val_loader, test_loader"
236
- ]
237
- },
238
- {
239
- "cell_type": "code",
240
- "execution_count": 3,
241
- "metadata": {},
242
- "outputs": [],
243
- "source": [
244
- "import os\n",
245
- "import torch\n",
246
- "# 디바이스 설정 (CUDA 사용 가능하면 GPU로, 아니면 CPU로)\n",
247
- "import glob\n",
248
- "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
249
- "\n",
250
- "def calculate_csi(Y_test, pred):\n",
251
- "\n",
252
- " cm = confusion_matrix(Y_test, pred) # 변수 이름을 cm으로 변경\n",
253
- " # 혼동 행렬에서 H, F, M 추출\n",
254
- " H = (cm[0, 0] + cm[1, 1])\n",
255
- " \n",
256
- " F = (cm[1, 0] + cm[2, 0] +\n",
257
- " cm[0, 1] + cm[2, 1])\n",
258
- "\n",
259
- " M = (cm[0, 2] + cm[1, 2])\n",
260
- " \n",
261
- " # CSI 계산\n",
262
- " CSI = H / (H + F + M + 1e-10)\n",
263
- " return CSI\n",
264
- "\n",
265
- "def csi_metric(y_true, pred):\n",
266
- " y_pred_binary = np.argmax(pred, axis=1)\n",
267
- " score = calculate_csi(y_true, y_pred_binary)\n",
268
- " return 'CSI', score, True # higher_better=True\n",
269
- "\n",
270
- "\n",
271
- "def eval_metric_csi(y_true, pred_prob):\n",
272
- "\n",
273
- " pred = np.argmax(pred_prob, axis=1)\n",
274
- " y_true = y_true\n",
275
- " y_pred = pred\n",
276
- " csi = calculate_csi(y_true, y_pred)\n",
277
- " return -1*csi\n",
278
- "\n",
279
- "\n",
280
- "from sklearn.metrics import matthews_corrcoef, accuracy_score\n",
281
- "\n",
282
- "def multiclass_mcc(y_val, y_pred):\n",
283
- " \"\"\"\n",
284
- " 다중 분류에서도 sklearn의 matthews_corrcoef를 그대로 사용할 수 있음.\n",
285
- " \"\"\"\n",
286
- " return matthews_corrcoef(y_val, y_pred)"
287
- ]
288
- },
289
- {
290
- "cell_type": "code",
291
- "execution_count": 4,
292
- "metadata": {},
293
- "outputs": [],
294
- "source": [
295
- "import os\n",
296
- "import torch\n",
297
- "# 디바이스 설정 (CUDA 사용 가능하면 GPU로, 아니면 CPU로)\n",
298
- "import glob\n",
299
- "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
300
- "import warnings\n",
301
- "warnings.filterwarnings('ignore')\n",
302
- "\n",
303
- "def calculate_csi(Y_test, pred):\n",
304
- "\n",
305
- " cm = confusion_matrix(Y_test, pred) # 변수 이름을 cm으로 변경\n",
306
- " # 혼동 행렬에서 H, F, M 추출\n",
307
- " H = (cm[0, 0] + cm[1, 1])\n",
308
- " \n",
309
- " F = (cm[1, 0] + cm[2, 0] +\n",
310
- " cm[0, 1] + cm[2, 1])\n",
311
- "\n",
312
- " M = (cm[0, 2] + cm[1, 2])\n",
313
- " \n",
314
- " # CSI 계산\n",
315
- " CSI = H / (H + F + M + 1e-10)\n",
316
- " return CSI\n",
317
- "\n",
318
- "# Soft Voting 앙상블\n",
319
- "def get_proba(region, model_choose, data_sample, fold, target='multi'):\n",
320
- " _, _, _, _,val_loader , test_loader = prepare_dataloader(region=region, data_sample=data_sample, target=target,fold=fold ,random_state=120)\n",
321
- "\n",
322
- " folder_path = f'../save_model/{model_choose}/{data_sample}'\n",
323
- " model_paths = [path for path in glob.glob(f'{folder_path}/*.pth') if f'{region}' in path]\n",
324
- "\n",
325
- " model = torch.load(model_paths[fold-1], weights_only=False).to(device)\n",
326
- " model.eval()\n",
327
- "\n",
328
- " test_preds = []\n",
329
- "\n",
330
- "\n",
331
- " with torch.no_grad():\n",
332
- " for x_num_batch, x_cat_batch, _ in test_loader:\n",
333
- " output = model(x_num_batch.to(device), x_cat_batch.to(device))\n",
334
- " output = torch.softmax(output, dim=1)\n",
335
- " test_preds.extend(output.cpu().numpy())\n",
336
- "\n",
337
- "\n",
338
- " return test_preds\n"
339
- ]
340
- },
341
- {
342
- "cell_type": "code",
343
- "execution_count": 5,
344
- "metadata": {},
345
- "outputs": [],
346
- "source": [
347
- "df_seoul = pd.read_csv(\"../../data/data_for_modeling/seoul_train.csv\")\n",
348
- "df_seoul_test = pd.read_csv(\"../../data/data_for_modeling/seoul_test.csv\")\n",
349
- "\n",
350
- "df_busan = pd.read_csv(\"../../data/data_for_modeling/busan_train.csv\")\n",
351
- "df_busan_test = pd.read_csv(\"../../data/data_for_modeling/busan_test.csv\")\n",
352
- "\n",
353
- "df_daegu = pd.read_csv(\"../../data/data_for_modeling/daegu_train.csv\")\n",
354
- "df_daegu_test = pd.read_csv(\"../../data/data_for_modeling/daegu_test.csv\")\n",
355
- "\n",
356
- "df_daejeon = pd.read_csv(\"../../data/data_for_modeling/daejeon_train.csv\")\n",
357
- "df_daejeon_test = pd.read_csv(\"../../data/data_for_modeling/daejeon_test.csv\")\n",
358
- "\n",
359
- "df_incheon = pd.read_csv(\"../../data/data_for_modeling/incheon_train.csv\")\n",
360
- "df_incheon_test = pd.read_csv(\"../../data/data_for_modeling/incheon_test.csv\")\n",
361
- "\n",
362
- "df_gwangju = pd.read_csv(\"../../data/data_for_modeling/gwangju_train.csv\")\n",
363
- "df_gwangju_test = pd.read_csv(\"../../data/data_for_modeling/gwangju_test.csv\")"
364
- ]
365
- },
366
- {
367
- "cell_type": "code",
368
- "execution_count": 6,
369
- "metadata": {},
370
- "outputs": [],
371
- "source": [
372
- "def preprocessing_df(df):\n",
373
- " df = df[df.columns].copy()\n",
374
- " df['year'] = df['year'].astype('int')\n",
375
- " df['month'] = df['month'].astype('int')\n",
376
- " df['hour'] = df['hour'].astype('int')\n",
377
- " df['binary_class'] = df['binary_class'].astype('int')\n",
378
- " df['multi_class'] = df['multi_class'].astype('int')\n",
379
- "\n",
380
- " df.loc[df['wind_dir']=='정온', 'wind_dir'] = \"0\"\n",
381
- " df['wind_dir'] = df['wind_dir'].astype('int')\n",
382
- " df= df[['temp_C', 'precip_mm', 'wind_speed', 'wind_dir', 'hm',\n",
383
- " 'vap_pressure', 'dewpoint_C', 'loc_pressure', 'sea_pressure',\n",
384
- " 'solarRad', 'snow_cm', 'cloudcover', 'lm_cloudcover', 'low_cloudbase',\n",
385
- " 'groundtemp', 'O3', 'NO2', 'PM10', 'PM25', 'year',\n",
386
- " 'month', 'hour', 'ground_temp - temp_C', 'hour_sin', 'hour_cos',\n",
387
- " 'month_sin', 'month_cos','multi_class']]\n",
388
- " return df\n",
389
- "\n"
390
- ]
391
- },
392
- {
393
- "cell_type": "code",
394
- "execution_count": 7,
395
- "metadata": {},
396
- "outputs": [],
397
- "source": [
398
- "df_seoul_test= preprocessing_df(df_seoul_test).copy()\n",
399
- "df_busan_test= preprocessing_df(df_busan_test).copy()\n",
400
- "df_daegu_test= preprocessing_df(df_daegu_test).copy()\n",
401
- "df_gwangju_test= preprocessing_df(df_gwangju_test).copy()\n",
402
- "df_daejeon_test= preprocessing_df(df_daejeon_test).copy()\n",
403
- "df_incheon_test= preprocessing_df(df_incheon_test).copy()\n",
404
- "\n",
405
- "df_seoul= preprocessing_df(df_seoul).copy()\n",
406
- "df_busan= preprocessing_df(df_busan).copy()\n",
407
- "df_daegu= preprocessing_df(df_daegu).copy()\n",
408
- "df_gwangju= preprocessing_df(df_gwangju).copy()\n",
409
- "df_daejeon= preprocessing_df(df_daejeon).copy()\n",
410
- "df_incheon= preprocessing_df(df_incheon).copy()\n",
411
- "\n",
412
- "df_seoul_test.drop(columns=['year'], inplace=True)\n",
413
- "df_busan_test.drop(columns=['year'], inplace=True)\n",
414
- "df_daegu_test.drop(columns=['year'], inplace=True)\n",
415
- "df_daejeon_test.drop(columns=['year'], inplace=True)\n",
416
- "df_incheon_test.drop(columns=['year'], inplace=True)\n",
417
- "df_gwangju_test.drop(columns=['year'], inplace=True)"
418
- ]
419
- },
420
- {
421
- "cell_type": "code",
422
- "execution_count": 8,
423
- "metadata": {},
424
- "outputs": [],
425
- "source": [
426
- "import joblib\n",
427
- "\n",
428
- "lgb_seoul= joblib.load('../save_model/LGB_optima/lgb_seoul_smote.pkl')\n",
429
- "lgb_busan= joblib.load('../save_model/LGB_optima/lgb_busan_smote.pkl')\n",
430
- "lgb_incheon= joblib.load('../save_model/LGB_optima/lgb_incheon_smote.pkl')\n",
431
- "lgb_daegu= joblib.load('../save_model/LGB_optima/lgb_daegu_smote.pkl')\n",
432
- "lgb_daejeon= joblib.load('../save_model/LGB_optima/lgb_daejeon_smote.pkl')\n",
433
- "lgb_gwangju= joblib.load('../save_model/LGB_optima/lgb_gwangju_smote.pkl')\n",
434
- "\n",
435
- "xgb_seoul= joblib.load('../save_model/XGB_optima/xgb_seoul_smote.pkl')\n",
436
- "xgb_busan= joblib.load('../save_model/XGB_optima/xgb_busan_ctgan20000.pkl')\n",
437
- "xgb_incheon= joblib.load('../save_model/XGB_optima/xgb_incheon_smote.pkl')\n",
438
- "xgb_daegu= joblib.load('../save_model/XGB_optima/xgb_daegu_smote.pkl')\n",
439
- "xgb_daejeon= joblib.load('../save_model/XGB_optima/xgb_daejeon_smote.pkl')\n",
440
- "xgb_gwangju= joblib.load('../save_model/XGB_optima/xgb_gwangju_smote.pkl')\n",
441
- "\n",
442
- "lgb_seoul_1= lgb_seoul[0]\n",
443
- "lgb_seoul_2= lgb_seoul[1]\n",
444
- "lgb_seoul_3= lgb_seoul[2]\n",
445
- "\n",
446
- "lgb_busan_1= lgb_busan[0]\n",
447
- "lgb_busan_2= lgb_busan[1]\n",
448
- "lgb_busan_3= lgb_busan[2]\n",
449
- "\n",
450
- "lgb_incheon_1= lgb_incheon[0]\n",
451
- "lgb_incheon_2= lgb_incheon[1]\n",
452
- "lgb_incheon_3= lgb_incheon[2]\n",
453
- "\n",
454
- "lgb_daegu_1= lgb_daegu[0]\n",
455
- "lgb_daegu_2= lgb_daegu[1]\n",
456
- "lgb_daegu_3= lgb_daegu[2]\n",
457
- "\n",
458
- "lgb_daejeon_1= lgb_daejeon[0]\n",
459
- "lgb_daejeon_2= lgb_daejeon[1]\n",
460
- "lgb_daejeon_3= lgb_daejeon[2]\n",
461
- "\n",
462
- "lgb_gwangju_1= lgb_gwangju[0]\n",
463
- "lgb_gwangju_2= lgb_gwangju[1]\n",
464
- "lgb_gwangju_3= lgb_gwangju[2]\n",
465
- "\n",
466
- "\n",
467
- "xgb_seoul_1= xgb_seoul[0]\n",
468
- "xgb_seoul_2= xgb_seoul[1]\n",
469
- "xgb_seoul_3= xgb_seoul[2]\n",
470
- "\n",
471
- "xgb_busan_1= xgb_busan[0]\n",
472
- "xgb_busan_2= xgb_busan[1]\n",
473
- "xgb_busan_3= xgb_busan[2]\n",
474
- "\n",
475
- "xgb_incheon_1= xgb_incheon[0]\n",
476
- "xgb_incheon_2= xgb_incheon[1]\n",
477
- "xgb_incheon_3= xgb_incheon[2]\n",
478
- "\n",
479
- "xgb_daegu_1= xgb_daegu[0]\n",
480
- "xgb_daegu_2= xgb_daegu[1]\n",
481
- "xgb_daegu_3= xgb_daegu[2]\n",
482
- "\n",
483
- "xgb_daejeon_1= xgb_daejeon[0]\n",
484
- "xgb_daejeon_2= xgb_daejeon[1]\n",
485
- "xgb_daejeon_3= xgb_daejeon[2]\n",
486
- "\n",
487
- "xgb_gwangju_1= xgb_gwangju[0]\n",
488
- "xgb_gwangju_2= xgb_gwangju[1]\n",
489
- "xgb_gwangju_3= xgb_gwangju[2]\n"
490
- ]
491
- },
492
- {
493
- "cell_type": "markdown",
494
- "metadata": {},
495
- "source": [
496
- "## **Soft Voting**"
497
- ]
498
- },
499
- {
500
- "cell_type": "markdown",
501
- "metadata": {},
502
- "source": [
503
- "## **서울**"
504
- ]
505
- },
506
- {
507
- "cell_type": "code",
508
- "execution_count": 9,
509
- "metadata": {},
510
- "outputs": [],
511
- "source": [
512
- "voting = []\n",
513
- "mcc = []\n",
514
- "accuracy = []\n"
515
- ]
516
- },
517
- {
518
- "cell_type": "code",
519
- "execution_count": 10,
520
- "metadata": {},
521
- "outputs": [
522
- {
523
- "data": {
524
- "text/plain": [
525
- "Index(['temp_C', 'precip_mm', 'wind_speed', 'wind_dir', 'hm', 'vap_pressure',\n",
526
- " 'dewpoint_C', 'loc_pressure', 'sea_pressure', 'solarRad', 'snow_cm',\n",
527
- " 'cloudcover', 'lm_cloudcover', 'low_cloudbase', 'groundtemp', 'O3',\n",
528
- " 'NO2', 'PM10', 'PM25', 'month', 'hour', 'ground_temp - temp_C',\n",
529
- " 'hour_sin', 'hour_cos', 'month_sin', 'month_cos', 'multi_class'],\n",
530
- " dtype='object')"
531
- ]
532
- },
533
- "execution_count": 10,
534
- "metadata": {},
535
- "output_type": "execute_result"
536
- }
537
- ],
538
- "source": [
539
- "df_seoul_test.columns"
540
- ]
541
- },
542
- {
543
- "cell_type": "code",
544
- "execution_count": 11,
545
- "metadata": {},
546
- "outputs": [
547
- {
548
- "name": "stdout",
549
- "output_type": "stream",
550
- "text": [
551
- "CSI score of soft(test) : 0.3248062015503624\n"
552
- ]
553
- }
554
- ],
555
- "source": [
556
- "from scipy.stats import mode # 최다 득표수 계산을 위한 mode 함수\n",
557
- "\n",
558
- "probas = []\n",
559
- "\n",
560
- "# 1 Fold\n",
561
- "test_preds = get_proba('seoul', 'deepgbm', 'ctgan20000', 1)\n",
562
- "probas.append(test_preds)\n",
563
- "test_preds = get_proba('seoul', 'resnet_like', 'smote', 1)\n",
564
- "probas.append(test_preds)\n",
565
- "# probas.append(xgb_seoul_1.predict_proba(df_seoul_test.iloc[:,:-1]))\n",
566
- "\n",
567
- "# 2 Fold\n",
568
- "test_preds = get_proba('seoul', 'deepgbm', 'ctgan20000', 2)\n",
569
- "probas.append(test_preds)\n",
570
- "test_preds = get_proba('seoul', 'resnet_like', 'smote', 2)\n",
571
- "probas.append(test_preds)\n",
572
- "# probas.append(xgb_seoul_2.predict_proba(df_seoul_test.iloc[:,:-1]))\n",
573
- "\n",
574
- "# 3 Fold\n",
575
- "test_preds = get_proba('seoul', 'deepgbm', 'ctgan20000', 3)\n",
576
- "probas.append(test_preds)\n",
577
- "test_preds = get_proba('seoul', 'resnet_like', 'smote', 3)\n",
578
- "probas.append(test_preds)\n",
579
- "# probas.append(xgb_seoul_3.predict_proba(df_seoul_test.iloc[:,:-1]))\n",
580
- "\n",
581
- "voting.append(calculate_csi(df_seoul_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n",
582
- "mcc.append(multiclass_mcc(df_seoul_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n",
583
- "accuracy.append(accuracy_score(df_seoul_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n",
584
- "\n",
585
- "\n",
586
- "print(\"CSI score of soft(test) :\", calculate_csi(df_seoul_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n"
587
- ]
588
- },
589
- {
590
- "cell_type": "code",
591
- "execution_count": 12,
592
- "metadata": {},
593
- "outputs": [
594
- {
595
- "data": {
596
- "text/plain": [
597
- "array([[ 2, 11, 0],\n",
598
- " [ 6, 417, 58],\n",
599
- " [ 7, 789, 7470]])"
600
- ]
601
- },
602
- "execution_count": 12,
603
- "metadata": {},
604
- "output_type": "execute_result"
605
- }
606
- ],
607
- "source": [
608
- "confusion_matrix(df_seoul_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1))"
609
- ]
610
- },
611
- {
612
- "cell_type": "markdown",
613
- "metadata": {},
614
- "source": [
615
- "## **부산**"
616
- ]
617
- },
618
- {
619
- "cell_type": "code",
620
- "execution_count": 13,
621
- "metadata": {},
622
- "outputs": [
623
- {
624
- "name": "stdout",
625
- "output_type": "stream",
626
- "text": [
627
- "CSI score of soft(test) : 0.46608315098458075\n"
628
- ]
629
- }
630
- ],
631
- "source": [
632
- "from scipy.stats import mode # 최다 득표수 계산을 위한 mode 함수\n",
633
- "\n",
634
- "probas = []\n",
635
- "\n",
636
- "# 1 Fold\n",
637
- "test_preds = get_proba('busan', 'deepgbm', 'pure', 1)\n",
638
- "probas.append(test_preds)\n",
639
- "test_preds = get_proba('busan', 'resnet_like', 'ctgan10000', 1)\n",
640
- "probas.append(test_preds)\n",
641
- "\n",
642
- "\n",
643
- "# 2 Fold\n",
644
- "test_preds = get_proba('busan', 'deepgbm', 'pure', 2)\n",
645
- "probas.append(test_preds)\n",
646
- "test_preds = get_proba('busan', 'resnet_like', 'ctgan10000', 2)\n",
647
- "probas.append(test_preds)\n",
648
- "\n",
649
- "\n",
650
- "# 3 Fold\n",
651
- "test_preds = get_proba('busan', 'deepgbm', 'pure', 3)\n",
652
- "probas.append(test_preds)\n",
653
- "test_preds = get_proba('busan', 'resnet_like', 'ctgan10000', 3)\n",
654
- "probas.append(test_preds)\n",
655
- "\n",
656
- "\n",
657
- "voting.append(calculate_csi(df_busan_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n",
658
- "mcc.append(multiclass_mcc(df_busan_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n",
659
- "accuracy.append(accuracy_score(df_busan_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n",
660
- "\n",
661
- "print(\"CSI score of soft(test) :\", calculate_csi(df_busan_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n"
662
- ]
663
- },
664
- {
665
- "cell_type": "code",
666
- "execution_count": 14,
667
- "metadata": {},
668
- "outputs": [
669
- {
670
- "data": {
671
- "text/plain": [
672
- "array([[ 11, 13, 0],\n",
673
- " [ 11, 202, 68],\n",
674
- " [ 2, 150, 8303]])"
675
- ]
676
- },
677
- "execution_count": 14,
678
- "metadata": {},
679
- "output_type": "execute_result"
680
- }
681
- ],
682
- "source": [
683
- "confusion_matrix(df_busan_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1))"
684
- ]
685
- },
686
- {
687
- "cell_type": "markdown",
688
- "metadata": {},
689
- "source": [
690
- "## **인천**"
691
- ]
692
- },
693
- {
694
- "cell_type": "code",
695
- "execution_count": 15,
696
- "metadata": {},
697
- "outputs": [
698
- {
699
- "name": "stdout",
700
- "output_type": "stream",
701
- "text": [
702
- "CSI score of hard(test) : 0.572269457161506\n"
703
- ]
704
- }
705
- ],
706
- "source": [
707
- "from scipy.stats import mode # 최다 득표수 계산을 위한 mode 함수\n",
708
- "\n",
709
- "\n",
710
- "# 1 Fold\n",
711
- "probas = []\n",
712
- "test_preds = get_proba('incheon', 'deepgbm', 'pure', 1)\n",
713
- "probas.append(test_preds)\n",
714
- "test_preds = get_proba('incheon', 'resnet_like', 'smote', 1)\n",
715
- "probas.append(test_preds)\n",
716
- "test_preds = get_proba('incheon', 'ft_transformer', 'pure', 1)\n",
717
- "probas.append(test_preds)\n",
718
- "\n",
719
- "probas.append(lgb_incheon_1.predict_proba(df_incheon_test.iloc[:,:-1]))\n",
720
- "probas.append(xgb_incheon_1.predict_proba(df_incheon_test.iloc[:,:-1]))\n",
721
- "\n",
722
- "# 2 Fold\n",
723
- "test_preds = get_proba('incheon', 'deepgbm', 'pure', 2)\n",
724
- "probas.append(test_preds)\n",
725
- "test_preds = get_proba('incheon', 'resnet_like', 'smote', 2)\n",
726
- "probas.append(test_preds)\n",
727
- "test_preds = get_proba('incheon', 'ft_transformer', 'pure', 2)\n",
728
- "probas.append(test_preds)\n",
729
- "\n",
730
- "probas.append(lgb_incheon_2.predict_proba(df_incheon_test.iloc[:,:-1]))\n",
731
- "probas.append(xgb_incheon_2.predict_proba(df_incheon_test.iloc[:,:-1]))\n",
732
- "\n",
733
- "# 3 Fold\n",
734
- "test_preds = get_proba('incheon', 'deepgbm', 'pure', 3)\n",
735
- "probas.append(test_preds)\n",
736
- "test_preds = get_proba('incheon', 'resnet_like', 'smote', 3)\n",
737
- "probas.append(test_preds)\n",
738
- "test_preds = get_proba('incheon', 'ft_transformer', 'pure', 3)\n",
739
- "probas.append(test_preds)\n",
740
- "\n",
741
- "probas.append(lgb_incheon_3.predict_proba(df_incheon_test.iloc[:,:-1]))\n",
742
- "probas.append(xgb_incheon_3.predict_proba(df_incheon_test.iloc[:,:-1]))\n",
743
- "\n",
744
- "\n",
745
- "\n",
746
- "voting.append(calculate_csi(df_incheon_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n",
747
- "mcc.append(multiclass_mcc(df_incheon_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n",
748
- "accuracy.append(accuracy_score(df_incheon_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n",
749
- "\n",
750
- "\n",
751
- "print(\"CSI score of hard(test) :\", calculate_csi(df_incheon_test.iloc[:,-1],mode(np.argmax(probas, axis=2), axis=0).mode[0]))\n"
752
- ]
753
- },
754
- {
755
- "cell_type": "code",
756
- "execution_count": 16,
757
- "metadata": {},
758
- "outputs": [
759
- {
760
- "data": {
761
- "text/plain": [
762
- "array([[ 87, 74, 21],\n",
763
- " [ 22, 788, 395],\n",
764
- " [ 2, 140, 7231]])"
765
- ]
766
- },
767
- "execution_count": 16,
768
- "metadata": {},
769
- "output_type": "execute_result"
770
- }
771
- ],
772
- "source": [
773
- "confusion_matrix(df_incheon_test.iloc[:,-1],mode(np.argmax(probas, axis=2), axis=0).mode[0])"
774
- ]
775
- },
776
- {
777
- "cell_type": "markdown",
778
- "metadata": {},
779
- "source": [
780
- "## **대구**"
781
- ]
782
- },
783
- {
784
- "cell_type": "code",
785
- "execution_count": 17,
786
- "metadata": {},
787
- "outputs": [
788
- {
789
- "name": "stdout",
790
- "output_type": "stream",
791
- "text": [
792
- "CSI score of soft(test) : 0.2852112676055334\n"
793
- ]
794
- }
795
- ],
796
- "source": [
797
- "from scipy.stats import mode # 최다 득표수 계산을 위한 mode 함수\n",
798
- "\n",
799
- "probas= []\n",
800
- "\n",
801
- "# 1 Fold\n",
802
- "test_preds = get_proba('daegu', 'deepgbm', 'smote', 1)\n",
803
- "probas.append(test_preds)\n",
804
- "test_preds = get_proba('daegu', 'ft_transformer', 'pure', 1)\n",
805
- "probas.append(test_preds)\n",
806
- "\n",
807
- "# 2 Fold\n",
808
- "test_preds = get_proba('daegu', 'deepgbm', 'smote', 2)\n",
809
- "probas.append(test_preds)\n",
810
- "test_preds = get_proba('daegu', 'ft_transformer', 'pure', 2)\n",
811
- "probas.append(test_preds)\n",
812
- "\n",
813
- "# 3 Fold\n",
814
- "test_preds = get_proba('daegu', 'deepgbm', 'smote', 3)\n",
815
- "probas.append(test_preds)\n",
816
- "test_preds = get_proba('daegu', 'ft_transformer', 'pure', 3)\n",
817
- "probas.append(test_preds)\n",
818
- "\n",
819
- "voting.append(calculate_csi(df_daegu_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n",
820
- "mcc.append(multiclass_mcc(df_daegu_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n",
821
- "accuracy.append(accuracy_score(df_daegu_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n",
822
- "\n",
823
- "print(\"CSI score of soft(test) :\", calculate_csi(df_daegu_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n"
824
- ]
825
- },
826
- {
827
- "cell_type": "code",
828
- "execution_count": 18,
829
- "metadata": {},
830
- "outputs": [
831
- {
832
- "data": {
833
- "text/plain": [
834
- "array([[ 1, 0, 0],\n",
835
- " [ 1, 80, 47],\n",
836
- " [ 2, 153, 8476]])"
837
- ]
838
- },
839
- "execution_count": 18,
840
- "metadata": {},
841
- "output_type": "execute_result"
842
- }
843
- ],
844
- "source": [
845
- "confusion_matrix(df_daegu_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1))"
846
- ]
847
- },
848
- {
849
- "cell_type": "markdown",
850
- "metadata": {},
851
- "source": [
852
- "## **대전**"
853
- ]
854
- },
855
- {
856
- "cell_type": "code",
857
- "execution_count": 19,
858
- "metadata": {},
859
- "outputs": [
860
- {
861
- "name": "stdout",
862
- "output_type": "stream",
863
- "text": [
864
- "CSI score of soft(test) : 0.31884057971011603\n"
865
- ]
866
- }
867
- ],
868
- "source": [
869
- "from scipy.stats import mode # 최다 득표수 계산을 위한 mode 함수\n",
870
- "\n",
871
- "probas = []\n",
872
- "\n",
873
- "# 1 Fold\n",
874
- "test_preds = get_proba('daejeon', 'deepgbm', 'pure', 1)\n",
875
- "probas.append(test_preds)\n",
876
- "test_preds = get_proba('daejeon', 'ft_transformer', 'pure', 1)\n",
877
- "probas.append(test_preds)\n",
878
- "\n",
879
- "\n",
880
- "# 2 Fold\n",
881
- "test_preds = get_proba('daejeon', 'deepgbm', 'pure', 2)\n",
882
- "probas.append(test_preds)\n",
883
- "test_preds = get_proba('daejeon', 'ft_transformer', 'pure', 2)\n",
884
- "probas.append(test_preds)\n",
885
- "\n",
886
- "\n",
887
- "# 3 Fold\n",
888
- "test_preds = get_proba('daejeon', 'deepgbm', 'pure', 3)\n",
889
- "probas.append(test_preds)\n",
890
- "test_preds = get_proba('daejeon', 'ft_transformer', 'pure', 3)\n",
891
- "probas.append(test_preds)\n",
892
- "\n",
893
- "voting.append(calculate_csi(df_daejeon_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n",
894
- "mcc.append(multiclass_mcc(df_daejeon_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n",
895
- "accuracy.append(accuracy_score(df_daejeon_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n",
896
- "\n",
897
- "\n",
898
- "print(\"CSI score of soft(test) :\", calculate_csi(df_daejeon_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))"
899
- ]
900
- },
901
- {
902
- "cell_type": "code",
903
- "execution_count": 20,
904
- "metadata": {},
905
- "outputs": [
906
- {
907
- "data": {
908
- "text/plain": [
909
- "array([[ 15, 23, 15],\n",
910
- " [ 10, 337, 271],\n",
911
- " [ 0, 433, 7656]])"
912
- ]
913
- },
914
- "execution_count": 20,
915
- "metadata": {},
916
- "output_type": "execute_result"
917
- }
918
- ],
919
- "source": [
920
- "confusion_matrix(df_daejeon_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1))"
921
- ]
922
- },
923
- {
924
- "cell_type": "markdown",
925
- "metadata": {},
926
- "source": [
927
- "## **광주**"
928
- ]
929
- },
930
- {
931
- "cell_type": "code",
932
- "execution_count": 21,
933
- "metadata": {},
934
- "outputs": [
935
- {
936
- "name": "stdout",
937
- "output_type": "stream",
938
- "text": [
939
- "CSI score of soft(test) : 0.4759725400457121\n"
940
- ]
941
- }
942
- ],
943
- "source": [
944
- "from scipy.stats import mode # 최다 득표수 계산을 위한 mode 함수\n",
945
- "\n",
946
- "probas = []\n",
947
- "\n",
948
- "# 1 Fold\n",
949
- "test_preds = get_proba('gwangju', 'deepgbm', 'pure', 1)\n",
950
- "probas.append(test_preds)\n",
951
- "test_preds = get_proba('gwangju', 'ft_transformer', 'pure', 1)\n",
952
- "probas.append(test_preds)\n",
953
- "\n",
954
- "\n",
955
- "# 2 Fold\n",
956
- "test_preds = get_proba('gwangju', 'deepgbm', 'pure', 2)\n",
957
- "probas.append(test_preds)\n",
958
- "test_preds = get_proba('gwangju', 'ft_transformer', 'pure', 2)\n",
959
- "probas.append(test_preds)\n",
960
- "\n",
961
- "\n",
962
- "# 3 Fold\n",
963
- "test_preds = get_proba('gwangju', 'deepgbm', 'pure', 3)\n",
964
- "probas.append(test_preds)\n",
965
- "test_preds = get_proba('gwangju', 'ft_transformer', 'pure', 3)\n",
966
- "probas.append(test_preds)\n",
967
- "\n",
968
- "voting.append(calculate_csi(df_gwangju_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n",
969
- "mcc.append(multiclass_mcc(df_gwangju_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n",
970
- "accuracy.append(accuracy_score(df_gwangju_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))\n",
971
- "\n",
972
- "\n",
973
- "print(\"CSI score of soft(test) :\", calculate_csi(df_gwangju_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1)))"
974
- ]
975
- },
976
- {
977
- "cell_type": "code",
978
- "execution_count": 22,
979
- "metadata": {},
980
- "outputs": [
981
- {
982
- "data": {
983
- "text/plain": [
984
- "array([[ 10, 12, 8],\n",
985
- " [ 2, 406, 235],\n",
986
- " [ 0, 201, 7886]])"
987
- ]
988
- },
989
- "execution_count": 22,
990
- "metadata": {},
991
- "output_type": "execute_result"
992
- }
993
- ],
994
- "source": [
995
- "confusion_matrix(df_gwangju_test.iloc[:,-1], np.argmax(np.mean(probas, axis=0), axis=1))"
996
- ]
997
- },
998
- {
999
- "cell_type": "code",
1000
- "execution_count": 23,
1001
- "metadata": {},
1002
- "outputs": [
1003
- {
1004
- "data": {
1005
- "image/png": "iVBORw0KGgoAAAANSUhEUgAAA04AAAHDCAYAAAATEUquAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuNSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/xnp5ZAAAACXBIWXMAAA9hAAAPYQGoP6dpAABDfUlEQVR4nO3deVwVdf///+cBZBfEDcgQUtw33EMvxQpDLcsrKysL5GvqpWJeF5VFlmiLWJbppaZZH9PcMs1WU0vUSrM0FZdCxd00cClFUKHg/fujH+fqCDhiynF53G+3c6t5z3tmXnPOeM55MjPvYzPGGAEAAAAASuXi7AIAAAAA4EpHcAIAAAAACwQnAAAAALBAcAIAAAAACwQnAAAAALBAcAIAAAAACwQnAAAAALBAcAIAAAAACwQnAAAAALBAcAIAXFPWr1+vdu3aycfHRzabTWlpac4uSSNHjpTNZnN2GeVq1apVstlsWrVqVZmXnTFjhmw2m/bt23fJ6wKAi0VwAoDLaPfu3RowYIBq1aolT09P+fn5qX379powYYLOnDlj75efn68JEyaoefPm8vPzU6VKldSoUSP1799f27dvt/cr+kL5ww8/WG573759io+PV+3ateXp6amgoCB17NhRycnJl2VfrwS///677rvvPv366696/fXXNWvWLIWGhhbr99hjj8lms2nXrl2lrmv48OGy2WzasmXLBW379OnTGjly5EUFhcupT58+stls8vPzczjmimRkZMhms8lms+nVV191QoUAcHUgOAHAZbJ48WI1adJE77//vrp3766JEycqJSVFNWvW1JNPPqmhQ4fa+/bs2VOPP/64GjdurDFjxmjUqFHq2LGjlixZou+++67M2961a5eaN2+uZcuW6cEHH9SkSZM0ePBgValSRS+//PKl3M0ryu7du7V//3498cQT6t+/vx5++GEFBAQU69e7d29J0ty5c0td17x589SkSRM1bdr0grZ9+vRpjRo1qsTg9Oyzz5YYWsqLm5ubTp8+rU8//bTYvDlz5sjT09MJVQHA1cXN2QUAwLVo7969euCBBxQaGqoVK1YoODjYPm/w4MHatWuXFi9eLOnPS8s+++wzvfTSS3rmmWcc1jNp0iSdOHGizNt//fXXlZOTo7S0tGJnXI4cOVL2HfobcnNz5ePjUy7bKtq3SpUqnbdf27ZtFR4ernnz5mnEiBHF5q9du1Z79+7VmDFjLkldbm5ucnNz3keuh4eH2rdvr3nz5un+++93mDd37lzdcccd+uCDD5xUHQBcHTjjBACXwSuvvKKcnBz93//9n0NoKhIeHm4/47R7925JUvv27Yv1c3V1VZUqVcq8/d27d+vGG28s8TK16tWrF2tbsmSJoqKiVLFiRfn5+al169bFzsYsWLBALVu2lJeXl6pWraqHH35Yhw4dcujTp08f+fr6avfu3erWrZsqVqxoP7tTWFio8ePHq1GjRvL09FRgYKAGDBig33777YL2acWKFerQoYN8fHxUqVIl3X333UpPT3fYdlRUlCTpvvvuk81mU6dOnUpdX+/evbV9+3Zt3Lix2Ly5c+fKZrPpwQcflPRnIOvbt68CAwPl6empZs2aaebMmfb++/btU7Vq1SRJo0aNsl/6NnLkSEkl3+Nks9mUkJCgjz76SI0bN5aHh4caNWqkpUuXFqtn1apVatWqlTw9PVW7dm29+eabZb5v6qGHHtKSJUscgvj69euVkZGhhx56qMRl9uzZo/vuu0+VK1eWt7e3br75Znvg/6uff/5ZPXr0kI+Pj6pXr67//Oc/ysvLK3Gd33//vbp06SJ/f395e3srKipKa9asueD9AABnITgBwGXw6aefqlatWmrXrp1l36JwM2fOHP3xxx+XZPuhoaE6ePCgVqxYYdl3xowZuuOOO/Trr78qKSlJY8aMUUREhMMX+BkzZuj++++Xq6urUlJS1K9fPy1atEj/+Mc/ip0R++OPPxQTE6Pq1avr1VdfVc+ePSVJAwYM0JNPPmm/xys+Pl5z5sxRTEyMfv/99/PWuHz5csXExOjIkSMaOXKkEhMT9e2336p9+/b2AQQGDBhgP2P32GOPadasWRo+fHip6yztcr2CggK9//776tChg2rWrKkzZ86oU6dOmjVrlnr37q2xY8fK399fffr00YQJEyRJ1apV05QpUyRJ//znPzVr1izNmjVL99xzz3n3a/Xq1Ro0aJAeeOABvfLKKzp79qx69uyp48eP2/ts2rRJXbp00fHjxzVq1Cj17dtXzz//vD766KPzrvtc99xzj2w2mxYtWmRvmzt3rurXr68WLVoU65+VlaV27dpp2bJlGjRokF566SWdPXtWd911lz788EN7vzNnzui2227TsmXLlJCQoOHDh+ubb77RsGHDiq1zxYoV6tixo7Kzs5WcnKzRo0frxIkTuvXWW7Vu3boy7Q8AlDsDALikTp48aSSZu++++4L6FxYWmqioKCPJBAYGmgcffNBMnjzZ7N+/v1jfd955x0gy69evP+86t23bZry8vIwkExERYYYOHWo++ugjk5ub69DvxIkTpmLFiqZt27bmzJkzxeoyxpj8/HxTvXp107hxY4c+n332mZFkRowYYW+Li4szkszTTz/tsK5vvvnGSDJz5sxxaF+6dGmJ7eeKiIgw1atXN8ePH7e3bd682bi4uJjY2Fh728qVK40ks2DBgvOur0jr1q3NjTfeaAoKCorV9OabbxpjjBk/fryRZGbPnm3vk5+fbyIjI42vr6/Jzs42xhhz9OhRI8kkJycX205ycrI59yNXknF3dze7du1y2CdJZuLEifa27t27G29vb3Po0CF7W0ZGhnFzcyu2zpLExcUZHx8fY4wx9957r7ntttuMMcYUFBSYoKAgM2rUKLN3714jyYwdO9a+3L///W8jyXzzzTf2tlOnTpmbbrrJhIWF2Z+zoufn/ffft/fLzc014eHhRpJZuXKlMebP46lOnTomJibGfmwZY8zp06fNTTfdZDp37mx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Dw0D333KOZM2dqz5499sErykPR2aSxY8cqIiKixD6+vr7lVg8AlBXBCQAugzvvvFPTpk3T2rVrFRkZeVHrqFChgpo2baqMjAwdO3ZMQUFBf7uuVq1aSfrz8jdJ9svEtm3bVuqZh6LBK3bs2KFbb73VYd6OHTtKHLnvXLVr19by5cvVvn17eXl5lanmv27/XNu3b1fVqlX/1nDnvXv31tKlS7VkyRLNnTtXfn5+6t69u8P2t2zZosLCQodAWPTDxEX1lWWEuwtVvXp1eXp6lvhDvef78d7zeeihhzR9+nS5uLjogQceKLVfaGhoqc950fyi/27btk3GGIfn4Nxli441Pz+/yxbaAeBy4lI9ALgMhg0bJh8fHz366KPKysoqNn/37t32EdkyMjJ04MCBYn1OnDihtWvXKiAgoMxnZL755psSR6oruh+o6DKq22+/XRUrVlRKSorOnj3r0LforEerVq1UvXp1TZ061WGI6SVLlig9PV133HGHZT3333+/CgoK9MILLxSb98cff5z3Pq7g4GBFRERo5syZDv22bdumL774Qt26dbPc/vn06NFD3t7eeuONN7RkyRLdc889DvdydevWTZmZmZo/f75DzRMnTpSvr699CHRvb29Juqh70krj6uqq6OhoffTRRzp8+LC9fdeuXVqyZMlFrfOWW27RCy+8oEmTJp03jHfr1k3r1q3T2rVr7W25ubmaNm2awsLC1LBhQ3u/w4cPa+HChfZ+p0+f1rRp0xzW17JlS9WuXVuvvvqqcnJyim3v6NGjF7U/AFBeOOMEAJdB7dq1NXfuXPXq1UsNGjRQbGysGjdurPz8fH377bdasGCB+vTpI0navHmzHnroIXXt2lUdOnRQ5cqVdejQIc2cOVOHDx/W+PHjS72kqzQvv/yyNmzYoHvuuUdNmzaVJG3cuFHvvvuuKleurH//+9+S/vzr/+uvv65HH31UrVu31kMPPaSAgABt3rxZp0+f1syZM1WhQgW9/PLLio+PV1RUlB588EFlZWVpwoQJCgsL03/+8x/LeqKiojRgwAClpKQoLS1Nt99+uypUqKCMjAwtWLBAEyZMcBhc4Fxjx45V165dFRkZqb59++rMmTOaOHGi/P39//bl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ePlqmAXr166ejRoxoxYoQyMzMVERGhpUuX2geMOHDggFxc/pfvcnNzNWjQIP3888/y8vJS/fr1NXv2bPXq1atM2wUAAACAC1Wm4FSjRg1t27bNfn/RubZs2aLg4OAyF5GQkKCEhIQS561atcph+sUXX9SLL75Y5m0AAAAAwMUq06V63bp103PPPaezZ88Wm3fmzBklJyfrzjvvvGTFAQAAAMCVoExnnJ599lktWrRIdevWVUJCgurVqydJ2r59uyZPnqyCggINHz78shQKAAAAAM5SpuAUGBiob7/9VgMHDlRSUpKMMZIkm82mmJgYTZ48udiP2QIAAADA1a5MwUmSQkND9fnnn+u3337Trl27ZIxRnTp1FBAQcDnqAwDgivJVxyhnl4BSRH39lbNLAHANK3NwKhIQEKDWrVtfyloAAAAA4IpUpsEhAAAAAOB6RHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAsEJwAAAACwQHACAAAAAAtXRHCaPHmywsLC5OnpqbZt22rdunWl9n3rrbfUoUMHBQQEKCAgQNHR0eftDwAAAAB/l9OD0/z585WYmKjk5GRt3LhRzZo1U0xMjI4cOVJi/1WrVunBBx/UypUrtXbtWoWEhOj222/XoUOHyrlyAAAAANcLpwencePGqV+/foqPj1fDhg01depUeXt7a/r06SX2nzNnjgYNGqSIiAjVr19fb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jQoEEOr5UkrV69Wh06dJCXl5dCQkL02GOPKTc31z7/l19+0R133CEvLy/ddNNNmjt3rsLCwjR+/HhJfE6Uh/J6rc+9VC8vL09PPPGEatSoIR8fH7Vt27bYa/rBBx+oUaNG8vDwUFhYmF577TWH+WFhYRo9erT+3//7f6pYsaJq1qypadOmXdLn51o2aNAgubm56YcfftD999+vBg0aqFatWrr77ru1ePFide/eXU888YTDH07Hjx8vm82mpUuX2tvCw8P19ttvS5LWr1+vzp07q2rVqvL391dUVJQ2btzosF2bzaa3335b//znP+Xt7a06derok08+cejzySefqE6dOvL09NQtt9yimTNnOnz3OPe7yMiRIxUREeGwjvHjxyssLOzSPFnljOB0lfH19ZWvr68++ugj5eXlldjnvvvu05EjR7RkyRJt2LBBLVq00G233aZff/1VkvThhx9q6NChevzxx7Vt2zYNGDBA8fHxWrlyZXnuCv6mnJwczZ49W+Hh4apSpcoFLTN48GDl5eXp66+/1tatW/Xyyy/L19dXklRYWKgbb7xRCxYs0E8//aQRI0bomWee0fvvv++wjpUrV2r37t1auXKlZs6cqRkzZtg/xHF5zJw5Uz4+Pvr+++/1yiuv6Pnnn9eXX34p6c/XrWvXrlqzZo1mz56tn376SWPGjJGrq6t9+dOnT+vVV1/VrFmz9PXXX+vAgQN64okn7PPnzJmjESNG6KWXXlJ6erpGjx6t5557TjNnzpQk5ebmKiYmRgEBAVq/fr0WLFig5cuXKyEhwaFOjg3nuPXWW9WsWTMtWrRIkuTi4qL//ve/+vHHHzVz5kytWLFCw4YNs/ffvXu3unTpop49e2rLli2aP3++Vq9e7fB6xsbG6vDhw1q1apU++OADTZs2TUeOHCn3fYOjy/FanyshIUFr167Ve++9py1btui+++5Tly5dlJGRIUnasGGD7r//fj3wwAPaunWrRo4cqeeee67Yv/XXXntNrVq10qZNmzRo0CANHDhQO3bsuPRPyjXm+PHj+uKLLzR48GD5+PiU2MdmsykqKkqrV69WQUGBJOmrr75S1apV7SH30KFD2r17tzp16iRJOnXqlOLi4rR69Wp99913q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Whh/f3/j7e1t6tWrZ5599llz+vRpY4wx2dnZZsiQIeaGG24wFSpUMCEhIaZ3797mwIED9vW88cYbplatWqZChQqmbt265t1333XYzk8//WQiIyONl5eXiYiIMF988QWDQzhZXFyckWR/VKxY0bRu3dosXLjQ3mf16tWmSZMmxtPT03To0MEsWLDAYXCIhIQEU7t2bePh4WGqVatmHnnkEXPs2DFjzJ/HVp8+fYy/v7+pVKmSGThwoHn66acdbuos6YbloUOHmqioqMu899eXcweHKLpxu8jdd99t4uLi7NPHjx838fHxpkqVKsbT09M0btzYfPbZZ8aYPweH8Pf3d1j+ww8/NOe+/c+ZM8dEREQYd3d3ExAQYDp27Ohwc/KWLVvMLbfcYjw9PU3lypVNv379zKlTp0qsuQjHxqX11/cANzc3U61aNRMdHW2mT59uCgoK7P3GjRtngoODjZeXl4mJiTHvvvtusffrdevWmc6dOxtfX1/j4+NjmjZtal566SX7/MOHD5uuXbsaDw8PExoaaubOnWuqV69upk6dau9j9TmBi1eer/W57zH5+flmxIgRJiwszFSoUMEEBwebf/7zn2bLli32PgsXLjQNGzY0FSpUMDVr1jRjx451qD80NNQ+kEiRZs2ameTk5Evy/FwPDh8+bBISEsxNN91kKlSoYHx9fU2bNm3M2LFjTW5urr1fs2bNTFBQkH36+PHjxmazmQceeMBhfRs3bjStWrUynp6epk6dOmbBggXFXidJ5sMPP3RYzt/f37zzzjv26Y8//tiEh4cbDw8P06lTJzNlyhQjyT7YSEnfD6dMmWJCQkKMj4+PiY2NNS+99NJVOziEzZhzLjwEAAD4i59//lkhISH2wQhw7YiMjNRtt92mF1980dml4Cr00ksvaerUqTp48KCkP38zsGvXrjp79qzc3d2dXN2lxz1OAADAwYoVK5STk6MmTZrol19+0bBhwxQWFqaOHTs6uzRcInl5edq6dat+/PHHEgePAEryxhtvqHXr1qpSpYrWrFmjsWPH2i/9zMrK0scff6w6depck6FJIjgBAIBz/P7773rmmWe0Z88eVaxYUe3atdOcOXOKjbiFq9eSJUsUGxuru+66S/fee6+zy8FVIiMjQy+++KJ+/fVX1axZU48//riSkpIkyf6Dum+88YaTq7x8uFQPAAAAACwwqh4AAAAAWCA4AQAAAIAFghMAAAAAWCA4AQAAAIAFghMAAAAAWCA4AQAAAIAFghMAAAAAWCA4AQAAAIAFghMAAAAAWPj/AJ3jGjFFTxgpAAAAAElFTkSuQmCC",
1006
- "text/plain": [
1007
- "<Figure size 1000x500 with 1 Axes>"
1008
- ]
1009
- },
1010
- "metadata": {},
1011
- "output_type": "display_data"
1012
- }
1013
- ],
1014
- "source": [
1015
- "import matplotlib.pyplot as plt\n",
1016
- "import seaborn as sns\n",
1017
- "\n",
1018
- "plt.figure(figsize=(10,5))\n",
1019
- "sns.barplot(x=['Seoul', 'Busan', 'Incheon', 'Daegu', 'Daejeon', 'Gwangju'], y=voting)\n",
1020
- "plt.title('CSI Score of Voting Model')\n",
1021
- "plt.ylabel('CSI')\n",
1022
- "\n",
1023
- "plt.show()"
1024
- ]
1025
- },
1026
- {
1027
- "cell_type": "code",
1028
- "execution_count": 24,
1029
- "metadata": {},
1030
- "outputs": [
1031
- {
1032
- "data": {
1033
- "text/plain": [
1034
- "0.4078715882283252"
1035
- ]
1036
- },
1037
- "execution_count": 24,
1038
- "metadata": {},
1039
- "output_type": "execute_result"
1040
- }
1041
- ],
1042
- "source": [
1043
- "np.mean(voting)"
1044
- ]
1045
- },
1046
- {
1047
- "cell_type": "code",
1048
- "execution_count": 25,
1049
- "metadata": {},
1050
- "outputs": [
1051
- {
1052
- "data": {
1053
- "text/plain": [
1054
- "[0.3248062015503624,\n",
1055
- " 0.46608315098458075,\n",
1056
- " 0.5763157894736463,\n",
1057
- " 0.2852112676055334,\n",
1058
- " 0.31884057971011603,\n",
1059
- " 0.4759725400457121]"
1060
- ]
1061
- },
1062
- "execution_count": 25,
1063
- "metadata": {},
1064
- "output_type": "execute_result"
1065
- }
1066
- ],
1067
- "source": [
1068
- "voting"
1069
- ]
1070
- },
1071
- {
1072
- "cell_type": "code",
1073
- "execution_count": 26,
1074
- "metadata": {},
1075
- "outputs": [
1076
- {
1077
- "data": {
1078
- "text/plain": [
1079
- "[0.5106142349456536,\n",
1080
- " 0.640202275543952,\n",
1081
- " 0.709448778435959,\n",
1082
- " 0.45579515959653394,\n",
1083
- " 0.453960121993875,\n",
1084
- " 0.6218724605270242]"
1085
- ]
1086
- },
1087
- "execution_count": 26,
1088
- "metadata": {},
1089
- "output_type": "execute_result"
1090
- }
1091
- ],
1092
- "source": [
1093
- "mcc"
1094
- ]
1095
- },
1096
- {
1097
- "cell_type": "code",
1098
- "execution_count": 27,
1099
- "metadata": {},
1100
- "outputs": [
1101
- {
1102
- "data": {
1103
- "text/plain": [
1104
- "[0.9005707762557078,\n",
1105
- " 0.9721461187214612,\n",
1106
- " 0.9264840182648402,\n",
1107
- " 0.9768264840182649,\n",
1108
- " 0.9141552511415525,\n",
1109
- " 0.9477168949771689]"
1110
- ]
1111
- },
1112
- "execution_count": 27,
1113
- "metadata": {},
1114
- "output_type": "execute_result"
1115
- }
1116
- ],
1117
- "source": [
1118
- "accuracy"
1119
- ]
1120
- }
1121
- ],
1122
- "metadata": {
1123
- "kernelspec": {
1124
- "display_name": "Python 3",
1125
- "language": "python",
1126
- "name": "python3"
1127
- },
1128
- "language_info": {
1129
- "codemirror_mode": {
1130
- "name": "ipython",
1131
- "version": 3
1132
- },
1133
- "file_extension": ".py",
1134
- "mimetype": "text/x-python",
1135
- "name": "python",
1136
- "nbconvert_exporter": "python",
1137
- "pygments_lexer": "ipython3",
1138
- "version": "3.8.10"
1139
- }
1140
- },
1141
- "nbformat": 4,
1142
- "nbformat_minor": 2
1143
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Analysis_code/find_reason/make_trend_plot.ipynb DELETED
The diff for this file is too large to render. See raw diff
 
Analysis_code/find_reason/wasserstein_distance.ipynb DELETED
@@ -1,552 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "code",
5
- "execution_count": 1,
6
- "metadata": {},
7
- "outputs": [
8
- {
9
- "name": "stderr",
10
- "output_type": "stream",
11
- "text": [
12
- "2025-12-29 07:26:00.319461: I tensorflow/core/util/port.cc:110] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.\n",
13
- "2025-12-29 07:26:00.343609: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\n",
14
- "To enable the following instructions: AVX2 AVX_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n",
15
- "2025-12-29 07:26:00.726272: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n"
16
- ]
17
- }
18
- ],
19
- "source": [
20
- "# 분석에 필요한 라이브러리 임포트\n",
21
- "import warnings\n",
22
- "warnings.filterwarnings('ignore')\n",
23
- "import pandas as pd\n",
24
- "import numpy as np\n",
25
- "import matplotlib.pyplot as plt\n",
26
- "import seaborn as sns\n",
27
- "from scipy import stats\n",
28
- "from scipy.spatial import distance\n",
29
- "from scipy.stats import wasserstein_distance, entropy, ks_2samp\n",
30
- "from sklearn.manifold import TSNE\n",
31
- "from sklearn.preprocessing import StandardScaler\n",
32
- "from sklearn.ensemble import RandomForestRegressor\n",
33
- "from sklearn.ensemble import RandomForestClassifier # Added\n",
34
- "from sklearn.model_selection import train_test_split # Added\n",
35
- "from sklearn.metrics import roc_auc_score # Added\n",
36
- "from statsmodels.distributions.empirical_distribution import ECDF # Added\n",
37
- "import ot\n",
38
- "\n",
39
- "\n",
40
- "# 한글 폰트 설정\n",
41
- "plt.rcParams['font.family'] = 'NanumGothic'\n",
42
- "plt.rcParams['axes.unicode_minus'] = False"
43
- ]
44
- },
45
- {
46
- "cell_type": "code",
47
- "execution_count": 2,
48
- "metadata": {},
49
- "outputs": [],
50
- "source": [
51
- "seoul = pd.read_feather(\"../../data/data_for_modeling/df_seoul.feather\")\n",
52
- "seoul= seoul[['datetime','hm','PM10','PM25','year','month','hour','multi_class']]\n",
53
- "\n",
54
- "busan = pd.read_feather(\"../../data/data_for_modeling/df_busan.feather\")\n",
55
- "busan= busan[['datetime','hm','PM10','PM25','year','month','hour','multi_class']]\n",
56
- "\n",
57
- "incheon = pd.read_feather(\"../../data/data_for_modeling/df_incheon.feather\")\n",
58
- "incheon= incheon[['datetime','hm','PM10','PM25','year','month','hour','multi_class']]\n",
59
- "\n",
60
- "daegu = pd.read_feather(\"../../data/data_for_modeling/df_daegu.feather\")\n",
61
- "daegu= daegu[['datetime','hm','PM10','PM25','year','month','hour','multi_class']]\n",
62
- "\n",
63
- "daejeon = pd.read_feather(\"../../data/data_for_modeling/df_daejeon.feather\")\n",
64
- "daejeon= daejeon[['datetime','hm','PM10','PM25','year','month','hour','multi_class']]\n",
65
- "\n",
66
- "gwangju = pd.read_feather(\"../../data/data_for_modeling/df_gwangju.feather\")\n",
67
- "gwangju= gwangju[['datetime','hm','PM10','PM25','year','month','hour','multi_class']]"
68
- ]
69
- },
70
- {
71
- "cell_type": "code",
72
- "execution_count": 3,
73
- "metadata": {},
74
- "outputs": [
75
- {
76
- "name": "stdout",
77
- "output_type": "stream",
78
- "text": [
79
- "[0.5920662 0.92351786]\n",
80
- "[0.60414398 0.9190468 ]\n",
81
- "[0.60250035 0.9391276 ]\n",
82
- "[0.60112832 0.92493121]\n",
83
- "[0.58469137 0.90476229]\n",
84
- "[0.617718 0.93503164]\n"
85
- ]
86
- }
87
- ],
88
- "source": [
89
- "from sklearn.decomposition import PCA\n",
90
- "\n",
91
- "# 특성 선택 (예: PM10, PM25, hm 등)\n",
92
- "features = ['PM10','PM25', 'hm']\n",
93
- "# 스케일링\n",
94
- "scaler = StandardScaler()\n",
95
- "scaled_features = scaler.fit_transform(seoul[features])\n",
96
- "pca = PCA(n_components=2)\n",
97
- "pca.fit(scaled_features)\n",
98
- "print(pca.explained_variance_ratio_.cumsum())\n",
99
- "seoul_pca = pca.transform(scaled_features)\n",
100
- "seoul.drop(columns=['PM25', 'hm'], inplace=True)\n",
101
- "seoul[['pca_x', 'pca_y']] = seoul_pca\n",
102
- "\n",
103
- "\n",
104
- "scaled_features = scaler.fit_transform(busan[features])\n",
105
- "pca = PCA(n_components=2)\n",
106
- "pca.fit(scaled_features)\n",
107
- "print(pca.explained_variance_ratio_.cumsum())\n",
108
- "busan_pca = pca.transform(scaled_features)\n",
109
- "busan.drop(columns=['PM25', 'hm'], inplace=True)\n",
110
- "busan[['pca_x', 'pca_y']] = busan_pca\n",
111
- "\n",
112
- "scaled_features = scaler.fit_transform(incheon[features]) \n",
113
- "pca = PCA(n_components=2)\n",
114
- "pca.fit(scaled_features)\n",
115
- "print(pca.explained_variance_ratio_.cumsum())\n",
116
- "incheon_pca = pca.transform(scaled_features)\n",
117
- "incheon.drop(columns=['PM25', 'hm'], inplace=True)\n",
118
- "incheon[['pca_x', 'pca_y']] = incheon_pca\n",
119
- "\n",
120
- "scaled_features = scaler.fit_transform(daegu[features])\n",
121
- "pca = PCA(n_components=2)\n",
122
- "pca.fit(scaled_features)\n",
123
- "print(pca.explained_variance_ratio_.cumsum())\n",
124
- "daegu_pca = pca.transform(scaled_features)\n",
125
- "daegu.drop(columns=['PM25', 'hm'], inplace=True)\n",
126
- "daegu[['pca_x', 'pca_y']] = daegu_pca\n",
127
- "\n",
128
- "scaled_features = scaler.fit_transform(daejeon[features])\n",
129
- "pca = PCA(n_components=2)\n",
130
- "pca.fit(scaled_features)\n",
131
- "print(pca.explained_variance_ratio_.cumsum())\n",
132
- "daejeon_pca = pca.transform(scaled_features)\n",
133
- "daejeon.drop(columns=['PM25', 'hm'], inplace=True)\n",
134
- "daejeon[['pca_x', 'pca_y']] = daejeon_pca\n",
135
- "\n",
136
- "scaled_features = scaler.fit_transform(gwangju[features])\n",
137
- "pca = PCA(n_components=2)\n",
138
- "pca.fit(scaled_features)\n",
139
- "print(pca.explained_variance_ratio_.cumsum())\n",
140
- "gwangju_pca = pca.transform(scaled_features)\n",
141
- "gwangju.drop(columns=['PM25', 'hm'], inplace=True)\n",
142
- "gwangju[['pca_x', 'pca_y']] = gwangju_pca\n"
143
- ]
144
- },
145
- {
146
- "cell_type": "code",
147
- "execution_count": 4,
148
- "metadata": {},
149
- "outputs": [],
150
- "source": [
151
- "seoul_2018 = seoul[seoul['year'] == 2018]\n",
152
- "seoul_2019 = seoul[seoul['year'] == 2019]\n",
153
- "seoul_2020 = seoul[seoul['year'] == 2020]\n",
154
- "seoul_2021 = seoul[seoul['year'] == 2021]\n",
155
- "years = [2018, 2019, 2020, 2021]\n",
156
- "\n",
157
- "\n",
158
- "busan_2018 = busan[busan['year'] == 2018]\n",
159
- "busan_2019 = busan[busan['year'] == 2019]\n",
160
- "busan_2020 = busan[busan['year'] == 2020]\n",
161
- "busan_2021 = busan[busan['year'] == 2021]\n",
162
- "years = [2018, 2019, 2020, 2021]\n",
163
- "\n",
164
- "\n",
165
- "incheon_2018 = incheon[incheon['year'] == 2018]\n",
166
- "incheon_2019 = incheon[incheon['year'] == 2019]\n",
167
- "incheon_2020 = incheon[incheon['year'] == 2020]\n",
168
- "incheon_2021 = incheon[incheon['year'] == 2021]\n",
169
- "years = [2018, 2019, 2020, 2021]\n",
170
- "\n",
171
- "\n",
172
- "daegu_2018 = daegu[daegu['year'] == 2018]\n",
173
- "daegu_2019 = daegu[daegu['year'] == 2019]\n",
174
- "daegu_2020 = daegu[daegu['year'] == 2020]\n",
175
- "daegu_2021 = daegu[daegu['year'] == 2021]\n",
176
- "years = [2018, 2019, 2020, 2021]\n",
177
- "\n",
178
- "\n",
179
- "daejeon_2018 = daejeon[daejeon['year'] == 2018]\n",
180
- "daejeon_2019 = daejeon[daejeon['year'] == 2019]\n",
181
- "daejeon_2020 = daejeon[daejeon['year'] == 2020]\n",
182
- "daejeon_2021 = daejeon[daejeon['year'] == 2021]\n",
183
- "years = [2018, 2019, 2020, 2021]\n",
184
- "\n",
185
- "\n",
186
- "gwangju_2018 = gwangju[gwangju['year'] == 2018]\n",
187
- "gwangju_2019 = gwangju[gwangju['year'] == 2019]\n",
188
- "gwangju_2020 = gwangju[gwangju['year'] == 2020]\n",
189
- "gwangju_2021 = gwangju[gwangju['year'] == 2021]\n",
190
- "years = [2018, 2019, 2020, 2021]\n",
191
- "\n",
192
- "\n",
193
- "\n"
194
- ]
195
- },
196
- {
197
- "cell_type": "code",
198
- "execution_count": 5,
199
- "metadata": {},
200
- "outputs": [
201
- {
202
- "name": "stdout",
203
- "output_type": "stream",
204
- "text": [
205
- " 2018 2019 2020 2021\n",
206
- "2018 0.0 0.123805 0.065046 1.077025\n",
207
- "2019 0.123805 0.0 0.0622 0.822734\n",
208
- "2020 0.065046 0.0622 0.0 0.038563\n",
209
- "2021 1.077025 0.822734 0.038563 0.0\n"
210
- ]
211
- }
212
- ],
213
- "source": [
214
- "# 연도별 데이터 준비\n",
215
- "years = [2018, 2019, 2020, 2021]\n",
216
- "data_dict = {\n",
217
- " 2018: seoul_2018[['pca_x', 'pca_y']].values,\n",
218
- " 2019: seoul_2019[['pca_x', 'pca_y']].values,\n",
219
- " 2020: seoul_2020[['pca_x', 'pca_y']].values,\n",
220
- " 2021: seoul_2021[['pca_x', 'pca_y']].values\n",
221
- "}\n",
222
- "\n",
223
- "\n",
224
- "# 결과를 저장할 데이터프레임 생성\n",
225
- "result_df = pd.DataFrame(index=years, columns=years)\n",
226
- "\n",
227
- "for i, year1 in enumerate(years):\n",
228
- " for j, year2 in enumerate(years):\n",
229
- " if year1 == year2:\n",
230
- " result_df.iloc[i, j] = 0.0\n",
231
- " if j < i:\n",
232
- " # 이미 계산된 값 사용\n",
233
- " result_df.iloc[i, j] = result_df.iloc[j, i]\n",
234
- " else:\n",
235
- " X = data_dict[year1]\n",
236
- " Y = data_dict[year2]\n",
237
- " a = np.ones(len(X)) / len(X)\n",
238
- " b = np.ones(len(Y)) / len(Y)\n",
239
- " W = ot.emd2(a, b, ot.dist(X, Y))\n",
240
- " result_df.iloc[i, j] = W\n",
241
- " result_df.iloc[j, i] = W # 대칭 위치에 동일 값 저장\n",
242
- "\n",
243
- "# 결과 출력\n",
244
- "print(result_df)"
245
- ]
246
- },
247
- {
248
- "cell_type": "code",
249
- "execution_count": 6,
250
- "metadata": {},
251
- "outputs": [
252
- {
253
- "name": "stdout",
254
- "output_type": "stream",
255
- "text": [
256
- " 2018 2019 2020 2021\n",
257
- "2018 0.0 0.121609 0.102711 1.413564\n",
258
- "2019 0.121609 0.0 0.095984 1.169424\n",
259
- "2020 0.102711 0.095984 0.0 0.968261\n",
260
- "2021 1.413564 1.169424 0.968261 0.0\n"
261
- ]
262
- }
263
- ],
264
- "source": [
265
- "# 연도별 데이터 준비\n",
266
- "years = [2018, 2019, 2020, 2021]\n",
267
- "data_dict = {\n",
268
- " 2018: busan_2018[['pca_x', 'pca_y']].values,\n",
269
- " 2019: busan_2019[['pca_x', 'pca_y']].values,\n",
270
- " 2020: busan_2020[['pca_x', 'pca_y']].values,\n",
271
- " 2021: busan_2021[['pca_x', 'pca_y']].values\n",
272
- "}\n",
273
- "\n",
274
- "\n",
275
- "# 결과를 저장할 데이터프레임 생성\n",
276
- "result_df = pd.DataFrame(index=years, columns=years)\n",
277
- "\n",
278
- "for i, year1 in enumerate(years):\n",
279
- " for j, year2 in enumerate(years):\n",
280
- " if year1 == year2:\n",
281
- " result_df.iloc[i, j] = 0.0\n",
282
- " if j < i:\n",
283
- " # 이미 계산된 값 사용\n",
284
- " result_df.iloc[i, j] = result_df.iloc[j, i]\n",
285
- " else:\n",
286
- " X = data_dict[year1]\n",
287
- " Y = data_dict[year2]\n",
288
- " a = np.ones(len(X)) / len(X)\n",
289
- " b = np.ones(len(Y)) / len(Y)\n",
290
- " W = ot.emd2(a, b, ot.dist(X, Y))\n",
291
- " result_df.iloc[i, j] = W\n",
292
- " result_df.iloc[j, i] = W # 대칭 위치에 동일 값 저장\n",
293
- "\n",
294
- "# 결과 출력\n",
295
- "print(result_df)"
296
- ]
297
- },
298
- {
299
- "cell_type": "code",
300
- "execution_count": 7,
301
- "metadata": {},
302
- "outputs": [
303
- {
304
- "name": "stdout",
305
- "output_type": "stream",
306
- "text": [
307
- " 2018 2019 2020 2021\n",
308
- "2018 0.0 0.07773 0.075873 0.452003\n",
309
- "2019 0.07773 0.0 0.057967 0.388116\n",
310
- "2020 0.075873 0.057967 0.0 0.038406\n",
311
- "2021 0.452003 0.388116 0.038406 0.0\n"
312
- ]
313
- }
314
- ],
315
- "source": [
316
- "# 연도별 데이터 준비\n",
317
- "years = [2018, 2019, 2020, 2021]\n",
318
- "data_dict = {\n",
319
- " 2018: incheon_2018[['pca_x', 'pca_y']].values,\n",
320
- " 2019: incheon_2019[['pca_x', 'pca_y']].values,\n",
321
- " 2020: incheon_2020[['pca_x', 'pca_y']].values,\n",
322
- " 2021: incheon_2021[['pca_x', 'pca_y']].values\n",
323
- "}\n",
324
- "\n",
325
- "\n",
326
- "# 결과를 저장할 데이터프레임 생성\n",
327
- "result_df = pd.DataFrame(index=years, columns=years)\n",
328
- "\n",
329
- "for i, year1 in enumerate(years):\n",
330
- " for j, year2 in enumerate(years):\n",
331
- " if year1 == year2:\n",
332
- " result_df.iloc[i, j] = 0.0\n",
333
- " if j < i:\n",
334
- " # 이미 계산된 값 사용\n",
335
- " result_df.iloc[i, j] = result_df.iloc[j, i]\n",
336
- " else:\n",
337
- " X = data_dict[year1]\n",
338
- " Y = data_dict[year2]\n",
339
- " a = np.ones(len(X)) / len(X)\n",
340
- " b = np.ones(len(Y)) / len(Y)\n",
341
- " W = ot.emd2(a, b, ot.dist(X, Y))\n",
342
- " result_df.iloc[i, j] = W\n",
343
- " result_df.iloc[j, i] = W # 대칭 위치에 동일 값 저장\n",
344
- "\n",
345
- "# 결과 출력\n",
346
- "print(result_df)"
347
- ]
348
- },
349
- {
350
- "cell_type": "code",
351
- "execution_count": 8,
352
- "metadata": {},
353
- "outputs": [
354
- {
355
- "name": "stdout",
356
- "output_type": "stream",
357
- "text": [
358
- " 2018 2019 2020 2021\n",
359
- "2018 0.0 0.120673 0.119091 0.73603\n",
360
- "2019 0.120673 0.0 0.094418 0.642491\n",
361
- "2020 0.119091 0.094418 0.0 0.060314\n",
362
- "2021 0.73603 0.642491 0.060314 0.0\n"
363
- ]
364
- }
365
- ],
366
- "source": [
367
- "# 연도별 데이터 준비\n",
368
- "years = [2018, 2019, 2020, 2021]\n",
369
- "data_dict = {\n",
370
- " 2018: daegu_2018[['pca_x', 'pca_y']].values,\n",
371
- " 2019: daegu_2019[['pca_x', 'pca_y']].values,\n",
372
- " 2020: daegu_2020[['pca_x', 'pca_y']].values,\n",
373
- " 2021: daegu_2021[['pca_x', 'pca_y']].values\n",
374
- "}\n",
375
- "\n",
376
- "\n",
377
- "# 결과를 저장할 데이터프레임 생성\n",
378
- "result_df = pd.DataFrame(index=years, columns=years)\n",
379
- "\n",
380
- "for i, year1 in enumerate(years):\n",
381
- " for j, year2 in enumerate(years):\n",
382
- " if year1 == year2:\n",
383
- " result_df.iloc[i, j] = 0.0\n",
384
- " if j < i:\n",
385
- " # 이미 계산된 값 사용\n",
386
- " result_df.iloc[i, j] = result_df.iloc[j, i]\n",
387
- " else:\n",
388
- " X = data_dict[year1]\n",
389
- " Y = data_dict[year2]\n",
390
- " a = np.ones(len(X)) / len(X)\n",
391
- " b = np.ones(len(Y)) / len(Y)\n",
392
- " W = ot.emd2(a, b, ot.dist(X, Y))\n",
393
- " result_df.iloc[i, j] = W\n",
394
- " result_df.iloc[j, i] = W # 대칭 위치에 동일 값 저장\n",
395
- "\n",
396
- "# 결과 출력\n",
397
- "print(result_df)"
398
- ]
399
- },
400
- {
401
- "cell_type": "code",
402
- "execution_count": 9,
403
- "metadata": {},
404
- "outputs": [
405
- {
406
- "name": "stdout",
407
- "output_type": "stream",
408
- "text": [
409
- " 2018 2019 2020 2021\n",
410
- "2018 0.0 0.28175 0.055327 0.881159\n",
411
- "2019 0.28175 0.0 0.119729 0.782018\n",
412
- "2020 0.055327 0.119729 0.0 0.042649\n",
413
- "2021 0.881159 0.782018 0.042649 0.0\n"
414
- ]
415
- }
416
- ],
417
- "source": [
418
- "# 연도별 데이터 준비\n",
419
- "years = [2018, 2019, 2020, 2021]\n",
420
- "data_dict = {\n",
421
- " 2018: daejeon_2018[['pca_x', 'pca_y']].values,\n",
422
- " 2019: daejeon_2019[['pca_x', 'pca_y']].values,\n",
423
- " 2020: daejeon_2020[['pca_x', 'pca_y']].values,\n",
424
- " 2021: daejeon_2021[['pca_x', 'pca_y']].values\n",
425
- "}\n",
426
- "\n",
427
- "\n",
428
- "# 결과를 저장할 데이터프레임 생성\n",
429
- "result_df = pd.DataFrame(index=years, columns=years)\n",
430
- "\n",
431
- "for i, year1 in enumerate(years):\n",
432
- " for j, year2 in enumerate(years):\n",
433
- " if year1 == year2:\n",
434
- " result_df.iloc[i, j] = 0.0\n",
435
- " if j < i:\n",
436
- " # 이미 계산된 값 사용\n",
437
- " result_df.iloc[i, j] = result_df.iloc[j, i]\n",
438
- " else:\n",
439
- " X = data_dict[year1]\n",
440
- " Y = data_dict[year2]\n",
441
- " a = np.ones(len(X)) / len(X)\n",
442
- " b = np.ones(len(Y)) / len(Y)\n",
443
- " W = ot.emd2(a, b, ot.dist(X, Y))\n",
444
- " result_df.iloc[i, j] = W\n",
445
- " result_df.iloc[j, i] = W # 대칭 위치에 동일 값 저장\n",
446
- "\n",
447
- "# 결과 출력\n",
448
- "print(result_df)"
449
- ]
450
- },
451
- {
452
- "cell_type": "code",
453
- "execution_count": 10,
454
- "metadata": {},
455
- "outputs": [
456
- {
457
- "name": "stdout",
458
- "output_type": "stream",
459
- "text": [
460
- " 2018 2019 2020 2021\n",
461
- "2018 0.0 0.104899 0.081615 1.013308\n",
462
- "2019 0.104899 0.0 0.070288 0.89982\n",
463
- "2020 0.081615 0.070288 0.0 0.840959\n",
464
- "2021 1.013308 0.89982 0.840959 0.0\n"
465
- ]
466
- }
467
- ],
468
- "source": [
469
- "# 연도별 데이터 준비\n",
470
- "years = [2018, 2019, 2020, 2021]\n",
471
- "data_dict = {\n",
472
- " 2018: gwangju_2018[['pca_x', 'pca_y']].values,\n",
473
- " 2019: gwangju_2019[['pca_x', 'pca_y']].values,\n",
474
- " 2020: gwangju_2020[['pca_x', 'pca_y']].values,\n",
475
- " 2021: gwangju_2021[['pca_x', 'pca_y']].values\n",
476
- "}\n",
477
- "\n",
478
- "\n",
479
- "# 결과를 저장할 데이터프레임 생성\n",
480
- "result_df = pd.DataFrame(index=years, columns=years)\n",
481
- "\n",
482
- "for i, year1 in enumerate(years):\n",
483
- " for j, year2 in enumerate(years):\n",
484
- " if year1 == year2:\n",
485
- " result_df.iloc[i, j] = 0.0\n",
486
- " if j < i:\n",
487
- " # 이미 계산된 값 사용\n",
488
- " result_df.iloc[i, j] = result_df.iloc[j, i]\n",
489
- " else:\n",
490
- " X = data_dict[year1]\n",
491
- " Y = data_dict[year2]\n",
492
- " a = np.ones(len(X)) / len(X)\n",
493
- " b = np.ones(len(Y)) / len(Y)\n",
494
- " W = ot.emd2(a, b, ot.dist(X, Y))\n",
495
- " result_df.iloc[i, j] = W\n",
496
- " result_df.iloc[j, i] = W # 대칭 위치에 동일 값 저장\n",
497
- "\n",
498
- "# 결과 출력\n",
499
- "print(result_df)"
500
- ]
501
- },
502
- {
503
- "cell_type": "code",
504
- "execution_count": null,
505
- "metadata": {},
506
- "outputs": [],
507
- "source": []
508
- },
509
- {
510
- "cell_type": "code",
511
- "execution_count": null,
512
- "metadata": {},
513
- "outputs": [],
514
- "source": []
515
- },
516
- {
517
- "cell_type": "code",
518
- "execution_count": null,
519
- "metadata": {},
520
- "outputs": [],
521
- "source": []
522
- },
523
- {
524
- "cell_type": "code",
525
- "execution_count": null,
526
- "metadata": {},
527
- "outputs": [],
528
- "source": []
529
- }
530
- ],
531
- "metadata": {
532
- "kernelspec": {
533
- "display_name": "py39",
534
- "language": "python",
535
- "name": "python3"
536
- },
537
- "language_info": {
538
- "codemirror_mode": {
539
- "name": "ipython",
540
- "version": 3
541
- },
542
- "file_extension": ".py",
543
- "mimetype": "text/x-python",
544
- "name": "python",
545
- "nbconvert_exporter": "python",
546
- "pygments_lexer": "ipython3",
547
- "version": "3.9.18"
548
- }
549
- },
550
- "nbformat": 4,
551
- "nbformat_minor": 4
552
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Analysis_code/model_voting_test_best_sample/ensemble__voting_best_sample.ipynb DELETED
The diff for this file is too large to render. See raw diff
 
Analysis_code/visualization/model_visualize.ipynb DELETED
The diff for this file is too large to render. See raw diff