-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_exportable_package.py
More file actions
1677 lines (1451 loc) · 56.5 KB
/
Copy pathcreate_exportable_package.py
File metadata and controls
1677 lines (1451 loc) · 56.5 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 python
# -*- coding: utf-8 -*-
"""
Pacific Classifier - Exportable Package Creation Pipeline.
This module provides the main pipeline for creating exportable classifier
packages from Pacific synthetic data, customized for external users who have
their own datasets with a subset of Pacific study variables.
The pipeline workflow:
1. Load reference Pacific synthetic data (557 variables)
2. Load external user data (subset of variables)
3. Compute variable INTERSECTION (synthetics ∩ external)
4. Filter synthetics to common variables
5. Optional feature reduction
6. Train ensemble classifier on filtered synthetics
7. Create exportable package
The classification system identifies four heart failure subject groups (these are
synthetic-data class labels, not clinical diagnoses):
- healthier: the lower-risk / control-like class
- rEF: named after heart failure with reduced ejection fraction
- pEF1: named after HFpEF subtype 1
- pEF2: named after HFpEF subtype 2
Usage:
python create_exportable_package.py --external_data <path> \\
--output_dir <path> --package_name <name>
Copyright (c) 2025 FEALINX - Pacific Project
Licensed under AGPL-3.0 and CC BY-NC-SA 4.0
See Also
--------
Project documentation: https://github.com/pboutinaud/pacific_classifier
"""
import argparse
import logging
import os
import pickle
import shutil
import sys
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from warnings import simplefilter
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import shap
from matplotlib.backends.backend_pdf import PdfPages
from sklearn.metrics import ConfusionMatrixDisplay, f1_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from tqdm import tqdm
from xgboost import XGBClassifier
# =============================================================================
# Constants
# =============================================================================
# Performance threshold for warning, derived from cross-validation on the real Pacific
# cohort (n=155). The packaged classifier is trained on synthetic data only; this
# threshold is a heuristic and not a measure of real-world or clinical validity.
F1_WARNING_THRESHOLD = 0.7
# Target variable name for classification
TARGET_COLUMN = 'clustername'
# Default hyperparameters for XGBoost, tuned on the real Pacific cohort (n=155).
# The packaged classifier itself is trained on synthetic data only.
DEFAULT_HYPERPARAMETERS = {
'colsample_bylevel': 0.4,
'colsample_bynode': 0.6,
'colsample_bytree': 0.74,
'gamma': 1.88,
'learning_rate': 0.03,
'max_depth': 5,
'reg_alpha': 2.0,
'reg_lambda': 2.0,
'n_estimators': 2000,
'split': 0.33,
}
# Base XGBoost parameters (fixed for all models)
XGBOOST_BASE_PARAMS = {
'device': 'cpu',
'early_stopping_rounds': 100,
'enable_categorical': False,
'eval_metric': 'mlogloss',
'importance_type': 'total_gain',
'objective': 'multi:softmax',
'random_state': 42,
'tree_method': 'hist',
'verbosity': 0,
}
# =============================================================================
# Data I/O Functions
# =============================================================================
def load_dataset_excel(
filepath: Path
) -> Tuple[pd.DataFrame, pd.DataFrame, Dict, set, pd.DataFrame]:
"""
Load dataset from Excel file with standard Pacific format.
The Excel file must contain the following sheets:
- training_datas: Feature matrix with Participant index
- objective_datas: Target labels and metadata
- reverse_dict: Variable to modality mapping
- categorical_features: List of categorical variable names
- variable_hierarchy: Variable importance ranking
Parameters
----------
filepath : Path
Path to the Excel file containing the dataset.
Returns
-------
tuple
(training_datas, objective_datas, reverse_dict,
categorical_features, variable_hierarchy)
Raises
------
FileNotFoundError
If the specified file does not exist.
ValueError
If required sheets are missing from the Excel file.
"""
if not filepath.exists():
raise FileNotFoundError(f"Dataset file not found: {filepath}")
# Load training data (mandatory)
training_datas = pd.read_excel(
filepath, sheet_name='training_datas',
header=0, index_col=0,
converters={"Participant": str},
)
# Load categorical features with fallback (detect from column names with #)
try:
categorical_features = pd.read_excel(
filepath, sheet_name='categorical_features', index_col=0
)
categorical_features = set(categorical_features.index)
except ValueError:
# Detect categorical features from one-hot encoded column names (contain #)
categorical_features = {col for col in training_datas.columns if '#' in col}
# Load objective data with fallback
try:
objective_datas = pd.read_excel(
filepath, sheet_name='objective_datas',
header=0, index_col=0,
converters={"Participant": str},
)
except ValueError:
objective_datas = pd.DataFrame(
columns=["subject_id", "cluster", "clustername",
"is_random", "is_smote"],
index=training_datas.index
)
objective_datas["subject_id"] = training_datas.index
# Load reverse dictionary with fallback
try:
reverse_dict = pd.read_excel(
filepath, sheet_name='reverse_dict', index_col=0
)
reverse_dict = reverse_dict['Modality'].to_dict()
except ValueError:
reverse_dict = {k: "unknown" for k in training_datas.columns}
# Load variable hierarchy with fallback
try:
variable_hierarchy = pd.read_excel(
filepath, sheet_name='variable_hierarchy', index_col=0
)
except ValueError:
variable_hierarchy = pd.DataFrame(
index=training_datas.columns,
columns=["ranking", "modality"]
)
variable_hierarchy["ranking"] = 2
variable_hierarchy["modality"] = "unknown"
return (
training_datas, objective_datas,
reverse_dict, categorical_features, variable_hierarchy
)
def save_dataset_excel(
training_datas: pd.DataFrame,
objective_datas: pd.DataFrame,
reverse_dict: Dict,
categorical_features: set,
variable_hierarchy: pd.DataFrame,
filepath: Path
) -> None:
"""
Save dataset to Excel file with standard Pacific format.
Parameters
----------
training_datas : pd.DataFrame
Feature matrix with Participant index.
objective_datas : pd.DataFrame
Target labels and metadata.
reverse_dict : dict
Variable to modality mapping.
categorical_features : set
Set of categorical variable names.
variable_hierarchy : pd.DataFrame
Variable importance ranking.
filepath : Path
Output file path.
"""
with pd.ExcelWriter(filepath) as writer:
training_datas.to_excel(writer, sheet_name='training_datas')
objective_datas.to_excel(writer, sheet_name='objective_datas')
pd.DataFrame.from_dict(
reverse_dict, orient='index', columns=['Modality']
).to_excel(writer, sheet_name='reverse_dict', index=True)
pd.DataFrame(
list(categorical_features), columns=['variable']
).to_excel(writer, sheet_name='categorical_features', index=False)
variable_hierarchy.to_excel(
writer, sheet_name='variable_hierarchy', index=True
)
# =============================================================================
# Data Processing Functions
# =============================================================================
def punch(
datas: pd.DataFrame,
ratio_punch_col: float = 0.2,
ratio_punch_row: float = 0.2,
rng: np.random.Generator = None
) -> pd.DataFrame:
"""
Introduce missing values (punch holes) in the dataset to improve robustness to missingness.
This function randomly selects a subset of rows and columns, then sets
the intersection cells to NA. Used to train models robust to missing data.
Parameters
----------
datas : pd.DataFrame
Input DataFrame to punch holes in.
ratio_punch_col : float, default=0.2
Proportion of columns to punch per selected row.
ratio_punch_row : float, default=0.2
Proportion of rows to select for punching.
rng : np.random.Generator, optional
Random number generator for reproducibility.
Returns
-------
pd.DataFrame
DataFrame with missing values introduced.
"""
if rng is None:
rng = np.random.default_rng(42)
datas = datas.copy()
n_rows = len(datas)
n_cols = len(datas.columns)
# Select rows to punch
rows_to_punch = rng.choice(
n_rows,
size=int(n_rows * ratio_punch_row),
replace=False
)
rows_to_punch = datas.index[rows_to_punch]
# For each selected row, punch a subset of columns
for row in rows_to_punch:
cols_to_punch = rng.choice(
n_cols,
size=int(n_cols * ratio_punch_col),
replace=False
)
cols_to_punch = datas.columns[cols_to_punch]
for col in cols_to_punch:
datas.loc[row, col] = pd.NA
return datas
def seed_everything(seed: int = 42) -> np.random.Generator:
"""
Set random seeds for reproducibility across all libraries.
Parameters
----------
seed : int, default=42
Random seed value.
Returns
-------
np.random.Generator
Numpy random generator initialized with the seed.
"""
import os
import random
os.environ['PYTHONHASHSEED'] = str(seed)
random.seed(seed)
np.random.seed(seed)
return np.random.default_rng(seed)
# =============================================================================
# Model Training Functions
# =============================================================================
def prepare_hyperparameters(
base_hyperp: Dict,
optimized_hyperp: Dict,
use_synthetic: bool = False
) -> Tuple[Dict, float, bool]:
"""
Merge and process hyperparameters for model training.
Combines base hyperparameters with optimized values, extracting
pipeline-specific parameters (split ratio, punch flag).
Parameters
----------
base_hyperp : dict
Base XGBoost hyperparameters.
optimized_hyperp : dict
Optimized hyperparameters to merge.
use_synthetic : bool, default=False
If True, always enable data punching.
Returns
-------
tuple
(hyperparameters_dict, split_ratio, should_punch)
"""
hyperp = base_hyperp.copy()
hyperp.update(optimized_hyperp)
# Extract pipeline-specific parameters
split = hyperp.pop('split', 0.33)
hyperp.pop('smote', None)
to_punch = hyperp.pop('punch', 0)
to_punch = True if use_synthetic else bool(to_punch)
hyperp.pop('tid', None)
hyperp.pop('loss', None)
# Handle None/NaN values
for key, value in list(hyperp.items()):
if pd.isna(value):
hyperp[key] = None
# XGBoost requires certain parameters to be integers
int_params = ['max_depth', 'n_estimators', 'early_stopping_rounds',
'random_state', 'verbosity', 'n_jobs']
for param in int_params:
if param in hyperp and hyperp[param] is not None:
hyperp[param] = int(hyperp[param])
return hyperp, split, to_punch
def prepare_data(
X: pd.DataFrame,
y: pd.DataFrame,
split: float,
target_col: str,
to_punch: bool = False,
add_random: bool = False,
label_encoder: LabelEncoder = None,
ratio_punch_col: float = 0.1,
ratio_punch_row: float = 0.1,
rng: np.random.Generator = None,
random_state: int = 42
) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame,
np.ndarray, np.ndarray]:
"""
Prepare train/test splits with optional data augmentation.
Parameters
----------
X : pd.DataFrame
Feature matrix.
y : pd.DataFrame
DataFrame containing target column.
split : float
Test set proportion (0-1).
target_col : str
Name of target column in y.
to_punch : bool, default=False
Whether to introduce missing values in training data.
add_random : bool, default=False
Whether to add a random feature for importance baseline.
label_encoder : LabelEncoder, optional
Encoder for target labels.
ratio_punch_col : float, default=0.1
Column punch ratio if to_punch=True.
ratio_punch_row : float, default=0.1
Row punch ratio if to_punch=True.
rng : np.random.Generator, optional
Random number generator.
random_state : int, default=42
Random state for train_test_split.
Returns
-------
tuple
(X_train, X_test, Y_train, Y_test, y_train_encoded, y_test_encoded)
"""
X_train, X_test, Y_train, Y_test = train_test_split(
X, y, stratify=y[target_col], shuffle=True,
test_size=split, random_state=random_state
)
# Punch training data to simulate missing values
if to_punch:
X_train = punch(
X_train,
ratio_punch_col=ratio_punch_col,
ratio_punch_row=ratio_punch_row,
rng=rng
)
# Ensure column alignment
X_test = X_test[X_train.columns].copy()
# Add random column for feature importance baseline
if add_random:
X_train["random"] = np.random.rand(len(X_train)).astype(np.float32)
X_test["random"] = np.random.rand(len(X_test)).astype(np.float32)
# Extract and encode targets
y_train = Y_train[target_col].values
y_test = Y_test[target_col].values
if label_encoder is not None:
y_train = label_encoder.transform(y_train)
y_test = label_encoder.transform(y_test)
return X_train, X_test, Y_train, Y_test, y_train, y_test
def train_model(
X_train: pd.DataFrame,
y_train: np.ndarray,
X_test: pd.DataFrame,
y_test: np.ndarray,
hyperp: Dict
) -> XGBClassifier:
"""
Train XGBoost classifier with early stopping.
Parameters
----------
X_train : pd.DataFrame
Training features.
y_train : np.ndarray
Training labels (encoded).
X_test : pd.DataFrame
Validation features.
y_test : np.ndarray
Validation labels (encoded).
hyperp : dict
XGBoost hyperparameters.
Returns
-------
XGBClassifier
Trained XGBoost model.
"""
xgb = XGBClassifier(**hyperp)
xgb.fit(X_train, y_train, eval_set=[(X_test, y_test)], verbose=False)
return xgb
def evaluate_predictions(
model: XGBClassifier,
X_test: pd.DataFrame,
y_test: np.ndarray,
Y_test: pd.DataFrame,
target_col: str,
label_encoder: LabelEncoder
) -> Tuple[pd.DataFrame, float]:
"""
Generate predictions and calculate performance metrics.
Parameters
----------
model : XGBClassifier
Trained classifier.
X_test : pd.DataFrame
Test features.
y_test : np.ndarray
Test labels (encoded).
Y_test : pd.DataFrame
Test metadata DataFrame.
target_col : str
Name of target column.
label_encoder : LabelEncoder
Encoder for inverse transform.
Returns
-------
tuple
(predictions_dataframe, f1_macro_score)
"""
pred_test = model.predict(X_test)
proba_test = model.predict_proba(X_test)
f1 = f1_score(y_test, pred_test, average='macro')
# Create predictions DataFrame
predicted = Y_test.copy()
predicted['predictions'] = label_encoder.inverse_transform(pred_test)
prob = pd.DataFrame(
proba_test,
index=Y_test.index,
columns=label_encoder.classes_
)
predicted = pd.concat([predicted, prob], axis=1)
return predicted, f1
def process_importances(
shap_values_perfold: List,
current_features: List[str],
class_dict: Dict[int, str],
reverse_dict: Dict[str, str],
variable_hierarchy: pd.DataFrame
) -> Tuple[pd.DataFrame, Dict[str, pd.DataFrame]]:
"""
Process SHAP values into feature importances per class and globally.
Uses mean absolute SHAP values to rank features by their contribution
to model predictions across all classes.
Parameters
----------
shap_values_perfold : list
SHAP values from each cross-validation fold.
current_features : list
List of current feature names.
class_dict : dict
Mapping from encoded class to class name.
reverse_dict : dict
Variable to modality mapping.
variable_hierarchy : pd.DataFrame
Pre-computed variable rankings.
Returns
-------
tuple
(global_importances_df, per_class_importances_dict)
"""
importances_perclass = {}
for encoded_class, class_name in class_dict.items():
importances = []
for i_fold in range(len(shap_values_perfold)):
shap_df = pd.DataFrame(
shap_values_perfold[i_fold][encoded_class].T,
columns=current_features + ["random"]
)
vals = np.abs(shap_df.values).mean(0)
importances.append(
pd.DataFrame(
list(zip(current_features + ["random"], vals)),
columns=['variable', 'importance']
)
)
# Combine and process importances
importances = pd.concat(importances, axis=0)
importances = importances.groupby('variable').mean(
numeric_only=True
).sort_values(by='importance', ascending=False)
importances['modality'] = importances.index.map(reverse_dict)
try:
importances = importances.merge(
variable_hierarchy.drop('modality', axis=1),
how='left', left_index=True, right_index=True
)
except Exception:
importances['ranking'] = 1
importances.reset_index(inplace=True)
importances = importances[['variable', 'modality', 'importance', 'ranking']]
importances_perclass[class_name] = importances
# Calculate global importances (mean across classes)
importances_all = pd.concat(importances_perclass.values(), axis=0)
importances_all = importances_all.groupby('variable').mean(
numeric_only=True
).sort_values(by='importance', ascending=False)
importances_all['modality'] = importances_all.index.map(reverse_dict)
importances_all.reset_index(inplace=True)
importances_all = importances_all[['variable', 'modality', 'importance', 'ranking']]
return importances_all, importances_perclass
def calculate_ensemble_metrics(
total_predictions: List[pd.DataFrame],
objective_data: pd.DataFrame,
target_col: str,
label_encoder: LabelEncoder
) -> Tuple[float, float]:
"""
Calculate performance metrics for voting and probability ensemble methods.
Compares two ensemble strategies:
1. Voting: Each model votes, majority wins
2. Probability: Average probabilities, argmax prediction
Parameters
----------
total_predictions : list
List of prediction DataFrames from each model.
objective_data : pd.DataFrame
Ground truth labels.
target_col : str
Name of target column.
label_encoder : LabelEncoder
Label encoder for class names.
Returns
-------
tuple
(voted_f1_score, probability_f1_score)
"""
df = pd.concat(total_predictions, axis=0)
# Voting ensemble: majority vote across models (group by index = participant)
votes = df.groupby(level=0).agg(
predictions=pd.NamedAgg(
column='predictions',
aggfunc=lambda x: x.value_counts().index[0]
),
count=pd.NamedAgg(column='predictions', aggfunc='count')
)
votes = votes.merge(
objective_data[target_col], how='left',
left_index=True, right_index=True
)
voted_f1 = f1_score(votes[target_col], votes['predictions'], average='macro')
# Probability ensemble: average probabilities, take argmax (group by index)
probas = pd.DataFrame(
df.groupby(level=0)[label_encoder.classes_].mean().idxmax(axis=1),
columns=["probed"]
)
probas = probas.merge(
objective_data[target_col], how='left',
left_index=True, right_index=True
)
probed_f1 = f1_score(probas[target_col], probas['probed'], average='macro')
return voted_f1, probed_f1
# =============================================================================
# Pipeline Steps
# =============================================================================
def step0_validate_inputs(
reference_synthetics_file: Path,
external_data_file: Path,
output_dir: Path,
logger: logging.Logger
) -> Tuple[pd.DataFrame, pd.DataFrame, Dict, set, pd.DataFrame, List[str]]:
"""
Step 0: Validate inputs, load data, and compute variable intersection.
Loads both the reference Pacific synthetic data and the external user data,
then computes the intersection of variables. The reference synthetics are
filtered to only contain variables present in both datasets.
Parameters
----------
reference_synthetics_file : Path
Path to reference Pacific synthetic data Excel file (557 variables).
external_data_file : Path
Path to external user data Excel file (subset of variables).
output_dir : Path
Output directory path.
logger : logging.Logger
Logger instance.
Returns
-------
tuple
(training_datas, objective_datas, reverse_dict, categorical_features,
variable_hierarchy, common_variables)
All components filtered to common variables only.
Raises
------
FileNotFoundError
If any data file does not exist.
ValueError
If data format is invalid or no common variables found.
"""
logger.info("=" * 80)
logger.info("STEP 0: INPUT VALIDATION AND VARIABLE INTERSECTION")
logger.info("=" * 80)
# Check files exist
if not reference_synthetics_file.exists():
raise FileNotFoundError(
f"Reference synthetic data file not found: {reference_synthetics_file}"
)
if not external_data_file.exists():
raise FileNotFoundError(
f"External data file not found: {external_data_file}"
)
# Create output directory
output_dir.mkdir(parents=True, exist_ok=True)
# Load reference synthetic data (full Pacific variables)
logger.info(f"Loading reference synthetics from: {reference_synthetics_file}")
ref_data = load_dataset_excel(reference_synthetics_file)
ref_training, ref_objective, ref_reverse, ref_categorical, ref_hierarchy = ref_data
logger.info(f" Reference data: {len(ref_training)} samples, {len(ref_training.columns)} variables")
# Load external data (user's subset of variables)
logger.info(f"Loading external data from: {external_data_file}")
ext_data = load_dataset_excel(external_data_file)
ext_training, _, _, _, _ = ext_data
logger.info(f" External data: {len(ext_training)} samples, {len(ext_training.columns)} variables")
# Compute variable intersection
ref_vars = set(ref_training.columns)
ext_vars = set(ext_training.columns)
common_vars = ref_vars.intersection(ext_vars)
common_vars_list = sorted(list(common_vars))
logger.info(f"\nVariable intersection:")
logger.info(f" Reference variables: {len(ref_vars)}")
logger.info(f" External variables: {len(ext_vars)}")
logger.info(f" Common variables: {len(common_vars)}")
if len(common_vars) == 0:
raise ValueError(
"No common variables found between reference synthetics and external data. "
"Please verify variable naming consistency."
)
# Log variables only in one dataset
ref_only = ref_vars - common_vars
ext_only = ext_vars - common_vars
if ref_only:
logger.info(f" Variables only in reference (not used): {len(ref_only)}")
if ext_only:
logger.warning(f" Variables only in external (ignored): {len(ext_only)}")
if len(ext_only) <= 10:
logger.warning(f" Ignored variables: {sorted(ext_only)}")
# Filter reference data to common variables only
logger.info(f"\nFiltering reference synthetics to {len(common_vars)} common variables...")
training_filtered = ref_training[common_vars_list].copy()
reverse_filtered = {k: v for k, v in ref_reverse.items() if k in common_vars}
categorical_filtered = ref_categorical.intersection(common_vars)
hierarchy_filtered = ref_hierarchy.loc[
ref_hierarchy.index.isin(common_vars)
].copy() if len(common_vars) > 0 else ref_hierarchy.iloc[:0]
logger.info(f"Filtered data: {len(training_filtered)} samples, {len(training_filtered.columns)} features")
logger.info(f"Target distribution:\n{ref_objective[TARGET_COLUMN].value_counts()}")
# Validate required columns
if TARGET_COLUMN not in ref_objective.columns:
raise ValueError(f"Target column '{TARGET_COLUMN}' not found in objective_datas")
# Save intersection report
intersection_report = output_dir / "variable_intersection_report.txt"
with open(intersection_report, 'w') as f:
f.write("VARIABLE INTERSECTION REPORT\n")
f.write("=" * 60 + "\n\n")
f.write(f"Reference file: {reference_synthetics_file}\n")
f.write(f"External file: {external_data_file}\n\n")
f.write(f"Reference variables: {len(ref_vars)}\n")
f.write(f"External variables: {len(ext_vars)}\n")
f.write(f"Common variables: {len(common_vars)}\n\n")
f.write("COMMON VARIABLES:\n")
for v in common_vars_list:
f.write(f" {v}\n")
if ext_only:
f.write(f"\nEXTERNAL-ONLY VARIABLES (ignored):\n")
for v in sorted(ext_only):
f.write(f" {v}\n")
logger.info(f"Intersection report saved to: {intersection_report}")
return (training_filtered, ref_objective, reverse_filtered,
categorical_filtered, hierarchy_filtered, common_vars_list)
def step1_feature_reduction(
training_datas: pd.DataFrame,
objective_datas: pd.DataFrame,
reverse_dict: Dict,
categorical_features: set,
variable_hierarchy: pd.DataFrame,
hyperparameters: pd.DataFrame,
reduction_dir: Path,
logger: logging.Logger,
reduce_rounds: int = 50,
keep_most_important_ratio: float = 0.66,
max_ranking_threshold: int = 6,
n_folds: int = 1,
hyperps_top: int = 25,
ratio_punch_col: float = 0.1,
ratio_punch_row: float = 0.1,
rng: np.random.Generator = None
) -> Tuple[List[str], pd.DataFrame]:
"""
Step 1: Iterative feature reduction using SHAP-based importance.
Performs iterative feature elimination based on SHAP importance values.
Features with importance below a random baseline or with low ranking
are progressively removed.
Parameters
----------
training_datas : pd.DataFrame
Training feature matrix.
objective_datas : pd.DataFrame
Objective data with target column.
reverse_dict : dict
Variable to modality mapping.
categorical_features : set
Set of categorical features.
variable_hierarchy : pd.DataFrame
Variable importance ranking.
hyperparameters : pd.DataFrame
Hyperparameter sets to sample from.
reduction_dir : Path
Directory to save reduction outputs.
logger : logging.Logger
Logger instance.
reduce_rounds : int, default=50
Maximum reduction iterations.
keep_most_important_ratio : float, default=0.66
Proportion of top features to always keep.
max_ranking_threshold : int, default=6
Maximum ranking threshold for removal.
n_folds : int, default=1
Number of cross-validation folds.
hyperps_top : int, default=25
Number of top hyperparameter sets to sample from.
ratio_punch_col : float, default=0.1
Column punch ratio.
ratio_punch_row : float, default=0.1
Row punch ratio.
rng : np.random.Generator, optional
Random generator.
Returns
-------
tuple
(final_feature_list, f1_scores_dataframe)
"""
logger.info("\n" + "=" * 80)
logger.info("STEP 1: FEATURE REDUCTION")
logger.info("=" * 80)
reduction_dir.mkdir(parents=True, exist_ok=True)
if rng is None:
rng = np.random.default_rng(42)
# Initialize label encoder
le_reduce = LabelEncoder()
le_reduce.fit(objective_datas[TARGET_COLUMN])
class_names = le_reduce.classes_
class_dict = {i: cl for i, cl in enumerate(class_names)}
# Base hyperparameters
hyperp_base = XGBOOST_BASE_PARAMS.copy()
hyperp_base['num_class'] = len(class_names)
hyperp_base['n_estimators'] = 1000
f1_scores = []
current_features = training_datas.columns.tolist()
for reduce_round in tqdm(range(reduce_rounds), desc="Feature Reduction"):
logger.info(f"\nReduction round {reduce_round}, features: {len(current_features)}")
round_output_dir = reduction_dir / f'reduce_{reduce_round:02d}'
round_output_dir.mkdir(exist_ok=True)
current_training_data = training_datas[current_features].copy()
shap_values_perfold = []
total_predictions = []
fold_f1_scores = []
for i_fold in range(n_folds):
# Sample hyperparameters
hyperp_idx = min(len(hyperparameters) - 1, rng.integers(hyperps_top))
hyperp, split, to_punch = prepare_hyperparameters(
hyperp_base,
hyperparameters.iloc[hyperp_idx].to_dict(),
use_synthetic=True
)
# Prepare data
X_train, X_test, Y_train, Y_test, y_train, y_test = prepare_data(
current_training_data, objective_datas,
split, TARGET_COLUMN, to_punch, add_random=True,
label_encoder=le_reduce, ratio_punch_col=ratio_punch_col,
ratio_punch_row=ratio_punch_row, rng=rng, random_state=42 + i_fold
)
# Train and evaluate
xgb = train_model(X_train, y_train, X_test, y_test, hyperp)
predicted, f1 = evaluate_predictions(
xgb, X_test, y_test, Y_test, TARGET_COLUMN, le_reduce
)
total_predictions.append(predicted)
fold_f1_scores.append(f1)
# SHAP analysis
explainer = shap.TreeExplainer(xgb, data=X_train)
shap_values = explainer.shap_values(X_test, check_additivity=False)
shap_values_perfold.append(shap_values)
f1_scores.append(np.mean(fold_f1_scores))
logger.info(f"Round {reduce_round} - F1 score: {f1_scores[-1]:.4f}")
# Process importances
importances_all, importances_perclass = process_importances(
shap_values_perfold, current_features, class_dict,
reverse_dict, variable_hierarchy
)
# Save importances
with pd.ExcelWriter(round_output_dir / 'importances.xlsx') as writer:
importances_all.to_excel(writer, sheet_name='Global')
for class_name, df in importances_perclass.items():
df.to_excel(writer, sheet_name=f'Cluster {class_name}')
# Determine features to remove
random_importance = importances_all[
importances_all['variable'] == 'random'
]['importance'].values[0]
stop_reduce = True
if len(importances_all) > 1:
filter_remove = pd.Series([False] * len(importances_all))
for ranking_threshold in range(2, max_ranking_threshold):
filter_remove = (
filter_remove | (
(importances_all['ranking'] <= ranking_threshold) &
(importances_all.index > max(1, round(len(importances_all) * keep_most_important_ratio)))
) | (
(importances_all['ranking'] <= ranking_threshold) &
(importances_all['importance'] <= random_importance)
)
)
to_remove = filter_remove.sum()
if to_remove >= round(len(importances_all) * (1 - keep_most_important_ratio) / 2):
stop_reduce = False
break
if stop_reduce and len(importances_all) > 1:
try:
filter_ranking = importances_all['ranking'] <= ranking_threshold
if filter_ranking.any():
last_var_idx = importances_all[filter_ranking].index[-1]
filter_remove = importances_all.index == last_var_idx
stop_reduce = False
except Exception:
stop_reduce = True
if stop_reduce or filter_remove.sum() < 1:
logger.info(f"Stopping reduction at round {reduce_round}")
break
# Update current features
remaining_features = importances_all[~filter_remove]
current_features = remaining_features['variable'].tolist()
if 'random' in current_features:
current_features.remove('random')