Antonio0616 commited on
Commit
f0671e0
·
verified ·
1 Parent(s): d08e094

Upload 3 files

Browse files
Files changed (3) hide show
  1. baseline_model.py +419 -0
  2. react_one.py +93 -0
  3. study_model.py +419 -0
baseline_model.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # train_blend_ftt_lgbm.py
2
+ # FT-Transformer (weighted MAE + 5-Fold OOF) + LightGBM (5-Fold OOF) + OOF blending
3
+ # pip install pandas numpy scikit-learn torch lightgbm openpyxl
4
+
5
+ import os, math, json, random, pathlib
6
+ import numpy as np
7
+ import pandas as pd
8
+ from typing import List, Tuple
9
+ from sklearn.model_selection import KFold
10
+ from sklearn.preprocessing import StandardScaler
11
+ from sklearn.metrics import mean_absolute_error
12
+ import lightgbm as lgb
13
+ import torch
14
+ import torch.nn as nn
15
+ from torch.utils.data import Dataset, DataLoader
16
+
17
+ # =========================
18
+ # Config
19
+ # =========================
20
+ SEED = 42
21
+ DATA_PATH = r"C:\Users\KDT10\OneDrive\바탕 화면\AutoForm\데이터통합.xlsx" # .xlsx 또는 .csv
22
+ TARGET = "max_failure"
23
+ CAT_COL = "material" # 범주형
24
+ NUM_COLS = ["thickness","diameter","degree","upper_radius","lower_radius","LB","RB"] # 필요 시 물성/파생변수 추가
25
+ N_SPLITS = 5
26
+
27
+ # FT-Transformer 하이퍼파라미터 (튜닝안)
28
+ D_MODEL = 256
29
+ NHEAD = 8
30
+ LAYERS = 6
31
+ DIM_FF = 1024
32
+ DROPOUT = 0.25
33
+ EPOCHS = 500
34
+ PATIENCE = 50
35
+ LR = 5e-4
36
+ WEIGHT_DECAY = 2e-4
37
+ BATCH_TRAIN = 256
38
+ BATCH_VAL = 512
39
+
40
+ # LightGBM 하이퍼파라미터
41
+ LGB_PARAMS = {
42
+ "objective": "mae",
43
+ "metric": "mae",
44
+ "learning_rate": 0.05,
45
+ "num_leaves": 31,
46
+ "feature_fraction": 0.9,
47
+ "bagging_fraction": 0.9,
48
+ "bagging_freq": 1,
49
+ "min_data_in_leaf": 20,
50
+ "verbosity": -1,
51
+ "seed": SEED,
52
+ }
53
+ NUM_BOOST_ROUND = 8000
54
+ EARLY_STOP = 400
55
+
56
+ ART_DIR = "artifacts_blend"
57
+ os.makedirs(ART_DIR, exist_ok=True)
58
+
59
+ # =========================
60
+ # Utils
61
+ # =========================
62
+ def get_safe_device():
63
+ """CUDA가 실제 사용 가능한지 미리 검증하고, 실패 시 CPU로 폴백."""
64
+ if torch.cuda.is_available():
65
+ try:
66
+ _ = torch.zeros(1, device="cuda")
67
+ torch.cuda.synchronize()
68
+ print("[INFO] Using CUDA")
69
+ return torch.device("cuda")
70
+ except Exception as e:
71
+ print(f"[WARN] CUDA available but failed to initialize: {e}")
72
+ print("[INFO] Using CPU")
73
+ return torch.device("cpu")
74
+
75
+ def set_seed(seed: int, device: torch.device):
76
+ random.seed(seed)
77
+ np.random.seed(seed)
78
+ torch.manual_seed(seed)
79
+ if device.type == "cuda":
80
+ try:
81
+ torch.cuda.manual_seed_all(seed)
82
+ except Exception as e:
83
+ print(f"[WARN] torch.cuda.manual_seed_all failed: {e}")
84
+
85
+ def read_table(path: str) -> pd.DataFrame:
86
+ p = pathlib.Path(path)
87
+ if p.suffix.lower() in (".xlsx", ".xls"):
88
+ return pd.read_excel(p) # openpyxl 필요
89
+ return pd.read_csv(p)
90
+
91
+ def ensure_categorical(df: pd.DataFrame, col: str) -> pd.DataFrame:
92
+ df = df.copy()
93
+ df[col] = df[col].astype(str).astype("category")
94
+ return df
95
+
96
+ def tukey_biweight_weights_by_group(df, target=TARGET, group=CAT_COL, c=4.685, eps=1e-9):
97
+ """재질별 median/IQR 기준 Tukey biweight 가중치(0~1)"""
98
+ df = df.copy()
99
+ w = np.ones(len(df), dtype=np.float32)
100
+ for g, idx in df.groupby(group).groups.items():
101
+ y = df.loc[idx, target].astype(float)
102
+ med = np.median(y)
103
+ q1, q3 = np.percentile(y, 25), np.percentile(y, 75)
104
+ iqr = max(q3 - q1, eps)
105
+ u = (y - med) / (c * iqr)
106
+ w_g = np.where(np.abs(u) < 1, (1 - u**2)**2, 0.0)
107
+ w[idx] = w_g.astype(np.float32)
108
+ return np.clip(w, 0.05, 1.0).astype(np.float32)
109
+
110
+ def search_best_alpha(oof_a: np.ndarray, oof_b: np.ndarray, y_true: np.ndarray):
111
+ alphas = np.linspace(0.0, 1.0, 1001) # 0.0001 간격 정밀 탐색
112
+ best_a, best_mae = None, 1e9
113
+ for a in alphas:
114
+ blend = a*oof_a + (1-a)*oof_b
115
+ mae = mean_absolute_error(y_true, blend)
116
+ if mae < best_mae:
117
+ best_a, best_mae = a, mae
118
+ return best_a, best_mae
119
+
120
+ # =========================
121
+ # Dataset / Model
122
+ # =========================
123
+ class TabDataset(Dataset):
124
+ def __init__(self, mat_ids, num_feats, target=None, weights=None):
125
+ self.mat_ids = torch.tensor(mat_ids, dtype=torch.long)
126
+ self.num_feats = torch.tensor(num_feats, dtype=torch.float32)
127
+ self.target = None if target is None else torch.tensor(target, dtype=torch.float32).view(-1,1)
128
+ self.weights = None if weights is None else torch.tensor(weights, dtype=torch.float32).view(-1,1)
129
+ def __len__(self): return len(self.mat_ids)
130
+ def __getitem__(self, i):
131
+ if self.target is None:
132
+ return self.mat_ids[i], self.num_feats[i]
133
+ if self.weights is None:
134
+ return self.mat_ids[i], self.num_feats[i], self.target[i]
135
+ return self.mat_ids[i], self.num_feats[i], self.target[i], self.weights[i]
136
+
137
+ class FTTransformer(nn.Module):
138
+ def __init__(self, n_materials:int, n_num:int, d_model:int=128, nhead:int=8,
139
+ num_layers:int=4, dim_ff:int=256, dropout:float=0.2):
140
+ super().__init__()
141
+ self.mat_emb = nn.Embedding(n_materials, d_model)
142
+ self.num_linears = nn.ModuleList([nn.Linear(1, d_model) for _ in range(n_num)])
143
+ self.cls = nn.Parameter(torch.zeros(1, 1, d_model))
144
+ nn.init.trunc_normal_(self.cls, std=0.02)
145
+ enc_layer = nn.TransformerEncoderLayer(
146
+ d_model=d_model, nhead=nhead,
147
+ dim_feedforward=dim_ff, dropout=dropout,
148
+ batch_first=True, activation='gelu', norm_first=True
149
+ )
150
+ self.encoder = nn.TransformerEncoder(enc_layer, num_layers=num_layers)
151
+ self.head = nn.Sequential(
152
+ nn.LayerNorm(d_model),
153
+ nn.Linear(d_model, d_model),
154
+ nn.GELU(),
155
+ nn.Dropout(dropout),
156
+ nn.Linear(d_model, 1)
157
+ )
158
+ def forward(self, mat_ids: torch.LongTensor, x_num: torch.FloatTensor):
159
+ B = x_num.size(0)
160
+ mat_tok = self.mat_emb(mat_ids).unsqueeze(1) # (B,1,d)
161
+ num_tok = torch.cat([lin(x_num[:, i:i+1]).unsqueeze(1) for i,lin in enumerate(self.num_linears)], dim=1)
162
+ tokens = torch.cat([self.cls.expand(B, -1, -1), mat_tok, num_tok], dim=1)
163
+ h = self.encoder(tokens)
164
+ return self.head(h[:, 0, :]) # (B,1)
165
+
166
+ def weighted_l1_loss(pred, y, w):
167
+ return (w * (pred - y).abs()).sum() / (w.sum() + 1e-9)
168
+
169
+ def val_mae(model, loader, device):
170
+ model.eval()
171
+ mae, n = 0.0, 0
172
+ with torch.no_grad():
173
+ for batch in loader:
174
+ if len(batch) == 4:
175
+ m,x,y,_ = batch
176
+ else:
177
+ m,x,y = batch
178
+ m,x,y = m.to(device), x.to(device), y.to(device)
179
+ p = model(m,x)
180
+ mae += (p - y).abs().sum().item()
181
+ n += y.size(0)
182
+ return mae / n
183
+
184
+ # =========================
185
+ # Main
186
+ # =========================
187
+ def main():
188
+ # 안전 디바이스 결정 → 그 디바이스 기준으로 시드 설정
189
+ device = get_safe_device()
190
+ set_seed(SEED, device)
191
+
192
+ # ----- Load -----
193
+ df = read_table(DATA_PATH).copy()
194
+ need = [CAT_COL] + NUM_COLS + [TARGET]
195
+ missing = [c for c in need if c not in df.columns]
196
+ if missing: raise RuntimeError(f"입력 데이터에 없는 컬럼: {missing}")
197
+ df = df.dropna(subset=[TARGET]).reset_index(drop=True)
198
+ df = ensure_categorical(df, CAT_COL)
199
+
200
+ # 샘플 가중치(없으면 로버스트 가중치 생성)
201
+ if "sample_weight" in df.columns:
202
+ df["sample_weight"] = df["sample_weight"].astype(np.float32)
203
+ else:
204
+ df["sample_weight"] = tukey_biweight_weights_by_group(df, target=TARGET, group=CAT_COL, c=4.685)
205
+
206
+ # material → id
207
+ materials = sorted(df[CAT_COL].astype(str).unique())
208
+ mat2id = {m:i for i,m in enumerate(materials)}
209
+ df["_mat_id"] = df[CAT_COL].astype(str).map(mat2id).astype(int)
210
+
211
+ # 공통 어레이
212
+ X_num_full = df[NUM_COLS].values.astype(np.float32)
213
+ y_full = df[TARGET].values.astype(np.float32)
214
+ m_full = df["_mat_id"].values
215
+ w_full = df["sample_weight"].values.astype(np.float32)
216
+
217
+ # =========================
218
+ # 1) FT-Transformer 5-Fold OOF
219
+ # =========================
220
+ kf = KFold(n_splits=N_SPLITS, shuffle=True, random_state=SEED)
221
+ oof_dl = np.zeros(len(df), dtype=np.float32)
222
+ dl_models, dl_scalers = [], []
223
+ fold_summ_dl = []
224
+
225
+ for fold, (tr_idx, va_idx) in enumerate(kf.split(X_num_full), 1):
226
+ print(f"\n========== [DL] FOLD {fold}/{N_SPLITS} ==========")
227
+ # 스케일러 누수 방지
228
+ scaler = StandardScaler()
229
+ X_tr = scaler.fit_transform(X_num_full[tr_idx]).astype(np.float32)
230
+ X_va = scaler.transform(X_num_full[va_idx]).astype(np.float32)
231
+ y_tr, y_va = y_full[tr_idx], y_full[va_idx]
232
+ m_tr, m_va = m_full[tr_idx], m_full[va_idx]
233
+ w_tr, w_va = w_full[tr_idx], w_full[va_idx]
234
+
235
+ train_ds = TabDataset(m_tr, X_tr, y_tr, w_tr)
236
+ val_ds = TabDataset(m_va, X_va, y_va, w_va)
237
+ train_dl = DataLoader(train_ds, batch_size=BATCH_TRAIN, shuffle=True, num_workers=0)
238
+ val_dl = DataLoader(val_ds, batch_size=BATCH_VAL, shuffle=False, num_workers=0)
239
+
240
+ model = FTTransformer(
241
+ n_materials=len(materials), n_num=len(NUM_COLS),
242
+ d_model=D_MODEL, nhead=NHEAD, num_layers=LAYERS, dim_ff=DIM_FF, dropout=DROPOUT
243
+ )
244
+ # 디바이스 이동에 실패하면 CPU 폴백
245
+ try:
246
+ model = model.to(device)
247
+ except Exception as e:
248
+ print(f"[WARN] model.to({device}) failed: {e}. Falling back to CPU.")
249
+ device = torch.device("cpu")
250
+ model = model.to(device)
251
+
252
+ optim = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=WEIGHT_DECAY)
253
+ sched = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optim, T_0=10)
254
+
255
+ best_mae, best_state, wait = 1e9, None, 0
256
+ for epoch in range(1, EPOCHS+1):
257
+ model.train()
258
+ for m,x,y,w in train_dl:
259
+ m,x,y,w = m.to(device), x.to(device), y.to(device), w.to(device)
260
+ optim.zero_grad(set_to_none=True)
261
+ pred = model(m,x)
262
+ loss = weighted_l1_loss(pred, y, w)
263
+ loss.backward()
264
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 2.0)
265
+ optim.step()
266
+ sched.step(epoch)
267
+
268
+ mae = val_mae(model, val_dl, device)
269
+ print(f"[DL {epoch:03d}] VAL MAE={mae:.4f}")
270
+ if mae < best_mae - 1e-4:
271
+ best_mae, wait = mae, 0
272
+ best_state = {k:v.cpu().clone() for k,v in model.state_dict().items()}
273
+ else:
274
+ wait += 1
275
+ if wait >= PATIENCE:
276
+ print("Early stopping.")
277
+ break
278
+
279
+ # 복원 + fold 저장
280
+ if best_state is not None:
281
+ model.load_state_dict(best_state)
282
+ torch.save({
283
+ "state_dict": model.state_dict(),
284
+ "materials": materials,
285
+ "num_cols": NUM_COLS,
286
+ "scaler_mean": scaler.mean_, "scaler_scale": scaler.scale_,
287
+ }, os.path.join(ART_DIR, f"ftt_fold{fold}.pt"))
288
+ fold_summ_dl.append(best_mae)
289
+ print(f"[DL FOLD {fold}] best VAL MAE={best_mae:.4f}")
290
+
291
+ # ── OOF 채우기 (모델과 텐서를 같은 device에서)
292
+ try:
293
+ model = model.to(device)
294
+ except Exception as e:
295
+ print(f"[WARN] model.to({device}) failed during OOF: {e}. Falling back to CPU.")
296
+ device = torch.device("cpu")
297
+ model = model.to(device)
298
+
299
+ model.eval()
300
+ preds = []
301
+ with torch.no_grad():
302
+ val_loader = DataLoader(val_ds, batch_size=BATCH_VAL, shuffle=False, num_workers=0)
303
+ for batch in val_loader:
304
+ if len(batch)==4:
305
+ m,x,y,_ = batch
306
+ else:
307
+ m,x,y = batch
308
+ m,x = m.to(device), x.to(device)
309
+ p = model(m,x).cpu().numpy().ravel()
310
+ preds.append(p)
311
+ oof_dl[va_idx] = np.concatenate(preds).astype(np.float32)
312
+
313
+ # ── OOF 완료 후 CPU로 내려서 보관
314
+ dl_models.append(model.cpu())
315
+ dl_scalers.append(scaler)
316
+
317
+ oof_mae_dl = mean_absolute_error(y_full, oof_dl)
318
+ print("\n[DL] Fold best MAEs:", [f"{m:.4f}" for m in fold_summ_dl])
319
+ print(f"[DL] OOF MAE : {oof_mae_dl:.4f}")
320
+ pd.DataFrame({"y_true": y_full, "y_oof_dl": oof_dl}).to_csv(os.path.join(ART_DIR, "oof_dl.csv"), index=False)
321
+
322
+ # =========================
323
+ # 2) LightGBM 5-Fold OOF (callbacks로 조기 종료/로그)
324
+ # =========================
325
+ df = ensure_categorical(df, CAT_COL)
326
+ FEATS_GBDT = [CAT_COL] + NUM_COLS
327
+ X_gbdt = df[FEATS_GBDT].copy()
328
+ y = y_full
329
+ w = w_full
330
+
331
+ kf2 = KFold(n_splits=N_SPLITS, shuffle=True, random_state=SEED)
332
+ oof_lgbm = np.zeros(len(df), dtype=np.float32)
333
+ lgbm_models = []
334
+ fold_summ_lgb = []
335
+
336
+ for fold, (tr_idx, va_idx) in enumerate(kf2.split(X_gbdt), 1):
337
+ print(f"\n========== [LGBM] FOLD {fold}/{N_SPLITS} ==========")
338
+ X_tr, X_va = X_gbdt.iloc[tr_idx], X_gbdt.iloc[va_idx]
339
+ y_tr, y_va = y[tr_idx], y[va_idx]
340
+ w_tr, w_va = w[tr_idx], w[va_idx]
341
+
342
+ dtr = lgb.Dataset(X_tr, label=y_tr, weight=w_tr,
343
+ categorical_feature=[CAT_COL], free_raw_data=False)
344
+ dva = lgb.Dataset(X_va, label=y_va, weight=w_va,
345
+ categorical_feature=[CAT_COL], reference=dtr, free_raw_data=False)
346
+
347
+ callbacks = [
348
+ lgb.early_stopping(EARLY_STOP, verbose=False),
349
+ lgb.log_evaluation(100),
350
+ ]
351
+
352
+ model = lgb.train(
353
+ LGB_PARAMS,
354
+ dtr,
355
+ num_boost_round=NUM_BOOST_ROUND,
356
+ valid_sets=[dtr, dva],
357
+ valid_names=["train","valid"],
358
+ callbacks=callbacks,
359
+ )
360
+
361
+ pred_va = model.predict(X_va, num_iteration=model.best_iteration)
362
+ oof_lgbm[va_idx] = pred_va.astype(np.float32)
363
+ mae = mean_absolute_error(y_va, pred_va)
364
+ fold_summ_lgb.append(mae)
365
+ print(f"[LGBM FOLD {fold}] VAL MAE={mae:.4f}")
366
+ model.save_model(os.path.join(ART_DIR, f"lgbm_fold{fold}.txt"),
367
+ num_iteration=model.best_iteration)
368
+ lgbm_models.append(model)
369
+
370
+ oof_mae_lgb = mean_absolute_error(y, oof_lgbm)
371
+ print("\n[LGBM] Fold MAEs:", [f"{m:.4f}" for m in fold_summ_lgb])
372
+ print(f"[LGBM] OOF MAE : {oof_mae_lgb:.4f}")
373
+ pd.DataFrame({"y_true": y, "y_oof_lgbm": oof_lgbm}).to_csv(os.path.join(ART_DIR, "oof_lgbm.csv"), index=False)
374
+
375
+ # =========================
376
+ # 3) OOF Blending (DL + LGBM)
377
+ # =========================
378
+ best_alpha, best_mae = search_best_alpha(oof_dl, oof_lgbm, y_full)
379
+ print(f"\n[BLEND] best α={best_alpha:.3f}, blended OOF MAE={best_mae:.4f}")
380
+ with open(os.path.join(ART_DIR, "blend_alpha.json"), "w") as f:
381
+ json.dump({"best_alpha": float(best_alpha), "oof_mae_blend": float(best_mae),
382
+ "oof_mae_dl": float(oof_mae_dl), "oof_mae_lgbm": float(oof_mae_lgb)}, f, indent=2)
383
+
384
+ # =========================
385
+ # 4) Inference helper (예시)
386
+ # =========================
387
+ def predict_dl_ensemble(df_new: pd.DataFrame) -> np.ndarray:
388
+ df_new = df_new.copy()
389
+ df_new["_mat_id"] = df_new[CAT_COL].astype(str).map(mat2id).fillna(0).astype(int)
390
+ Xn = df_new[NUM_COLS].values.astype(np.float32)
391
+
392
+ preds = []
393
+ for mdl, sc in zip(dl_models, dl_scalers):
394
+ x = sc.transform(Xn).astype(np.float32)
395
+ mdl.eval()
396
+ with torch.no_grad():
397
+ m_ids = torch.tensor(df_new["_mat_id"].values, dtype=torch.long)
398
+ x_t = torch.tensor(x, dtype=torch.float32)
399
+ p = mdl(m_ids, x_t).cpu().numpy().ravel()
400
+ preds.append(p)
401
+ return np.mean(preds, axis=0)
402
+
403
+ def predict_lgbm_ensemble(df_new: pd.DataFrame) -> np.ndarray:
404
+ Xn = df_new[[CAT_COL] + NUM_COLS].copy()
405
+ Xn[CAT_COL] = Xn[CAT_COL].astype(str).astype("category")
406
+ preds = [mdl.predict(Xn, num_iteration=mdl.best_iteration) for mdl in lgbm_models]
407
+ return np.mean(preds, axis=0)
408
+
409
+ with open(os.path.join(ART_DIR, "materials.json"), "w", encoding="utf-8") as f:
410
+ json.dump({"materials": materials}, f, ensure_ascii=False, indent=2)
411
+ with open(os.path.join(ART_DIR, "columns.json"), "w", encoding="utf-8") as f:
412
+ json.dump({"num_cols": NUM_COLS, "cat_col": CAT_COL, "target": TARGET}, f, ensure_ascii=False, indent=2)
413
+
414
+ print(f"\nArtifacts saved in: {ART_DIR}")
415
+ print("Use predict_dl_ensemble / predict_lgbm_ensemble, and blend with best_alpha for new data.")
416
+
417
+ if __name__ == "__main__":
418
+ device = get_safe_device()
419
+ main()
react_one.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # roofrail_filter_static.py
2
+ import numpy as np
3
+ import pandas as pd
4
+
5
+ # 최소 허용 R (전제)
6
+ R_MIN = 1.0
7
+
8
+ # 직경별 허용범위 (직접 정의)
9
+ # 구조: {직경: {각도: (상단R_max, 하단R_max)}}
10
+ CONSTRAINTS = {
11
+ 17: {deg: (2.0, 5.0) for deg in range(62, 90)}, # 62~89°
12
+ 18: {deg: (3.0, 5.0) for deg in range(65, 91)}, # 65~90°
13
+ 19: {deg: (3.5, 4.5) for deg in range(66, 91)}, # 66~90°
14
+ 20: {deg: (4.0, 4.0) for deg in range(69, 91)}, # 69~90°
15
+ 21: {deg: (4.5, 3.0) for deg in range(72, 88)}, # 72~87°
16
+ 22: {deg: (5.0, 2.5) for deg in range(75, 88)}, # 75~87°
17
+ }
18
+
19
+ # 소재별 thinning 허용치 (실제 기준)
20
+ THIN_LIMITS = {
21
+ "SPCUD": 0.25,
22
+ "SPCC": 0.21,
23
+ "SPRC340": 0.20,
24
+ "SPRC440": 0.17,
25
+ "SPFC590": 0.16,
26
+ "SPFC780": 0.10,
27
+ "SPFC980": 0.08,
28
+ }
29
+
30
+ def filter_model_outputs(
31
+ candidates: pd.DataFrame,
32
+ thinning_limits: dict = THIN_LIMITS,
33
+ max_failure_threshold: float = 0.97, # ✅ 수정: 0.97 이하만 통과
34
+ r_min: float = R_MIN
35
+ ) -> pd.DataFrame:
36
+ """
37
+ candidates DataFrame 필수 컬럼:
38
+ ['material','thickness','diameter','degree','upper_r','lower_r',
39
+ 'pred_max_failure','pred_thining']
40
+
41
+ 반환: 입력 + ['allowed_R','allowed_model','final_ok','reject_reason']
42
+ """
43
+
44
+ df = candidates.copy()
45
+
46
+ allowed_R = []
47
+ reject_reason = []
48
+
49
+ for _, row in df.iterrows():
50
+ dia, deg, up, lo = int(row["diameter"]), int(row["degree"]), row["upper_r"], row["lower_r"]
51
+
52
+ # 1) 직경/각도 허용 여부
53
+ if dia not in CONSTRAINTS or deg not in CONSTRAINTS[dia]:
54
+ allowed_R.append(False)
55
+ reject_reason.append("disallowed_diameter_or_degree")
56
+ continue
57
+
58
+ up_max, lo_max = CONSTRAINTS[dia][deg]
59
+
60
+ # 2) R 범위 확인
61
+ if up < r_min or lo < r_min:
62
+ allowed_R.append(False)
63
+ reject_reason.append("R_below_min")
64
+ continue
65
+ if up > up_max:
66
+ allowed_R.append(False)
67
+ reject_reason.append("upper_r_above_max")
68
+ continue
69
+ if lo > lo_max:
70
+ allowed_R.append(False)
71
+ reject_reason.append("lower_r_above_max")
72
+ continue
73
+
74
+ # 통과
75
+ allowed_R.append(True)
76
+ reject_reason.append("")
77
+
78
+ df["allowed_R"] = allowed_R
79
+ df["reject_reason"] = reject_reason
80
+
81
+ # 3) 모델 조건
82
+ thin_limit = df["material"].map(thinning_limits)
83
+ cond_model = (
84
+ (df["pred_max_failure"] <= max_failure_threshold) & # ✅ 수정: <= 0.97
85
+ thin_limit.notna() &
86
+ (df["pred_thining"] <= thin_limit)
87
+ )
88
+ df["allowed_model"] = cond_model
89
+
90
+ # 최종
91
+ df["final_ok"] = df["allowed_R"] & df["allowed_model"]
92
+
93
+ return df
study_model.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # train_blend_ftt_lgbm.py
2
+ # FT-Transformer (weighted MAE + 5-Fold OOF) + LightGBM (5-Fold OOF) + OOF blending
3
+ # pip install pandas numpy scikit-learn torch lightgbm openpyxl
4
+
5
+ import os, math, json, random, pathlib
6
+ import numpy as np
7
+ import pandas as pd
8
+ from typing import List, Tuple
9
+ from sklearn.model_selection import KFold
10
+ from sklearn.preprocessing import StandardScaler
11
+ from sklearn.metrics import mean_absolute_error
12
+ import lightgbm as lgb
13
+ import torch
14
+ import torch.nn as nn
15
+ from torch.utils.data import Dataset, DataLoader
16
+
17
+ # =========================
18
+ # Config
19
+ # =========================
20
+ SEED = 42
21
+ DATA_PATH = r"C:\Users\KDT10\OneDrive\바탕 화면\AutoForm\데이터통합.xlsx" # .xlsx 또는 .csv
22
+ TARGET = "max_failure"
23
+ CAT_COL = "material" # 범주형
24
+ NUM_COLS = ["thickness","diameter","degree","upper_radius","lower_radius","LB","RB"] # 필요 시 물성/파생변수 추가
25
+ N_SPLITS = 5
26
+
27
+ # FT-Transformer 하이퍼파라미터 (튜닝안)
28
+ D_MODEL = 256
29
+ NHEAD = 8
30
+ LAYERS = 6
31
+ DIM_FF = 1024
32
+ DROPOUT = 0.25
33
+ EPOCHS = 500
34
+ PATIENCE = 50
35
+ LR = 5e-4
36
+ WEIGHT_DECAY = 2e-4
37
+ BATCH_TRAIN = 256
38
+ BATCH_VAL = 512
39
+
40
+ # LightGBM 하이퍼파라미터
41
+ LGB_PARAMS = {
42
+ "objective": "mae",
43
+ "metric": "mae",
44
+ "learning_rate": 0.05,
45
+ "num_leaves": 31,
46
+ "feature_fraction": 0.9,
47
+ "bagging_fraction": 0.9,
48
+ "bagging_freq": 1,
49
+ "min_data_in_leaf": 20,
50
+ "verbosity": -1,
51
+ "seed": SEED,
52
+ }
53
+ NUM_BOOST_ROUND = 8000
54
+ EARLY_STOP = 400
55
+
56
+ ART_DIR = "artifacts_blend"
57
+ os.makedirs(ART_DIR, exist_ok=True)
58
+
59
+ # =========================
60
+ # Utils
61
+ # =========================
62
+ def get_safe_device():
63
+ """CUDA가 실제 사용 가능한지 미리 검증하고, 실패 시 CPU로 폴백."""
64
+ if torch.cuda.is_available():
65
+ try:
66
+ _ = torch.zeros(1, device="cuda")
67
+ torch.cuda.synchronize()
68
+ print("[INFO] Using CUDA")
69
+ return torch.device("cuda")
70
+ except Exception as e:
71
+ print(f"[WARN] CUDA available but failed to initialize: {e}")
72
+ print("[INFO] Using CPU")
73
+ return torch.device("cpu")
74
+
75
+ def set_seed(seed: int, device: torch.device):
76
+ random.seed(seed)
77
+ np.random.seed(seed)
78
+ torch.manual_seed(seed)
79
+ if device.type == "cuda":
80
+ try:
81
+ torch.cuda.manual_seed_all(seed)
82
+ except Exception as e:
83
+ print(f"[WARN] torch.cuda.manual_seed_all failed: {e}")
84
+
85
+ def read_table(path: str) -> pd.DataFrame:
86
+ p = pathlib.Path(path)
87
+ if p.suffix.lower() in (".xlsx", ".xls"):
88
+ return pd.read_excel(p) # openpyxl 필요
89
+ return pd.read_csv(p)
90
+
91
+ def ensure_categorical(df: pd.DataFrame, col: str) -> pd.DataFrame:
92
+ df = df.copy()
93
+ df[col] = df[col].astype(str).astype("category")
94
+ return df
95
+
96
+ def tukey_biweight_weights_by_group(df, target=TARGET, group=CAT_COL, c=4.685, eps=1e-9):
97
+ """재질별 median/IQR 기준 Tukey biweight 가중치(0~1)"""
98
+ df = df.copy()
99
+ w = np.ones(len(df), dtype=np.float32)
100
+ for g, idx in df.groupby(group).groups.items():
101
+ y = df.loc[idx, target].astype(float)
102
+ med = np.median(y)
103
+ q1, q3 = np.percentile(y, 25), np.percentile(y, 75)
104
+ iqr = max(q3 - q1, eps)
105
+ u = (y - med) / (c * iqr)
106
+ w_g = np.where(np.abs(u) < 1, (1 - u**2)**2, 0.0)
107
+ w[idx] = w_g.astype(np.float32)
108
+ return np.clip(w, 0.05, 1.0).astype(np.float32)
109
+
110
+ def search_best_alpha(oof_a: np.ndarray, oof_b: np.ndarray, y_true: np.ndarray):
111
+ alphas = np.linspace(0.0, 1.0, 1001) # 0.0001 간격 정밀 탐색
112
+ best_a, best_mae = None, 1e9
113
+ for a in alphas:
114
+ blend = a*oof_a + (1-a)*oof_b
115
+ mae = mean_absolute_error(y_true, blend)
116
+ if mae < best_mae:
117
+ best_a, best_mae = a, mae
118
+ return best_a, best_mae
119
+
120
+ # =========================
121
+ # Dataset / Model
122
+ # =========================
123
+ class TabDataset(Dataset):
124
+ def __init__(self, mat_ids, num_feats, target=None, weights=None):
125
+ self.mat_ids = torch.tensor(mat_ids, dtype=torch.long)
126
+ self.num_feats = torch.tensor(num_feats, dtype=torch.float32)
127
+ self.target = None if target is None else torch.tensor(target, dtype=torch.float32).view(-1,1)
128
+ self.weights = None if weights is None else torch.tensor(weights, dtype=torch.float32).view(-1,1)
129
+ def __len__(self): return len(self.mat_ids)
130
+ def __getitem__(self, i):
131
+ if self.target is None:
132
+ return self.mat_ids[i], self.num_feats[i]
133
+ if self.weights is None:
134
+ return self.mat_ids[i], self.num_feats[i], self.target[i]
135
+ return self.mat_ids[i], self.num_feats[i], self.target[i], self.weights[i]
136
+
137
+ class FTTransformer(nn.Module):
138
+ def __init__(self, n_materials:int, n_num:int, d_model:int=128, nhead:int=8,
139
+ num_layers:int=4, dim_ff:int=256, dropout:float=0.2):
140
+ super().__init__()
141
+ self.mat_emb = nn.Embedding(n_materials, d_model)
142
+ self.num_linears = nn.ModuleList([nn.Linear(1, d_model) for _ in range(n_num)])
143
+ self.cls = nn.Parameter(torch.zeros(1, 1, d_model))
144
+ nn.init.trunc_normal_(self.cls, std=0.02)
145
+ enc_layer = nn.TransformerEncoderLayer(
146
+ d_model=d_model, nhead=nhead,
147
+ dim_feedforward=dim_ff, dropout=dropout,
148
+ batch_first=True, activation='gelu', norm_first=True
149
+ )
150
+ self.encoder = nn.TransformerEncoder(enc_layer, num_layers=num_layers)
151
+ self.head = nn.Sequential(
152
+ nn.LayerNorm(d_model),
153
+ nn.Linear(d_model, d_model),
154
+ nn.GELU(),
155
+ nn.Dropout(dropout),
156
+ nn.Linear(d_model, 1)
157
+ )
158
+ def forward(self, mat_ids: torch.LongTensor, x_num: torch.FloatTensor):
159
+ B = x_num.size(0)
160
+ mat_tok = self.mat_emb(mat_ids).unsqueeze(1) # (B,1,d)
161
+ num_tok = torch.cat([lin(x_num[:, i:i+1]).unsqueeze(1) for i,lin in enumerate(self.num_linears)], dim=1)
162
+ tokens = torch.cat([self.cls.expand(B, -1, -1), mat_tok, num_tok], dim=1)
163
+ h = self.encoder(tokens)
164
+ return self.head(h[:, 0, :]) # (B,1)
165
+
166
+ def weighted_l1_loss(pred, y, w):
167
+ return (w * (pred - y).abs()).sum() / (w.sum() + 1e-9)
168
+
169
+ def val_mae(model, loader, device):
170
+ model.eval()
171
+ mae, n = 0.0, 0
172
+ with torch.no_grad():
173
+ for batch in loader:
174
+ if len(batch) == 4:
175
+ m,x,y,_ = batch
176
+ else:
177
+ m,x,y = batch
178
+ m,x,y = m.to(device), x.to(device), y.to(device)
179
+ p = model(m,x)
180
+ mae += (p - y).abs().sum().item()
181
+ n += y.size(0)
182
+ return mae / n
183
+
184
+ # =========================
185
+ # Main
186
+ # =========================
187
+ def main():
188
+ # 안전 디바이스 결정 → 그 디바이스 기준으로 시드 설정
189
+ device = get_safe_device()
190
+ set_seed(SEED, device)
191
+
192
+ # ----- Load -----
193
+ df = read_table(DATA_PATH).copy()
194
+ need = [CAT_COL] + NUM_COLS + [TARGET]
195
+ missing = [c for c in need if c not in df.columns]
196
+ if missing: raise RuntimeError(f"입력 데이터에 없는 컬럼: {missing}")
197
+ df = df.dropna(subset=[TARGET]).reset_index(drop=True)
198
+ df = ensure_categorical(df, CAT_COL)
199
+
200
+ # 샘플 가중치(없으면 로버스트 가중치 생성)
201
+ if "sample_weight" in df.columns:
202
+ df["sample_weight"] = df["sample_weight"].astype(np.float32)
203
+ else:
204
+ df["sample_weight"] = tukey_biweight_weights_by_group(df, target=TARGET, group=CAT_COL, c=4.685)
205
+
206
+ # material → id
207
+ materials = sorted(df[CAT_COL].astype(str).unique())
208
+ mat2id = {m:i for i,m in enumerate(materials)}
209
+ df["_mat_id"] = df[CAT_COL].astype(str).map(mat2id).astype(int)
210
+
211
+ # 공통 어레이
212
+ X_num_full = df[NUM_COLS].values.astype(np.float32)
213
+ y_full = df[TARGET].values.astype(np.float32)
214
+ m_full = df["_mat_id"].values
215
+ w_full = df["sample_weight"].values.astype(np.float32)
216
+
217
+ # =========================
218
+ # 1) FT-Transformer 5-Fold OOF
219
+ # =========================
220
+ kf = KFold(n_splits=N_SPLITS, shuffle=True, random_state=SEED)
221
+ oof_dl = np.zeros(len(df), dtype=np.float32)
222
+ dl_models, dl_scalers = [], []
223
+ fold_summ_dl = []
224
+
225
+ for fold, (tr_idx, va_idx) in enumerate(kf.split(X_num_full), 1):
226
+ print(f"\n========== [DL] FOLD {fold}/{N_SPLITS} ==========")
227
+ # 스케일러 누수 방지
228
+ scaler = StandardScaler()
229
+ X_tr = scaler.fit_transform(X_num_full[tr_idx]).astype(np.float32)
230
+ X_va = scaler.transform(X_num_full[va_idx]).astype(np.float32)
231
+ y_tr, y_va = y_full[tr_idx], y_full[va_idx]
232
+ m_tr, m_va = m_full[tr_idx], m_full[va_idx]
233
+ w_tr, w_va = w_full[tr_idx], w_full[va_idx]
234
+
235
+ train_ds = TabDataset(m_tr, X_tr, y_tr, w_tr)
236
+ val_ds = TabDataset(m_va, X_va, y_va, w_va)
237
+ train_dl = DataLoader(train_ds, batch_size=BATCH_TRAIN, shuffle=True, num_workers=0)
238
+ val_dl = DataLoader(val_ds, batch_size=BATCH_VAL, shuffle=False, num_workers=0)
239
+
240
+ model = FTTransformer(
241
+ n_materials=len(materials), n_num=len(NUM_COLS),
242
+ d_model=D_MODEL, nhead=NHEAD, num_layers=LAYERS, dim_ff=DIM_FF, dropout=DROPOUT
243
+ )
244
+ # 디바이스 이동에 실패하면 CPU 폴백
245
+ try:
246
+ model = model.to(device)
247
+ except Exception as e:
248
+ print(f"[WARN] model.to({device}) failed: {e}. Falling back to CPU.")
249
+ device = torch.device("cpu")
250
+ model = model.to(device)
251
+
252
+ optim = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=WEIGHT_DECAY)
253
+ sched = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optim, T_0=10)
254
+
255
+ best_mae, best_state, wait = 1e9, None, 0
256
+ for epoch in range(1, EPOCHS+1):
257
+ model.train()
258
+ for m,x,y,w in train_dl:
259
+ m,x,y,w = m.to(device), x.to(device), y.to(device), w.to(device)
260
+ optim.zero_grad(set_to_none=True)
261
+ pred = model(m,x)
262
+ loss = weighted_l1_loss(pred, y, w)
263
+ loss.backward()
264
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 2.0)
265
+ optim.step()
266
+ sched.step(epoch)
267
+
268
+ mae = val_mae(model, val_dl, device)
269
+ print(f"[DL {epoch:03d}] VAL MAE={mae:.4f}")
270
+ if mae < best_mae - 1e-4:
271
+ best_mae, wait = mae, 0
272
+ best_state = {k:v.cpu().clone() for k,v in model.state_dict().items()}
273
+ else:
274
+ wait += 1
275
+ if wait >= PATIENCE:
276
+ print("Early stopping.")
277
+ break
278
+
279
+ # 복원 + fold 저장
280
+ if best_state is not None:
281
+ model.load_state_dict(best_state)
282
+ torch.save({
283
+ "state_dict": model.state_dict(),
284
+ "materials": materials,
285
+ "num_cols": NUM_COLS,
286
+ "scaler_mean": scaler.mean_, "scaler_scale": scaler.scale_,
287
+ }, os.path.join(ART_DIR, f"ftt_fold{fold}.pt"))
288
+ fold_summ_dl.append(best_mae)
289
+ print(f"[DL FOLD {fold}] best VAL MAE={best_mae:.4f}")
290
+
291
+ # ── OOF 채우기 (모델과 텐서를 같은 device에서)
292
+ try:
293
+ model = model.to(device)
294
+ except Exception as e:
295
+ print(f"[WARN] model.to({device}) failed during OOF: {e}. Falling back to CPU.")
296
+ device = torch.device("cpu")
297
+ model = model.to(device)
298
+
299
+ model.eval()
300
+ preds = []
301
+ with torch.no_grad():
302
+ val_loader = DataLoader(val_ds, batch_size=BATCH_VAL, shuffle=False, num_workers=0)
303
+ for batch in val_loader:
304
+ if len(batch)==4:
305
+ m,x,y,_ = batch
306
+ else:
307
+ m,x,y = batch
308
+ m,x = m.to(device), x.to(device)
309
+ p = model(m,x).cpu().numpy().ravel()
310
+ preds.append(p)
311
+ oof_dl[va_idx] = np.concatenate(preds).astype(np.float32)
312
+
313
+ # ── OOF 완료 후 CPU로 내려서 보관
314
+ dl_models.append(model.cpu())
315
+ dl_scalers.append(scaler)
316
+
317
+ oof_mae_dl = mean_absolute_error(y_full, oof_dl)
318
+ print("\n[DL] Fold best MAEs:", [f"{m:.4f}" for m in fold_summ_dl])
319
+ print(f"[DL] OOF MAE : {oof_mae_dl:.4f}")
320
+ pd.DataFrame({"y_true": y_full, "y_oof_dl": oof_dl}).to_csv(os.path.join(ART_DIR, "oof_dl.csv"), index=False)
321
+
322
+ # =========================
323
+ # 2) LightGBM 5-Fold OOF (callbacks로 조기 종료/로그)
324
+ # =========================
325
+ df = ensure_categorical(df, CAT_COL)
326
+ FEATS_GBDT = [CAT_COL] + NUM_COLS
327
+ X_gbdt = df[FEATS_GBDT].copy()
328
+ y = y_full
329
+ w = w_full
330
+
331
+ kf2 = KFold(n_splits=N_SPLITS, shuffle=True, random_state=SEED)
332
+ oof_lgbm = np.zeros(len(df), dtype=np.float32)
333
+ lgbm_models = []
334
+ fold_summ_lgb = []
335
+
336
+ for fold, (tr_idx, va_idx) in enumerate(kf2.split(X_gbdt), 1):
337
+ print(f"\n========== [LGBM] FOLD {fold}/{N_SPLITS} ==========")
338
+ X_tr, X_va = X_gbdt.iloc[tr_idx], X_gbdt.iloc[va_idx]
339
+ y_tr, y_va = y[tr_idx], y[va_idx]
340
+ w_tr, w_va = w[tr_idx], w[va_idx]
341
+
342
+ dtr = lgb.Dataset(X_tr, label=y_tr, weight=w_tr,
343
+ categorical_feature=[CAT_COL], free_raw_data=False)
344
+ dva = lgb.Dataset(X_va, label=y_va, weight=w_va,
345
+ categorical_feature=[CAT_COL], reference=dtr, free_raw_data=False)
346
+
347
+ callbacks = [
348
+ lgb.early_stopping(EARLY_STOP, verbose=False),
349
+ lgb.log_evaluation(100),
350
+ ]
351
+
352
+ model = lgb.train(
353
+ LGB_PARAMS,
354
+ dtr,
355
+ num_boost_round=NUM_BOOST_ROUND,
356
+ valid_sets=[dtr, dva],
357
+ valid_names=["train","valid"],
358
+ callbacks=callbacks,
359
+ )
360
+
361
+ pred_va = model.predict(X_va, num_iteration=model.best_iteration)
362
+ oof_lgbm[va_idx] = pred_va.astype(np.float32)
363
+ mae = mean_absolute_error(y_va, pred_va)
364
+ fold_summ_lgb.append(mae)
365
+ print(f"[LGBM FOLD {fold}] VAL MAE={mae:.4f}")
366
+ model.save_model(os.path.join(ART_DIR, f"lgbm_fold{fold}.txt"),
367
+ num_iteration=model.best_iteration)
368
+ lgbm_models.append(model)
369
+
370
+ oof_mae_lgb = mean_absolute_error(y, oof_lgbm)
371
+ print("\n[LGBM] Fold MAEs:", [f"{m:.4f}" for m in fold_summ_lgb])
372
+ print(f"[LGBM] OOF MAE : {oof_mae_lgb:.4f}")
373
+ pd.DataFrame({"y_true": y, "y_oof_lgbm": oof_lgbm}).to_csv(os.path.join(ART_DIR, "oof_lgbm.csv"), index=False)
374
+
375
+ # =========================
376
+ # 3) OOF Blending (DL + LGBM)
377
+ # =========================
378
+ best_alpha, best_mae = search_best_alpha(oof_dl, oof_lgbm, y_full)
379
+ print(f"\n[BLEND] best α={best_alpha:.3f}, blended OOF MAE={best_mae:.4f}")
380
+ with open(os.path.join(ART_DIR, "blend_alpha.json"), "w") as f:
381
+ json.dump({"best_alpha": float(best_alpha), "oof_mae_blend": float(best_mae),
382
+ "oof_mae_dl": float(oof_mae_dl), "oof_mae_lgbm": float(oof_mae_lgb)}, f, indent=2)
383
+
384
+ # =========================
385
+ # 4) Inference helper (예시)
386
+ # =========================
387
+ def predict_dl_ensemble(df_new: pd.DataFrame) -> np.ndarray:
388
+ df_new = df_new.copy()
389
+ df_new["_mat_id"] = df_new[CAT_COL].astype(str).map(mat2id).fillna(0).astype(int)
390
+ Xn = df_new[NUM_COLS].values.astype(np.float32)
391
+
392
+ preds = []
393
+ for mdl, sc in zip(dl_models, dl_scalers):
394
+ x = sc.transform(Xn).astype(np.float32)
395
+ mdl.eval()
396
+ with torch.no_grad():
397
+ m_ids = torch.tensor(df_new["_mat_id"].values, dtype=torch.long)
398
+ x_t = torch.tensor(x, dtype=torch.float32)
399
+ p = mdl(m_ids, x_t).cpu().numpy().ravel()
400
+ preds.append(p)
401
+ return np.mean(preds, axis=0)
402
+
403
+ def predict_lgbm_ensemble(df_new: pd.DataFrame) -> np.ndarray:
404
+ Xn = df_new[[CAT_COL] + NUM_COLS].copy()
405
+ Xn[CAT_COL] = Xn[CAT_COL].astype(str).astype("category")
406
+ preds = [mdl.predict(Xn, num_iteration=mdl.best_iteration) for mdl in lgbm_models]
407
+ return np.mean(preds, axis=0)
408
+
409
+ with open(os.path.join(ART_DIR, "materials.json"), "w", encoding="utf-8") as f:
410
+ json.dump({"materials": materials}, f, ensure_ascii=False, indent=2)
411
+ with open(os.path.join(ART_DIR, "columns.json"), "w", encoding="utf-8") as f:
412
+ json.dump({"num_cols": NUM_COLS, "cat_col": CAT_COL, "target": TARGET}, f, ensure_ascii=False, indent=2)
413
+
414
+ print(f"\nArtifacts saved in: {ART_DIR}")
415
+ print("Use predict_dl_ensemble / predict_lgbm_ensemble, and blend with best_alpha for new data.")
416
+
417
+ if __name__ == "__main__":
418
+ device = get_safe_device()
419
+ main()