-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathml_feature_selection.py
More file actions
1595 lines (1370 loc) · 62.1 KB
/
Copy pathml_feature_selection.py
File metadata and controls
1595 lines (1370 loc) · 62.1 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
"""
Feature selection workflow for subject-level ICF modeling.
This script supports two complementary selection families:
1) Filter methods: target correlation ranking + inter-feature collinearity pruning.
2) Wrapper methods: greedy forward selection and backward elimination
using LOOCV multi-output ridge regression MAE.
"""
from __future__ import annotations
import argparse
import json
import logging
import re
from pathlib import Path
from typing import Dict, List, Sequence, Tuple
import matplotlib
matplotlib.use("Agg") # non-interactive backend; safe for scripts
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np
import pandas as pd
import seaborn as sns
from scipy import stats
from upsetplot import from_contents, UpSet
from ml_build_dataset import (
_parse_path_list,
build_training_table,
find_latest_batch,
load_combined_icf_targets,
)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
def _parse_target_cols(value: str | None) -> List[str]:
if value is None:
return []
return [item.strip() for item in value.split(",") if item.strip()]
def _parse_id_col(value: str) -> str | int:
value = value.strip()
if value.isdigit():
return int(value)
return value
def _load_or_build_table(args: argparse.Namespace) -> pd.DataFrame:
if not args.build_from_batch and args.table is not None:
if not args.table.exists():
raise FileNotFoundError(f"Training table not found: {args.table}")
table = pd.read_csv(args.table)
logger.info("Loaded training table: %s (shape=%s)", args.table, table.shape)
return table
if not args.target_cols:
raise ValueError("--target-cols is required when building table from batch outputs")
explicit_batch_dirs = _parse_path_list(args.batch_dirs)
if explicit_batch_dirs:
batch_dirs = explicit_batch_dirs
else:
batch_dir = args.batch_dir if args.batch_dir is not None else find_latest_batch(args.batch_root)
batch_dirs = [batch_dir]
explicit_icf_csvs = _parse_path_list(args.icf_csvs)
if explicit_icf_csvs:
icf_csvs = explicit_icf_csvs
else:
if args.icf_csv is None:
raise ValueError("--icf-csv or --icf-csvs is required when building table from batch outputs")
icf_csvs = [args.icf_csv]
id_col = _parse_id_col(str(args.id_col))
icf_targets = load_combined_icf_targets(icf_csvs=icf_csvs, id_col=id_col, target_cols=args.target_cols)
table = build_training_table(
batch_dirs=batch_dirs,
icf_targets=icf_targets,
min_feature_non_nan_ratio=args.min_feature_non_nan_ratio,
)
logger.info("Built training table from batch dirs: %s (shape=%s)", [str(path) for path in batch_dirs], table.shape)
if args.out_table is not None:
args.out_table.parent.mkdir(parents=True, exist_ok=True)
table.to_csv(args.out_table, index=False)
logger.info("Saved built training table to: %s", args.out_table)
return table
def _resolve_target_cols(table: pd.DataFrame, target_cols_arg: Sequence[str]) -> List[str]:
if target_cols_arg:
missing = [col for col in target_cols_arg if col not in table.columns]
if missing:
raise ValueError(f"Target column(s) missing from table: {missing}")
return list(target_cols_arg)
if "target_score" in table.columns:
logger.info("No --target-cols provided; defaulting to ['target_score']")
return ["target_score"]
raise ValueError("Could not infer target columns. Provide --target-cols.")
def _prepare_features(
table: pd.DataFrame,
target_cols: Sequence[str],
subject_col: str,
min_non_nan_ratio: float,
) -> Tuple[pd.DataFrame, pd.DataFrame, List[str], pd.DataFrame]:
if subject_col not in table.columns:
raise ValueError(f"Subject column '{subject_col}' not found")
y = table[list(target_cols)].apply(pd.to_numeric, errors="coerce")
valid_rows = ~y.isna().any(axis=1)
if valid_rows.sum() < 3:
raise ValueError("Not enough rows with valid targets for analysis")
work = table.loc[valid_rows].copy()
y = y.loc[valid_rows].copy()
numeric_cols = [
col
for col in work.columns
if col not in set(target_cols) | {subject_col}
and pd.api.types.is_numeric_dtype(work[col])
]
if not numeric_cols:
raise ValueError("No numeric feature columns found")
min_non_nan = int(np.ceil(min_non_nan_ratio * len(work)))
kept_cols: List[str] = []
dropped_cols: List[str] = []
drop_rows: List[Dict[str, float | int | str]] = []
for col in numeric_cols:
non_nan = int(work[col].notna().sum())
if non_nan >= min_non_nan:
kept_cols.append(col)
else:
dropped_cols.append(col)
drop_rows.append(
{
"feature": col,
"stage": "prepare_features",
"target": "all",
"step": "min_non_nan_ratio",
"reason": "insufficient_non_nan_coverage",
"non_nan_count": non_nan,
"threshold_non_nan": int(min_non_nan),
}
)
x = work[kept_cols].apply(pd.to_numeric, errors="coerce")
x = x.fillna(x.median(numeric_only=True))
variances = x.var(axis=0, ddof=0)
variable_cols = variances[variances > 0.0].index.tolist()
dropped_constant = sorted(set(kept_cols) - set(variable_cols))
if dropped_constant:
dropped_cols.extend(dropped_constant)
for col in dropped_constant:
drop_rows.append(
{
"feature": col,
"stage": "prepare_features",
"target": "all",
"step": "constant_variance",
"reason": "zero_variance",
"non_nan_count": int(work[col].notna().sum()) if col in work.columns else np.nan,
"threshold_non_nan": int(min_non_nan),
}
)
x = x[variable_cols]
if x.shape[1] == 0:
raise ValueError("No usable features remained after NaN/constant filtering")
logger.info(
"Prepared matrix with %d samples, %d features (dropped %d)",
x.shape[0],
x.shape[1],
len(dropped_cols),
)
dropped_detail_df = pd.DataFrame(drop_rows)
return x, y, dropped_cols, dropped_detail_df
def _build_feature_drop_audit(
all_features_after_prepare: Sequence[str],
dropped_prepare_df: pd.DataFrame,
corr_selected_by_target: Dict[str, List[str]],
wrapper_candidates_by_target: Dict[str, List[str]],
forward_trace: pd.DataFrame,
backward_trace: pd.DataFrame,
wrapper_selected_by_target: Dict[str, List[str]],
collinearity_decisions: pd.DataFrame,
) -> Tuple[pd.DataFrame, pd.DataFrame]:
rows: List[Dict[str, float | int | str]] = []
if not dropped_prepare_df.empty:
for rec in dropped_prepare_df.to_dict("records"):
rows.append(
{
"feature": str(rec.get("feature", "")),
"stage": str(rec.get("stage", "prepare_features")),
"target": str(rec.get("target", "all")),
"step": str(rec.get("step", "prepare_features")),
"reason": str(rec.get("reason", "dropped")),
"ref_feature": "",
"score_before": np.nan,
"score_after": np.nan,
"metric": "",
}
)
all_features_set = set(all_features_after_prepare)
for target, corr_selected in corr_selected_by_target.items():
corr_selected_set = set(corr_selected)
dropped_corr = sorted(all_features_set - corr_selected_set)
for feature in dropped_corr:
rows.append(
{
"feature": feature,
"stage": "filter",
"target": target,
"step": "target_corr_top_n_cutoff",
"reason": "outside_corr_max_features",
"ref_feature": "",
"score_before": np.nan,
"score_after": np.nan,
"metric": "max_abs_corr",
}
)
wrapper_candidates = wrapper_candidates_by_target.get(target, [])
wrapper_candidates_set = set(wrapper_candidates)
dropped_wrapper_cutoff = sorted(corr_selected_set - wrapper_candidates_set)
for feature in dropped_wrapper_cutoff:
rows.append(
{
"feature": feature,
"stage": "wrapper",
"target": target,
"step": "wrapper_candidate_top_k_cutoff",
"reason": "outside_wrapper_candidates",
"ref_feature": "",
"score_before": np.nan,
"score_after": np.nan,
"metric": "max_abs_corr",
}
)
selected_final = set(wrapper_selected_by_target.get(target, []))
dropped_not_selected = sorted(wrapper_candidates_set - selected_final)
for feature in dropped_not_selected:
rows.append(
{
"feature": feature,
"stage": "wrapper",
"target": target,
"step": "wrapper_not_in_target_final",
"reason": "not_selected_by_forward_backward",
"ref_feature": "",
"score_before": np.nan,
"score_after": np.nan,
"metric": "mae",
}
)
if not forward_trace.empty:
fwd_stop = forward_trace[forward_trace["operation"] == "stop"]
for rec in fwd_stop.to_dict("records"):
rows.append(
{
"feature": str(rec.get("feature", "")),
"stage": "wrapper",
"target": str(rec.get("target", "all")),
"step": "forward_stop",
"reason": "min_improvement_not_met",
"ref_feature": "",
"score_before": np.nan,
"score_after": float(rec.get("score_mae", np.nan)),
"metric": "mae",
}
)
if not backward_trace.empty:
bwd_remove = backward_trace[backward_trace["operation"] == "remove"]
for rec in bwd_remove.to_dict("records"):
rows.append(
{
"feature": str(rec.get("feature", "")),
"stage": "wrapper",
"target": str(rec.get("target", "all")),
"step": "backward_remove",
"reason": "removed_by_backward_elimination",
"ref_feature": "",
"score_before": np.nan,
"score_after": float(rec.get("score_mae", np.nan)),
"metric": "mae",
}
)
bwd_stop = backward_trace[backward_trace["operation"] == "stop"]
for rec in bwd_stop.to_dict("records"):
rows.append(
{
"feature": str(rec.get("feature", "")),
"stage": "wrapper",
"target": str(rec.get("target", "all")),
"step": "backward_stop",
"reason": "min_improvement_not_met",
"ref_feature": "",
"score_before": np.nan,
"score_after": float(rec.get("score_mae", np.nan)),
"metric": "mae",
}
)
if not collinearity_decisions.empty:
for rec in collinearity_decisions.to_dict("records"):
rows.append(
{
"feature": str(rec.get("feature_dropped", "")),
"stage": "union_prune",
"target": "all",
"step": "post_union_collinearity",
"reason": "high_collinearity_pair",
"ref_feature": str(rec.get("feature_kept", "")),
"score_before": float(rec.get("dropped_predictive_power", np.nan)),
"score_after": float(rec.get("kept_predictive_power", np.nan)),
"metric": "predictive_power",
}
)
detail_df = pd.DataFrame(rows)
if detail_df.empty:
summary_df = pd.DataFrame(
columns=["stage", "target", "step", "reason", "n_drop_events", "n_unique_features"]
)
else:
summary_df = (
detail_df.groupby(["stage", "target", "step", "reason"], as_index=False)
.agg(
n_drop_events=("feature", "size"),
n_unique_features=("feature", pd.Series.nunique),
)
.sort_values(["stage", "target", "step", "reason"])
.reset_index(drop=True)
)
return detail_df, summary_df
def _feature_target_correlation_table(x: pd.DataFrame, y: pd.DataFrame) -> pd.DataFrame:
rows: List[Dict[str, float | str]] = []
for feature in x.columns:
xv = x[feature].to_numpy(dtype=float)
for target in y.columns:
yv = y[target].to_numpy(dtype=float)
if np.std(xv) == 0.0 or np.std(yv) == 0.0:
pearson_r = np.nan
pearson_p = np.nan
spearman_r = np.nan
spearman_p = np.nan
else:
pearson_r, pearson_p = stats.pearsonr(xv, yv)
spearman_r, spearman_p = stats.spearmanr(xv, yv)
rows.append(
{
"feature": feature,
"target": target,
"pearson_r": float(pearson_r) if not pd.isna(pearson_r) else np.nan,
"pearson_p": float(pearson_p) if not pd.isna(pearson_p) else np.nan,
"spearman_r": float(spearman_r) if not pd.isna(spearman_r) else np.nan,
"spearman_p": float(spearman_p) if not pd.isna(spearman_p) else np.nan,
"abs_corr_score": float(
np.nanmax([abs(pearson_r), abs(spearman_r)])
if not (pd.isna(pearson_r) and pd.isna(spearman_r))
else np.nan
),
}
)
corr_df = pd.DataFrame(rows)
return corr_df.sort_values(["abs_corr_score", "feature", "target"], ascending=[False, True, True]).reset_index(drop=True)
def _aggregate_feature_scores(corr_df: pd.DataFrame) -> pd.DataFrame:
agg = (
corr_df.groupby("feature", as_index=False)
.agg(
max_abs_corr=("abs_corr_score", "max"),
mean_abs_corr=("abs_corr_score", "mean"),
best_target=("target", lambda s: s.iloc[int(corr_df.loc[s.index, "abs_corr_score"].argmax())]),
)
.sort_values(["max_abs_corr", "mean_abs_corr"], ascending=[False, False])
.reset_index(drop=True)
)
return agg
def _safe_target_name(target: str) -> str:
safe = re.sub(r"[^A-Za-z0-9._-]+", "_", str(target).strip())
return safe.strip("_") or "target"
def _build_feature_priority_rows(
target_cols: Sequence[str],
score_by_target: Dict[str, pd.DataFrame],
wrapper_selected_by_target: Dict[str, List[str]],
wrapper_best_score_by_target: Dict[str, float],
) -> pd.DataFrame:
"""
Build feature-level priority metadata used for post-union collinearity pruning.
Predictive power is a combined score using:
- target-specific max absolute correlation
- wrapper model quality when the feature is wrapper-selected for that target
"""
rows: List[Dict[str, float | str | bool]] = []
score_maps = {
target: dict(zip(df["feature"].tolist(), df["max_abs_corr"].tolist()))
for target, df in score_by_target.items()
}
wrapper_sets = {
target: set(features)
for target, features in wrapper_selected_by_target.items()
}
all_features = sorted(
{
feature
for target in target_cols
for feature in score_maps.get(target, {}).keys()
}
)
for feature in all_features:
best_row: Dict[str, float | str | bool] | None = None
best_key: Tuple[int, float, float] | None = None
for target in target_cols:
corr_value = score_maps.get(target, {}).get(feature, np.nan)
corr_value = float(corr_value) if pd.notna(corr_value) else float("-inf")
wrapper_selected = feature in wrapper_sets.get(target, set())
wrapper_score = float(wrapper_best_score_by_target.get(target, float("inf")))
wrapper_strength = 1.0 / (1.0 + wrapper_score) if wrapper_selected and np.isfinite(wrapper_score) else float("-inf")
predictive_power = max(corr_value, wrapper_strength)
# Prefer wrapper-selected features first, then higher combined power, then higher correlation.
rank_key = (1 if wrapper_selected else 0, predictive_power, corr_value)
if best_key is None or rank_key > best_key:
best_key = rank_key
best_row = {
"feature": feature,
"best_target": target,
"best_abs_corr": corr_value,
"wrapper_selected": bool(wrapper_selected),
"wrapper_best_score_mae": wrapper_score if np.isfinite(wrapper_score) else np.nan,
"predictive_power": predictive_power,
}
if best_row is not None:
rows.append(best_row)
if not rows:
return pd.DataFrame(
columns=[
"feature",
"best_target",
"best_abs_corr",
"wrapper_selected",
"wrapper_best_score_mae",
"predictive_power",
]
)
return pd.DataFrame(rows).sort_values("predictive_power", ascending=False).reset_index(drop=True)
def _high_collinearity_pairs(
x: pd.DataFrame,
feature_order: Sequence[str],
collinearity_scan_top_n: int,
threshold: float,
) -> pd.DataFrame:
candidate_cols = list(feature_order[:collinearity_scan_top_n])
if len(candidate_cols) < 2:
return pd.DataFrame(columns=["feature_a", "feature_b", "abs_corr"])
corr = x[candidate_cols].corr().abs()
pairs: List[Dict[str, float | str]] = []
for i, a in enumerate(candidate_cols):
for b in candidate_cols[i + 1 :]:
value = corr.at[a, b]
if pd.notna(value) and value >= threshold:
pairs.append({"feature_a": a, "feature_b": b, "abs_corr": float(value)})
if not pairs:
return pd.DataFrame(columns=["feature_a", "feature_b", "abs_corr"])
return pd.DataFrame(pairs).sort_values("abs_corr", ascending=False).reset_index(drop=True)
def _post_union_collinearity_prune(
x: pd.DataFrame,
union_features: Sequence[str],
feature_priority: pd.DataFrame,
threshold: float,
) -> Tuple[List[str], pd.DataFrame, pd.DataFrame]:
"""
Apply collinearity pruning only on the union feature set.
For each highly-collinear pair, keep the feature with higher predictive power.
Returns:
- final selected feature list
- high-correlation pair table restricted to union set
- prune decision table
"""
candidate_cols = [feature for feature in union_features if feature in x.columns]
if len(candidate_cols) < 2:
return sorted(candidate_cols), pd.DataFrame(columns=["feature_a", "feature_b", "abs_corr"]), pd.DataFrame(
columns=[
"feature_kept",
"feature_dropped",
"abs_corr",
"kept_predictive_power",
"dropped_predictive_power",
"kept_target",
"dropped_target",
"decision_rule",
]
)
corr = x[candidate_cols].corr().abs()
pair_rows: List[Dict[str, float | str]] = []
for i, feature_a in enumerate(candidate_cols):
for feature_b in candidate_cols[i + 1 :]:
value = corr.at[feature_a, feature_b]
if pd.notna(value) and value >= threshold:
pair_rows.append({"feature_a": feature_a, "feature_b": feature_b, "abs_corr": float(value)})
if not pair_rows:
return sorted(candidate_cols), pd.DataFrame(columns=["feature_a", "feature_b", "abs_corr"]), pd.DataFrame(
columns=[
"feature_kept",
"feature_dropped",
"abs_corr",
"kept_predictive_power",
"dropped_predictive_power",
"kept_target",
"dropped_target",
"decision_rule",
]
)
high_pairs_df = pd.DataFrame(pair_rows).sort_values("abs_corr", ascending=False).reset_index(drop=True)
priority_map = feature_priority.set_index("feature").to_dict("index") if not feature_priority.empty else {}
active = set(candidate_cols)
decisions: List[Dict[str, float | str]] = []
for row in high_pairs_df.itertuples(index=False):
feature_a = str(row.feature_a)
feature_b = str(row.feature_b)
abs_corr = float(row.abs_corr)
if feature_a not in active or feature_b not in active:
continue
meta_a = priority_map.get(feature_a, {})
meta_b = priority_map.get(feature_b, {})
power_a = float(meta_a.get("predictive_power", float("-inf")))
power_b = float(meta_b.get("predictive_power", float("-inf")))
corr_a = float(meta_a.get("best_abs_corr", float("-inf")))
corr_b = float(meta_b.get("best_abs_corr", float("-inf")))
# Keep stronger feature by predictive power; break ties by correlation then name.
rank_a = (power_a, corr_a, feature_a)
rank_b = (power_b, corr_b, feature_b)
if rank_a >= rank_b:
kept, dropped = feature_a, feature_b
kept_meta, dropped_meta = meta_a, meta_b
kept_power, dropped_power = power_a, power_b
else:
kept, dropped = feature_b, feature_a
kept_meta, dropped_meta = meta_b, meta_a
kept_power, dropped_power = power_b, power_a
active.remove(dropped)
decisions.append(
{
"feature_kept": kept,
"feature_dropped": dropped,
"abs_corr": abs_corr,
"kept_predictive_power": kept_power,
"dropped_predictive_power": dropped_power,
"kept_target": str(kept_meta.get("best_target", "")),
"dropped_target": str(dropped_meta.get("best_target", "")),
"decision_rule": "keep_higher_predictive_power",
}
)
final_selected = sorted(active)
decisions_df = pd.DataFrame(decisions)
return final_selected, high_pairs_df, decisions_df
def _correlation_filter_select(
x: pd.DataFrame,
ranked_features: Sequence[str],
threshold: float,
max_features: int,
) -> List[str]:
selected: List[str] = []
for feat in ranked_features:
if len(selected) >= max_features:
break
keep = True
for selected_feat in selected:
corr = x[[feat, selected_feat]].corr().iloc[0, 1]
if pd.notna(corr) and abs(corr) >= threshold:
keep = False
break
if keep:
selected.append(feat)
return selected
def _ridge_predict_loocv_mae(x: np.ndarray, y: np.ndarray, alpha: float) -> float:
n_samples = x.shape[0]
if n_samples < 3:
return float("inf")
errors: List[float] = []
for i in range(n_samples):
train_mask = np.ones(n_samples, dtype=bool)
train_mask[i] = False
x_train = x[train_mask]
y_train = y[train_mask]
x_test = x[~train_mask]
y_test = y[~train_mask]
if x_train.shape[1] == 0:
y_pred = np.repeat(y_train.mean(axis=0, keepdims=True), repeats=1, axis=0)
else:
x_mean = x_train.mean(axis=0, keepdims=True)
x_std = x_train.std(axis=0, keepdims=True)
x_std[x_std == 0.0] = 1.0
x_train_z = (x_train - x_mean) / x_std
x_test_z = (x_test - x_mean) / x_std
xtx = x_train_z.T @ x_train_z
reg = alpha * np.eye(xtx.shape[0], dtype=float)
xty = x_train_z.T @ y_train
try:
beta = np.linalg.solve(xtx + reg, xty)
except np.linalg.LinAlgError:
beta = np.linalg.pinv(xtx + reg) @ xty
intercept = y_train.mean(axis=0, keepdims=True)
y_pred = x_test_z @ beta + intercept
mae = np.mean(np.abs(y_pred - y_test))
errors.append(float(mae))
return float(np.mean(errors))
def _forward_selection(
x: pd.DataFrame,
y: pd.DataFrame,
candidate_features: Sequence[str],
max_features: int,
alpha: float,
min_improvement: float,
) -> Tuple[pd.DataFrame, List[str], float]:
selected: List[str] = []
remaining = list(candidate_features)
y_np = y.to_numpy(dtype=float)
baseline_score = _ridge_predict_loocv_mae(np.zeros((len(y), 0), dtype=float), y_np, alpha=alpha)
trace_rows: List[Dict[str, float | int | str]] = [
{
"step": 0,
"n_features": 0,
"operation": "baseline",
"feature": "",
"score_mae": baseline_score,
"improvement": 0.0,
}
]
best_score = baseline_score
best_set: List[str] = []
step = 0
while remaining and len(selected) < max_features:
step += 1
best_feature = None
best_candidate_score = float("inf")
for feature in remaining:
cols = selected + [feature]
score = _ridge_predict_loocv_mae(x[cols].to_numpy(dtype=float), y_np, alpha=alpha)
if score < best_candidate_score:
best_candidate_score = score
best_feature = feature
if best_feature is None:
break
improvement = best_score - best_candidate_score
if improvement < min_improvement:
trace_rows.append(
{
"step": step,
"n_features": len(selected),
"operation": "stop",
"feature": str(best_feature),
"score_mae": float(best_candidate_score),
"improvement": float(improvement),
}
)
break
selected.append(best_feature)
remaining.remove(best_feature)
best_score = best_candidate_score
if best_score <= min(row["score_mae"] for row in trace_rows if isinstance(row["score_mae"], float)):
best_set = selected.copy()
trace_rows.append(
{
"step": step,
"n_features": len(selected),
"operation": "add",
"feature": best_feature,
"score_mae": float(best_score),
"improvement": float(improvement),
}
)
if not best_set:
best_set = selected.copy()
return pd.DataFrame(trace_rows), best_set, best_score
def _backward_elimination(
x: pd.DataFrame,
y: pd.DataFrame,
initial_features: Sequence[str],
min_features: int,
alpha: float,
min_improvement: float,
) -> Tuple[pd.DataFrame, List[str], float]:
selected = list(initial_features)
y_np = y.to_numpy(dtype=float)
if not selected:
empty_trace = pd.DataFrame(
[{"step": 0, "n_features": 0, "operation": "empty", "feature": "", "score_mae": np.nan, "improvement": 0.0}]
)
return empty_trace, [], float("inf")
current_score = _ridge_predict_loocv_mae(x[selected].to_numpy(dtype=float), y_np, alpha=alpha)
trace_rows: List[Dict[str, float | int | str]] = [
{
"step": 0,
"n_features": len(selected),
"operation": "start",
"feature": "",
"score_mae": float(current_score),
"improvement": 0.0,
}
]
best_score = current_score
best_set = selected.copy()
step = 0
while len(selected) > min_features:
step += 1
best_feature_to_remove = None
best_candidate_score = float("inf")
for feature in selected:
candidate = [f for f in selected if f != feature]
score = _ridge_predict_loocv_mae(x[candidate].to_numpy(dtype=float), y_np, alpha=alpha)
if score < best_candidate_score:
best_candidate_score = score
best_feature_to_remove = feature
if best_feature_to_remove is None:
break
improvement = current_score - best_candidate_score
if improvement < min_improvement:
trace_rows.append(
{
"step": step,
"n_features": len(selected),
"operation": "stop",
"feature": str(best_feature_to_remove),
"score_mae": float(best_candidate_score),
"improvement": float(improvement),
}
)
break
selected.remove(best_feature_to_remove)
current_score = best_candidate_score
if current_score < best_score:
best_score = current_score
best_set = selected.copy()
trace_rows.append(
{
"step": step,
"n_features": len(selected),
"operation": "remove",
"feature": best_feature_to_remove,
"score_mae": float(current_score),
"improvement": float(improvement),
}
)
return pd.DataFrame(trace_rows), best_set, float(best_score)
# ---------------------------------------------------------------------------
# Plot / report generator
# ---------------------------------------------------------------------------
def _generate_plots(
out_dir: Path,
corr_df: pd.DataFrame,
score_df: pd.DataFrame,
high_corr_pairs: pd.DataFrame,
forward_trace: pd.DataFrame,
backward_trace: pd.DataFrame,
corr_selected: List[str],
final_selected: List[str],
wrapper_selected_by_target: Dict[str, List[str]] | None = None,
x: pd.DataFrame | None = None,
y: pd.DataFrame | None = None,
top_n: int = 25,
plot_scale: float = 1.0,
) -> None:
"""Write diagnostic plots into *out_dir*/plots/."""
plots_dir = out_dir / "plots"
plots_dir.mkdir(parents=True, exist_ok=True)
def _short_name(value: str, max_len: int = 60) -> str:
return value[:max_len] + "..." if len(value) > max_len else value
def _figsize(width: float, height: float) -> Tuple[float, float]:
scale = max(0.2, float(plot_scale))
return (max(1.0, width * scale), max(1.0, height * scale))
# ------------------------------------------------------------------
# 1. Top-feature correlation bar chart (max_abs_corr across targets)
# ------------------------------------------------------------------
top_scores = score_df.head(top_n).copy()
# Shorten feature names for readability
short_names = [_short_name(str(f), max_len=60) for f in top_scores["feature"]]
fig, ax = plt.subplots(figsize=_figsize(10, max(4, top_n * 0.35)))
colors = [
"#2196F3" if f in final_selected else
"#4CAF50" if f in corr_selected else "#BDBDBD"
for f in top_scores["feature"]
]
bars = ax.barh(range(len(top_scores)), top_scores["max_abs_corr"], color=colors)
ax.set_yticks(range(len(top_scores)))
ax.set_yticklabels(short_names, fontsize=8)
ax.invert_yaxis()
ax.set_xlabel("Max |correlation| across targets")
ax.set_title(f"Top {top_n} Features by Correlation Strength")
ax.xaxis.set_major_formatter(mticker.FormatStrFormatter("%.2f"))
# Legend
from matplotlib.patches import Patch
legend_elements = [
Patch(facecolor="#2196F3", label="Wrapper-selected"),
Patch(facecolor="#4CAF50", label="Filter-selected"),
Patch(facecolor="#BDBDBD", label="Not selected"),
]
ax.legend(handles=legend_elements, loc="lower right", fontsize=8)
fig.tight_layout()
fig.savefig(plots_dir / "top_feature_correlations.png", dpi=130)
plt.close(fig)
logger.info("Saved top_feature_correlations.png")
# ------------------------------------------------------------------
# 2. Per-target top-correlation heatmap
# ------------------------------------------------------------------
top_features = score_df["feature"].head(top_n).tolist()
heatmap_df = (
corr_df[corr_df["feature"].isin(top_features)]
.pivot_table(index="feature", columns="target", values="pearson_r")
.reindex(top_features) # keep ranking order
)
n_targets = heatmap_df.shape[1]
fig, ax = plt.subplots(figsize=_figsize(max(4, n_targets * 1.4), max(4, top_n * 0.35)))
vmax = float(heatmap_df.abs().max().max())
im = ax.imshow(heatmap_df.values, aspect="auto", cmap="RdBu_r", vmin=-vmax, vmax=vmax)
ax.set_xticks(range(n_targets))
ax.set_xticklabels(heatmap_df.columns.tolist(), rotation=30, ha="right", fontsize=9)
ax.set_yticks(range(len(top_features)))
ax.set_yticklabels(
[f[:60] + "..." if len(f) > 60 else f for f in top_features], fontsize=7
)
ax.set_title(f"Pearson r — Top {top_n} Features × Targets")
plt.colorbar(im, ax=ax, label="Pearson r")
# Mark wrapper-selected features
for row_idx, feat in enumerate(top_features):
if feat in final_selected:
ax.get_yticklabels()[row_idx].set_fontweight("bold")
ax.get_yticklabels()[row_idx].set_color("#1565C0")
fig.tight_layout()
fig.savefig(plots_dir / "correlation_heatmap.png", dpi=130)
plt.close(fig)
logger.info("Saved correlation_heatmap.png")
# ------------------------------------------------------------------
# 3. Target-specific top-correlation bars
# ------------------------------------------------------------------
if "target" in corr_df.columns:
targets = sorted(corr_df["target"].dropna().unique().tolist())
else:
targets = []
if targets:
n_targets = len(targets)
ncols = 2 if n_targets > 1 else 1
nrows = int(np.ceil(n_targets / ncols))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=_figsize(12, max(3.8, 3.3 * nrows)))
axes_flat = np.atleast_1d(axes).ravel()
for idx, target in enumerate(targets):
ax_t = axes_flat[idx]
score_target = _aggregate_feature_scores(corr_df[corr_df["target"] == target])
top_target = score_target.head(top_n)
target_features = top_target["feature"].tolist()
labels = [_short_name(str(feat), max_len=42) for feat in target_features]
values = top_target["max_abs_corr"].tolist()
colors = ["#1976D2" if feat in final_selected else "#90CAF9" for feat in target_features]
ax_t.barh(range(len(top_target)), values, color=colors)
ax_t.set_yticks(range(len(top_target)))
ax_t.set_yticklabels(labels, fontsize=7)
ax_t.invert_yaxis()
ax_t.set_xlim(0.0, 1.0)
ax_t.xaxis.set_major_formatter(mticker.FormatStrFormatter("%.2f"))
ax_t.set_title(f"{target}", fontsize=10)
ax_t.grid(axis="x", alpha=0.25)
for idx in range(n_targets, len(axes_flat)):