-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain_model.py
More file actions
1964 lines (1619 loc) · 75.8 KB
/
Copy pathtrain_model.py
File metadata and controls
1964 lines (1619 loc) · 75.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Streaming model training for Overnight Finance Challenge.
Features computed row-by-row (no future leakage) via StatefulFeatureBuilder.
Pipeline:
- Ensemble: XGBoost + CatBoost + LightGBM (soft blend + stacking)
- Rare Class Detector (binary classifier: common vs rare)
- RareClassBooster for rare class probability correction
- DiagonalTemperatureCalibrator with per-class temperature
- OVR Threshold Optimizer
"""
from __future__ import annotations
import argparse
import csv
import gc
import json
import logging
import os
import sys
import time
import warnings
from datetime import datetime
from pathlib import Path
import numpy as np
import optuna
import xgboost as xgb
import lightgbm as lgb
from catboost import CatBoostClassifier
from scipy.interpolate import Akima1DInterpolator
from scipy.special import softmax
from sklearn.metrics import f1_score, log_loss, confusion_matrix, roc_auc_score
from sklearn.preprocessing import KBinsDiscretizer
from imblearn.over_sampling import SMOTE, RandomOverSampler
from imblearn.under_sampling import RandomUnderSampler
optuna.logging.set_verbosity(optuna.logging.WARNING)
warnings.filterwarnings("ignore", category=FutureWarning, module="sklearn")
warnings.filterwarnings("ignore", message="X does not have valid feature names")
from features import StatefulFeatureBuilder, feature_order_from_dict
# ===================== Logging Setup =====================
def setup_logging(output_dir: Path, verbose: bool = True):
"""Setup logging to file and console."""
log_file = output_dir / f"training_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
formatter = logging.Formatter(
'%(asctime)s | %(levelname)-8s | %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
file_handler = logging.FileHandler(log_file, encoding='utf-8')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(formatter)
console_handler.setLevel(logging.INFO if verbose else logging.WARNING)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.addHandler(file_handler)
logger.addHandler(console_handler)
return log_file
def log_step(step_name: str, step_num: int = None, total_steps: int = None):
"""Log step header."""
if step_num and total_steps:
header = f"STEP {step_num}/{total_steps}: {step_name}"
else:
header = f"STEP: {step_name}"
logging.info("=" * 70)
logging.info(header)
logging.info("=" * 70)
def log_metrics(metrics: dict, prefix: str = ""):
"""Log metrics dictionary."""
for key, value in metrics.items():
if isinstance(value, float):
logging.info(f"{prefix}{key}: {value:.6f}")
elif isinstance(value, (list, np.ndarray)):
if len(value) <= 10:
logging.info(f"{prefix}{key}: {value}")
else:
logging.info(f"{prefix}{key}: [{value[0]:.4f}, ..., {value[-1]:.4f}] (len={len(value)})")
else:
logging.info(f"{prefix}{key}: {value}")
def log_class_distribution(y: np.ndarray, name: str = ""):
"""Log class distribution with visual bars."""
n_classes = int(y.max() + 1)
counts = np.bincount(y, minlength=n_classes)
total = len(y)
logging.info(f"Class distribution ({name}, n={total}):")
for c in range(n_classes):
pct = 100 * counts[c] / total
bar = "█" * int(pct / 2)
logging.info(f" Class {c}: {counts[c]:7d} ({pct:5.2f}%) {bar}")
def log_model_comparison(results: list):
"""Log model comparison table."""
logging.info("-" * 50)
logging.info("MODEL COMPARISON (F1-macro):")
logging.info("-" * 50)
sorted_results = sorted(results, key=lambda x: x.get('f1_macro', 0), reverse=True)
for i, r in enumerate(sorted_results):
rank = "1st" if i == 0 else "2nd" if i == 1 else "3rd" if i == 2 else " "
name = r.get('name', 'Unknown')
f1 = r.get('f1_macro', 0)
time_s = r.get('training_time', 0)
logging.info(f"{rank} {name:20s}: F1={f1:.4f}, Time={time_s:.1f}s")
logging.info("-" * 50)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Train ensemble model for Overnight Finance Challenge")
parser.add_argument("--train-path", type=Path, default=Path("../data/train.csv"))
parser.add_argument("--output-dir", type=Path, default=Path("./"))
parser.add_argument("--val-fraction", type=float, default=0.1, help="Validation set fraction")
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--use-gpu", action="store_true", help="Enable GPU (CUDA/OpenCL)")
parser.add_argument("--n-estimators", type=int, default=1000, help="Max boosting rounds")
parser.add_argument("--learning-rate", type=float, default=0.01)
parser.add_argument("--xgb-weight", type=float, default=0.4, help="XGBoost weight in ensemble")
parser.add_argument("--cat-weight", type=float, default=0.3, help="CatBoost weight in ensemble")
parser.add_argument("--lgb-weight", type=float, default=0.3, help="LightGBM weight in ensemble")
parser.add_argument("--optuna-trials", type=int, default=60, help="Optuna HPO trials (0=disable)")
parser.add_argument("--oversample", action="store_true", default=True, help="Enable SMOTE for rare classes")
parser.add_argument("--no-oversample", dest="oversample", action="store_false")
parser.add_argument("--oversample-ratio", type=float, default=0.15, help="Target ratio for rare classes")
parser.add_argument("--downsample", action="store_true", default=True, help="Enable downsampling of majority class")
parser.add_argument("--no-downsample", dest="downsample", action="store_false")
parser.add_argument("--downsample-ratio", type=float, default=0.3, help="Downsample ratio for class 0")
parser.add_argument("--focal-loss", action="store_true", help="Use Focal Loss for XGBoost")
parser.add_argument("--focal-gamma", type=float, default=2.0, help="Focal Loss gamma parameter")
return parser.parse_args()
def stream_build_features(csv_path: Path) -> tuple[np.ndarray, np.ndarray, list[str]]:
"""Stream-read CSV, build features row-by-row, return X, y, feature_cols."""
builder = StatefulFeatureBuilder()
X_rows = []
y_rows = []
feature_cols: list[str] = []
print(f"[train] Stream reading CSV: {csv_path}")
with csv_path.open("r") as f:
reader = csv.DictReader(f)
for idx, row in enumerate(reader):
numeric_row = {k: float(v) for k, v in row.items() if k not in ("y",)}
feats = builder.build_row(numeric_row)
if not feature_cols:
feature_cols = feature_order_from_dict(feats)
X_rows.append([feats[c] for c in feature_cols])
y_rows.append(int(row["y"]))
if (idx + 1) % 200000 == 0:
print(f"[train] Processed {idx + 1} rows...")
X = np.array(X_rows, dtype=np.float32)
y = np.array(y_rows, dtype=np.int32)
# Free memory
del X_rows, y_rows
gc.collect()
return X, y, feature_cols
# ===================== Custom Focal Loss for XGBoost =====================
def softmax_numpy(x):
"""Softmax for multiclass classification."""
e_x = np.exp(x - np.max(x, axis=1, keepdims=True))
return e_x / e_x.sum(axis=1, keepdims=True)
def focal_loss_multiclass(y_true, y_pred_raw, gamma=2.0, alpha=None, n_classes=5):
"""
Focal Loss for multiclass classification.
FL(p_t) = -alpha_t * (1 - p_t)^gamma * log(p_t)
Args:
y_true: true labels
y_pred_raw: raw logits (n_samples * n_classes)
gamma: focusing parameter (typically 2.0)
alpha: class weights (None = equal)
n_classes: number of classes
"""
n_samples = len(y_true)
y_pred_raw = y_pred_raw.reshape(n_samples, n_classes)
# Softmax
probs = softmax_numpy(y_pred_raw)
probs = np.clip(probs, 1e-7, 1 - 1e-7)
# One-hot
y_onehot = np.zeros((n_samples, n_classes))
y_onehot[np.arange(n_samples), y_true.astype(int)] = 1
# p_t = probability of correct class
pt = np.sum(probs * y_onehot, axis=1, keepdims=True)
# Focal weight: (1 - p_t)^gamma
focal_weight = (1 - pt) ** gamma
# Alpha weights (inverse frequency weighting)
if alpha is None:
class_counts = np.bincount(y_true.astype(int), minlength=n_classes)
alpha = n_samples / (n_classes * class_counts + 1)
# Extra boost for rare classes 3 and 4
alpha[3] *= 2.0
alpha[4] *= 2.0
alpha_t = alpha[y_true.astype(int)].reshape(-1, 1)
# Gradient: focal_weight * alpha * (probs - y_onehot)
grad = focal_weight * alpha_t * (probs - y_onehot)
# Hessian: simplified for stability
hess = focal_weight * alpha_t * probs * (1 - probs)
hess = np.clip(hess, 1e-7, None)
# XGBoost >= 2.1 requires shape (n_samples, n_classes)
return grad, hess
def f1_macro_objective(y_true, y_pred_raw, n_classes=5):
"""Custom objective for XGBoost approximating F1-macro with focal-like weighting."""
n_samples = len(y_true)
y_pred_raw = y_pred_raw.reshape(n_samples, n_classes)
# Softmax to get probabilities
probs = softmax_numpy(y_pred_raw)
probs = np.clip(probs, 1e-7, 1 - 1e-7)
# One-hot encoding
y_onehot = np.zeros((n_samples, n_classes))
y_onehot[np.arange(n_samples), y_true.astype(int)] = 1
# Weights for rare classes (3 and 4)
class_counts = np.bincount(y_true.astype(int), minlength=n_classes)
class_weights = n_samples / (n_classes * class_counts + 1)
# Boost weights for rare classes
class_weights[3] *= 3.0
class_weights[4] *= 3.0
# Focal-like weighting
gamma = 2.0
pt = np.sum(probs * y_onehot, axis=1)
focal_weight = (1 - pt) ** gamma
# Gradient: (probs - y_onehot) * weights
sample_weights = class_weights[y_true.astype(int)] * focal_weight
grad = (probs - y_onehot) * sample_weights.reshape(-1, 1)
# Hessian: probs * (1 - probs) * weights
hess = probs * (1 - probs) * sample_weights.reshape(-1, 1)
hess = np.clip(hess, 1e-7, None)
# XGBoost >= 2.1 requires shape (n_samples, n_classes)
return grad, hess
def f1_macro_eval(y_true, y_pred_raw, n_classes=5):
"""F1-macro evaluation metric for XGBoost."""
n_samples = len(y_true)
y_pred_raw = y_pred_raw.reshape(n_samples, n_classes)
y_pred = np.argmax(y_pred_raw, axis=1)
score = f1_score(y_true, y_pred, average='macro')
return 'f1_macro', -score # Negative because XGBoost minimizes
# ===================== TargetExpandingMeanEncoder =====================
class TargetExpandingMeanEncoder:
"""
Target Encoding using strictly past values (expanding mean).
Bins features and computes target mean per bin using only past data.
"""
def __init__(self, smoothing: float = 10.0, n_bins: int = 10):
self.smoothing = smoothing
self.n_bins = n_bins
self.bin_edges = {}
self.global_mean = None
self.encoding_maps = {}
def fit_transform(self, X: np.ndarray, y: np.ndarray, feature_names: list,
features_to_encode: list) -> tuple:
"""
Fit and transform with expanding mean (strictly past data).
Returns:
X_new: array with new features
new_feature_names: names of new features
"""
self.global_mean = float(np.mean(y))
new_features = []
new_names = []
for feat_name in features_to_encode:
if feat_name not in feature_names:
continue
feat_idx = feature_names.index(feat_name)
feat_values = X[:, feat_idx]
# Bin the feature
valid_mask = ~np.isnan(feat_values)
if valid_mask.sum() < 100:
continue
percentiles = np.linspace(0, 100, self.n_bins + 1)
edges = np.percentile(feat_values[valid_mask], percentiles)
edges = np.unique(edges)
if len(edges) < 3:
continue
self.bin_edges[feat_name] = edges
# Convert to bins
bins = np.digitize(feat_values, edges[1:-1])
# Expanding mean encoding (strictly past data)
encoded = np.zeros(len(y), dtype=np.float32)
bin_sums = {}
bin_counts = {}
for i in range(len(y)):
b = int(bins[i])
# Use statistics up to current point
if b in bin_counts and bin_counts[b] > 0:
prior_mean = bin_sums[b] / bin_counts[b]
n = bin_counts[b]
encoded[i] = (n * prior_mean + self.smoothing * self.global_mean) / (n + self.smoothing)
else:
encoded[i] = self.global_mean
# Update statistics AFTER computing
if b not in bin_sums:
bin_sums[b] = 0.0
bin_counts[b] = 0
bin_sums[b] += y[i]
bin_counts[b] += 1
# Save final statistics for inference
self.encoding_maps[feat_name] = {}
for b in bin_counts:
if bin_counts[b] > 0:
mean_val = bin_sums[b] / bin_counts[b]
n = bin_counts[b]
self.encoding_maps[feat_name][int(b)] = (n * mean_val + self.smoothing * self.global_mean) / (n + self.smoothing)
else:
self.encoding_maps[feat_name][int(b)] = self.global_mean
new_features.append(encoded)
new_names.append(f"{feat_name}_te")
print(f"[TargetEnc] {feat_name}: {len(np.unique(bins))} bins, mean={np.mean(encoded):.4f}")
if new_features:
X_new = np.column_stack([X] + new_features)
new_feature_names = feature_names + new_names
else:
X_new = X
new_feature_names = feature_names
return X_new, new_feature_names
def get_state(self) -> dict:
"""Save state for inference."""
return {
'smoothing': self.smoothing,
'n_bins': self.n_bins,
'global_mean': self.global_mean,
'bin_edges': {k: v.tolist() for k, v in self.bin_edges.items()},
'encoding_maps': {k: {str(kk): vv for kk, vv in v.items()} for k, v in self.encoding_maps.items()}
}
# ===================== RareClassBooster =====================
class RareClassBooster:
"""
Probability calibrator for improving rare class classification.
Uses signal from binary classifier (common vs rare).
"""
def __init__(self, rare_classes=[3, 4], common_classes=[0, 1, 2]):
self.rare_classes = rare_classes
self.common_classes = common_classes
self.alpha = None # weight of model2 signal
self.beta = None # boost factor for rare classes
def fit(self, y_true, probs_model1, probs_model2,
alpha_range=(0.01, 50), beta_range=(0.01, 50),
n_trials=200):
"""
Find optimal parameters with Optuna.
probs_model1: (n_samples, 5) - main model probabilities
probs_model2: (n_samples, 2) - binary probs [common, rare]
"""
def objective(trial):
alpha = trial.suggest_float('alpha', alpha_range[0], alpha_range[1], log=True)
beta = trial.suggest_float('beta', beta_range[0], beta_range[1], log=True)
adjusted_probs = self._adjust_probs(probs_model1, probs_model2, alpha, beta)
y_pred = np.argmax(adjusted_probs, axis=1)
return f1_score(y_true, y_pred, average='macro')
study = optuna.create_study(
direction='maximize',
sampler=optuna.samplers.TPESampler(seed=42)
)
study.optimize(objective, n_trials=n_trials, show_progress_bar=True)
self.alpha = study.best_params['alpha']
self.beta = study.best_params['beta']
print(f"[RareBoost] Best params: alpha={self.alpha:.4f}, beta={self.beta:.4f}")
print(f"[RareBoost] F1-macro: {study.best_value:.4f}")
return self
def _adjust_probs(self, probs_model1, probs_model2, alpha, beta):
"""Adjust probabilities using rare class signal."""
adjusted = probs_model1.copy()
# Probability that sample is rare class (from model2)
rare_signal = probs_model2[:, 1].reshape(-1, 1)
# Mask for rare classes
rare_mask = np.zeros_like(adjusted)
for rare_cls in self.rare_classes:
rare_mask[:, rare_cls] = 1
# Boost rare classes based on model2 signal
boost_factor = 1 + alpha * rare_signal * rare_mask
adjusted = adjusted * boost_factor
# Additional boost for rare classes
for rare_cls in self.rare_classes:
adjusted[:, rare_cls] *= beta
# Normalize
adjusted = adjusted / adjusted.sum(axis=1, keepdims=True)
return adjusted
def predict_proba(self, probs_model1, probs_model2):
if self.alpha is None or self.beta is None:
raise ValueError("Model not fitted. Call fit() first.")
return self._adjust_probs(probs_model1, probs_model2, self.alpha, self.beta)
def predict(self, probs_model1, probs_model2):
probs = self.predict_proba(probs_model1, probs_model2)
return np.argmax(probs, axis=1)
# ===================== DiagonalTemperatureCalibrator =====================
class DiagonalTemperatureCalibrator:
"""Temperature calibration with per-class temperatures."""
def __init__(self, n_trials: int = 100):
self.temps = None
self.thresholds = None
self.n_classes = None
self.n_trials = n_trials
def fit(self, probs: np.ndarray, y_true: np.ndarray):
self.n_classes = probs.shape[1]
log_probs = np.log(np.clip(probs, 1e-15, 1.0))
best_temps = np.ones(self.n_classes)
best_score = -1
print("[DiagTemp] Optimizing per-class temperatures...")
for _ in range(self.n_trials):
temps = np.random.uniform(0.5, 5.0, self.n_classes)
scaled_logits = log_probs / temps
scaled_probs = softmax(scaled_logits, axis=1)
preds = np.argmax(scaled_probs, axis=1)
score = f1_score(y_true, preds, average='macro')
if score > best_score:
best_score = score
best_temps = temps.copy()
self.temps = best_temps
print(f"[DiagTemp] Best temps: {self.temps}, F1={best_score:.4f}")
calibrated = self.predict_proba(probs)
self.thresholds = self._optimize_thresholds(calibrated, y_true)
return self
def _optimize_thresholds(self, probs: np.ndarray, y_true: np.ndarray) -> np.ndarray:
print("[DiagTemp] Optimizing thresholds...")
best_thresholds = np.zeros(self.n_classes)
best_f1 = f1_score(y_true, probs.argmax(axis=1), average='macro')
for _ in range(self.n_trials):
thresholds = np.random.uniform(-0.3, 0.3, self.n_classes)
adjusted = probs - thresholds
preds = np.argmax(adjusted, axis=1)
score = f1_score(y_true, preds, average='macro')
if score > best_f1:
best_f1 = score
best_thresholds = thresholds.copy()
print(f"[DiagTemp] Best thresholds: {best_thresholds}, F1={best_f1:.4f}")
return best_thresholds
def predict_proba(self, probs: np.ndarray) -> np.ndarray:
log_probs = np.log(np.clip(probs, 1e-15, 1.0))
scaled_logits = log_probs / self.temps
return softmax(scaled_logits, axis=1)
def predict(self, probs: np.ndarray) -> np.ndarray:
calibrated = self.predict_proba(probs)
adjusted = calibrated - self.thresholds
return np.argmax(adjusted, axis=1)
# ===================== ThresholdOptimizerOVR =====================
class ThresholdOptimizerOVR:
"""One-vs-Rest threshold optimization for F1-macro."""
def __init__(self, n_steps: int = 100, n_iters: int = 5):
self.n_steps = n_steps
self.n_iters = n_iters
self.thresholds = None
def fit(self, probs: np.ndarray, y_true: np.ndarray):
n_classes = probs.shape[1]
self.thresholds = np.full(n_classes, 1.0 / n_classes)
best_f1 = f1_score(y_true, np.argmax(probs, axis=1), average='macro')
print(f"[OVR] Initial F1={best_f1:.4f}, optimizing thresholds...")
for iteration in range(self.n_iters):
improved = False
for c in range(n_classes):
min_prob = probs[:, c].min()
max_prob = probs[:, c].max()
threshold_range = np.linspace(min_prob, max_prob, self.n_steps)
best_t_for_c = self.thresholds[c]
for t in threshold_range:
temp_thresholds = self.thresholds.copy()
temp_thresholds[c] = t
preds = self._predict_with_thresholds(probs, temp_thresholds)
f1 = f1_score(y_true, preds, average='macro')
if f1 > best_f1:
best_f1 = f1
best_t_for_c = t
improved = True
self.thresholds[c] = best_t_for_c
if not improved:
break
print(f"[OVR] Final F1={best_f1:.4f}, thresholds={self.thresholds}")
return self
def _predict_with_thresholds(self, probs: np.ndarray, thresholds: np.ndarray) -> np.ndarray:
adjusted = probs.copy()
for c in range(len(thresholds)):
adjusted[:, c] = np.where(probs[:, c] >= thresholds[c], probs[:, c], -np.inf)
mask = np.all(adjusted == -np.inf, axis=1)
adjusted[mask] = probs[mask]
return np.argmax(adjusted, axis=1)
def predict(self, probs: np.ndarray) -> np.ndarray:
return self._predict_with_thresholds(probs, self.thresholds)
# ===================== AKIMA Calibration =====================
def akima_calibration(probs: np.ndarray, y_true: np.ndarray) -> np.ndarray:
"""AKIMA interpolation-based calibration per class."""
calibrated = np.zeros_like(probs)
n_classes = probs.shape[1]
for c in range(n_classes):
true = (y_true == c).astype(int)
bins = np.linspace(0, 1, 15)
bin_ids = np.digitize(probs[:, c], bins) - 1
bin_centers = []
frac_pos = []
for b in range(len(bins) - 1):
mask = bin_ids == b
if mask.sum() == 0:
continue
bin_centers.append((bins[b] + bins[b + 1]) / 2)
frac_pos.append(true[mask].mean())
if len(bin_centers) < 4:
calibrated[:, c] = probs[:, c]
continue
ak = Akima1DInterpolator(bin_centers, frac_pos)
interp_vals = ak(probs[:, c])
interp_vals = np.nan_to_num(interp_vals, nan=probs[:, c])
calibrated[:, c] = np.clip(interp_vals, 0.0, 1.0)
calibrated = np.nan_to_num(calibrated, nan=1e-15, posinf=1.0, neginf=1e-15)
calibrated = np.clip(calibrated, 1e-15, 1.0)
row_sums = calibrated.sum(axis=1, keepdims=True)
row_sums = np.where(row_sums == 0, 1.0, row_sums)
return calibrated / row_sums
def clean_probs(probs: np.ndarray, n_classes: int) -> np.ndarray:
"""Clean and normalize probabilities."""
probs = np.asarray(probs, dtype=np.float64)
probs = probs.reshape(-1, n_classes)
probs = np.nan_to_num(probs, nan=1e-15, posinf=1.0, neginf=1e-15)
probs = np.clip(probs, 1e-15, 1.0)
row_sums = probs.sum(axis=1, keepdims=True)
row_sums = np.where(row_sums == 0, 1.0, row_sums)
return probs / row_sums
def resample_classes(X: np.ndarray, y: np.ndarray,
rare_classes: list = [3, 4],
target_ratio: float = 0.15,
downsample_majority: bool = True,
downsample_ratio: float = 0.3,
seed: int = 42) -> tuple:
"""
Combined resampling: Downsampling + SMOTE.
1. Downsample majority class (0) to downsample_ratio of max
2. SMOTE for rare classes (3, 4) up to target_ratio of max
CRITICAL: After resampling, calibration must use ONLY original data!
Args:
X: features
y: target
rare_classes: classes to oversample
target_ratio: target ratio of rare classes to majority
downsample_majority: whether to downsample class 0
downsample_ratio: fraction to reduce class 0 to
seed: random seed
Returns:
X_aug, y_aug: augmented data
n_original: original dataset size (for calibration!)
"""
n_original = len(y)
class_counts = np.bincount(y)
n_classes = len(class_counts)
print(f"[Resample] Original class distribution: {class_counts}")
X_work, y_work = X, y
# ===== STEP 1: Downsample majority class =====
if downsample_majority and class_counts[0] > class_counts[1:].max() * 2:
# Target count for class 0: mean of classes 1,2
target_majority = int(np.mean(class_counts[1:3]) * (1 + downsample_ratio))
undersample_strategy = {0: target_majority}
print(f"[Resample] Downsampling Class 0: {class_counts[0]} -> {target_majority}")
rus = RandomUnderSampler(
sampling_strategy=undersample_strategy,
random_state=seed
)
X_work, y_work = rus.fit_resample(X_work, y_work)
class_counts_after_down = np.bincount(y_work)
print(f"[Resample] After downsampling: {class_counts_after_down}")
# ===== STEP 2: SMOTE for rare classes =====
class_counts_current = np.bincount(y_work)
max_count = class_counts_current.max()
target_count = int(max_count * target_ratio)
# Strategy: increase only rare classes
sampling_strategy = {}
for cls in rare_classes:
if cls < n_classes and class_counts_current[cls] < target_count:
sampling_strategy[cls] = max(target_count, class_counts_current[cls] * 3) # min x3
if sampling_strategy:
print(f"[Resample] SMOTE strategy: {sampling_strategy}")
try:
# Try SMOTE first
smote = SMOTE(
sampling_strategy=sampling_strategy,
random_state=seed,
k_neighbors=min(5, min(class_counts_current[list(sampling_strategy.keys())]) - 1)
)
X_aug, y_aug = smote.fit_resample(X_work, y_work)
print(f"[Resample] SMOTE: {len(y_work)} -> {len(y_aug)} samples")
except ValueError as e:
# Fallback to RandomOverSampler if SMOTE fails
print(f"[Resample] SMOTE failed ({e}), using RandomOverSampler")
ros = RandomOverSampler(sampling_strategy=sampling_strategy, random_state=seed)
X_aug, y_aug = ros.fit_resample(X_work, y_work)
print(f"[Resample] RandomOverSampler: {len(y_work)} -> {len(y_aug)} samples")
else:
X_aug, y_aug = X_work, y_work
print("[Resample] No oversampling needed")
# Free intermediate memory
del X_work, y_work
gc.collect()
aug_counts = np.bincount(y_aug)
print(f"[Resample] Augmented class distribution: {aug_counts}")
return X_aug, y_aug, n_original
def optuna_xgb_objective(trial, X_train, y_train, X_val, y_val, use_gpu, n_classes, seed):
"""Optuna objective for XGBoost hyperparameter optimization.
Note: We don't use XGBoostPruningCallback because:
- Study direction is 'maximize' (F1)
- XGBoost monitors 'mlogloss' which should be minimized
- This causes direction conflict
Instead, we use early_stopping_rounds which effectively prunes bad trials.
"""
params = {
"objective": "multi:softprob",
"num_class": n_classes,
"tree_method": "hist",
"eval_metric": "mlogloss",
"random_state": seed,
"early_stopping_rounds": 50,
"n_estimators": 500, # Reduced for HPO speed
# Optimized parameters
"learning_rate": trial.suggest_float("learning_rate", 0.005, 0.1, log=True),
"max_depth": trial.suggest_int("max_depth", 3, 8),
"min_child_weight": trial.suggest_float("min_child_weight", 1, 50, log=True),
"subsample": trial.suggest_float("subsample", 0.6, 1.0),
"colsample_bytree": trial.suggest_float("colsample_bytree", 0.5, 1.0),
"colsample_bylevel": trial.suggest_float("colsample_bylevel", 0.5, 1.0),
"reg_alpha": trial.suggest_float("reg_alpha", 1e-3, 10.0, log=True),
"reg_lambda": trial.suggest_float("reg_lambda", 1e-3, 10.0, log=True),
"gamma": trial.suggest_float("gamma", 1e-4, 1.0, log=True),
"max_delta_step": trial.suggest_int("max_delta_step", 0, 5),
}
if use_gpu:
params["device"] = "cuda"
else:
params["device"] = "cpu"
params["n_jobs"] = os.cpu_count() or -1
model = xgb.XGBClassifier(**params)
model.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose=False)
# Predictions
probs = model.predict_proba(X_val)
preds = probs.argmax(axis=1)
f1 = f1_score(y_val, preds, average='macro')
return f1
def optuna_catboost_objective(trial, X_train, y_train, X_val, y_val, use_gpu, n_classes, seed):
"""Optuna objective for CatBoost hyperparameter optimization.
Note: We don't use CatBoostPruningCallback because:
- Study direction is 'maximize' (F1)
- CatBoost monitors 'MultiClass' loss which should be minimized
- This causes direction conflict
Instead, we use od_type='Iter' with od_wait which effectively prunes bad trials.
"""
params = {
"iterations": 300, # Reduced for HPO speed
"random_seed": seed,
"loss_function": "MultiClass",
"eval_metric": "MultiClass",
"od_type": "Iter", # Overfitting detector acts as implicit pruning
"od_wait": 50,
"verbose": 0,
# Optimized parameters
"learning_rate": trial.suggest_float("learning_rate", 0.01, 0.15, log=True),
"depth": trial.suggest_int("depth", 4, 10),
"l2_leaf_reg": trial.suggest_float("l2_leaf_reg", 1.0, 50.0, log=True),
"bagging_temperature": trial.suggest_float("bagging_temperature", 0.0, 1.0),
"random_strength": trial.suggest_float("random_strength", 0.0, 10.0),
"border_count": trial.suggest_int("border_count", 32, 255),
}
if use_gpu:
params["task_type"] = "GPU"
params["devices"] = "0"
else:
params["task_type"] = "CPU"
params["thread_count"] = os.cpu_count() or -1
model = CatBoostClassifier(**params)
model.fit(
X_train, y_train,
eval_set=(X_val, y_val),
verbose=0
)
probs = model.predict_proba(X_val)
preds = probs.argmax(axis=1)
f1 = f1_score(y_val, preds, average='macro')
return f1
def optuna_lgb_objective(trial, X_train, y_train, X_val, y_val, use_gpu, n_classes, seed):
"""Optuna objective for LightGBM hyperparameter optimization.
Note: We don't use LightGBMPruningCallback because:
- Study direction is 'maximize' (F1)
- LightGBM monitors 'multi_logloss' which should be minimized
- This causes direction conflict
Instead, we use early_stopping which effectively prunes bad trials.
"""
max_depth = trial.suggest_int("max_depth", 4, 10)
# num_leaves should be <= 2^max_depth for stability
max_leaves = min(127, 2 ** max_depth - 1)
num_leaves = trial.suggest_int("num_leaves", 15, max_leaves)
params = {
"objective": "multiclass",
"num_class": n_classes,
"n_estimators": 300, # Reduced for HPO speed
"random_state": seed,
"verbose": -1,
"max_depth": max_depth,
"num_leaves": num_leaves,
# Optimized parameters
"learning_rate": trial.suggest_float("learning_rate", 0.01, 0.15, log=True),
"min_child_samples": trial.suggest_int("min_child_samples", 50, 200), # Increased for GPU stability
"min_data_in_leaf": trial.suggest_int("min_data_in_leaf", 100, 500), # Critical for GPU
"subsample": trial.suggest_float("subsample", 0.7, 1.0),
"colsample_bytree": trial.suggest_float("colsample_bytree", 0.6, 1.0),
"reg_alpha": trial.suggest_float("reg_alpha", 1e-2, 10.0, log=True),
"reg_lambda": trial.suggest_float("reg_lambda", 1e-2, 10.0, log=True),
}
# LightGBM: GPU (OpenCL) or CPU
if use_gpu:
params["device"] = "gpu"
params["gpu_use_dp"] = False
else:
params["device"] = "cpu"
params["n_jobs"] = os.cpu_count() or -1
model = lgb.LGBMClassifier(**params)
model.fit(
X_train, y_train,
eval_set=[(X_val, y_val)],
callbacks=[
lgb.early_stopping(stopping_rounds=50, verbose=False)
]
)
probs = model.predict_proba(X_val)
preds = probs.argmax(axis=1)
f1 = f1_score(y_val, preds, average='macro')
return f1
def run_optuna_hpo(X_train, y_train, X_val, y_val, use_gpu, n_classes, seed, n_trials):
"""Run Optuna HPO for all boosting models with pruning and error handling."""
import warnings
# Suppress Optuna experimental warnings (multivariate TPE is stable in practice)
warnings.filterwarnings("ignore", message=".*multivariate.*")
warnings.filterwarnings("ignore", message=".*ExperimentalWarning.*")
# Suppress XGBoost device mismatch warning (predict uses CPU which is fine)
warnings.filterwarnings("ignore", message=".*Falling back to prediction using DMatrix.*")
best_params = {"xgb": {}, "cat": {}, "lgb": {}}
trials_per_model = max(10, n_trials // 3) # Split trials between models
# Optimized sampler settings
sampler_kwargs = {
"seed": seed,
"n_startup_trials": 10, # Random trials before TPE
"multivariate": True, # Better correlated parameter search
"warn_independent_sampling": False, # Suppress warnings for dynamic search spaces (num_leaves depends on max_depth)
}
# Optimized pruner: prune unpromising trials early
pruner = optuna.pruners.MedianPruner(
n_startup_trials=5, # Trials before pruning starts
n_warmup_steps=20, # Steps before pruning within trial
interval_steps=10, # Check every N steps
)
# LightGBM HPO (first to test GPU)
print(f"\n{'='*70}")
print(f"[Optuna LGB] Starting HPO with {trials_per_model} trials (GPU test)...")
print(f"{'='*70}")
study_lgb = optuna.create_study(
direction='maximize',
sampler=optuna.samplers.TPESampler(**sampler_kwargs),
pruner=pruner
)
study_lgb.optimize(
lambda trial: optuna_lgb_objective(trial, X_train, y_train, X_val, y_val, use_gpu, n_classes, seed),
n_trials=trials_per_model,
show_progress_bar=True,
n_jobs=1,
catch=(Exception,), # Handle crashes gracefully
gc_after_trial=True # Memory cleanup
)
best_params["lgb"] = study_lgb.best_params if study_lgb.best_trial else {}
lgb_best = study_lgb.best_value if study_lgb.best_trial else 0.0
print(f"[Optuna LGB] Best F1: {lgb_best:.4f}")
# Memory cleanup
gc.collect()
# XGBoost HPO
print(f"\n{'='*70}")
print(f"[Optuna XGB] Starting HPO with {trials_per_model} trials...")
print(f"{'='*70}")
sampler_kwargs["seed"] = seed + 1
study_xgb = optuna.create_study(
direction='maximize',
sampler=optuna.samplers.TPESampler(**sampler_kwargs),
pruner=pruner
)
study_xgb.optimize(
lambda trial: optuna_xgb_objective(trial, X_train, y_train, X_val, y_val, use_gpu, n_classes, seed),
n_trials=trials_per_model,
show_progress_bar=True,
n_jobs=1,
catch=(Exception,),
gc_after_trial=True
)
best_params["xgb"] = study_xgb.best_params if study_xgb.best_trial else {}
xgb_best = study_xgb.best_value if study_xgb.best_trial else 0.0
print(f"[Optuna XGB] Best F1: {xgb_best:.4f}")
# Memory cleanup
gc.collect()
# CatBoost HPO
print(f"\n{'='*70}")
print(f"[Optuna CAT] Starting HPO with {trials_per_model} trials...")
print(f"{'='*70}")
sampler_kwargs["seed"] = seed + 2
study_cat = optuna.create_study(
direction='maximize',
sampler=optuna.samplers.TPESampler(**sampler_kwargs),
pruner=pruner
)
study_cat.optimize(
lambda trial: optuna_catboost_objective(trial, X_train, y_train, X_val, y_val, use_gpu, n_classes, seed),
n_trials=trials_per_model,
show_progress_bar=True,
n_jobs=1,
catch=(Exception,),
gc_after_trial=True
)
best_params["cat"] = study_cat.best_params if study_cat.best_trial else {}
cat_best = study_cat.best_value if study_cat.best_trial else 0.0
print(f"[Optuna CAT] Best F1: {cat_best:.4f}")
# Final cleanup
gc.collect()
print("\n" + "="*70)
print("[Optuna] HPO Complete!")
print("="*70)
print(f"XGB Best F1: {xgb_best:.4f}")
print(f"CAT Best F1: {cat_best:.4f}")
print(f"LGB Best F1: {lgb_best:.4f}")
return best_params
def evaluate_model(name: str, probs: np.ndarray, y_true: np.ndarray, n_classes: int) -> dict:
"""Detailed model evaluation with logging."""
preds = probs.argmax(axis=1)
# Metrics
f1_macro = f1_score(y_true, preds, average='macro')
f1_weighted = f1_score(y_true, preds, average='weighted')