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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Leakage_Free_PRECISE_v4.py
|
| 3 |
+
|
| 4 |
+
PRECISE-GBM v4 (nested-CV corrected; picklable selector):
|
| 5 |
+
- Leak-free radiomics-only predictors
|
| 6 |
+
- Per-label radiomics-immune alignment (no X/y length mismatch)
|
| 7 |
+
- GMM-derived binary immune labels (fit on TRAIN, applied to held-out)
|
| 8 |
+
- FEATURE SELECTION INSIDE THE CV PIPELINE (truly nested inner CV)
|
| 9 |
+
LASSO selection is a Pipeline step (LassoSelector), refit within every
|
| 10 |
+
inner-CV fold and every calibration fold.
|
| 11 |
+
- LassoSelector lives in precise_selectors.py (importable) so joblib can
|
| 12 |
+
pickle it during parallel CV AND reload saved models in a fresh session.
|
| 13 |
+
- Nested hyperparameter tuning (SVM & Ensemble)
|
| 14 |
+
- Post-tuning calibration with CalibratedClassifierCV on TRAIN ONLY
|
| 15 |
+
SVM: probability=False, so the sigmoid is fit ONCE on the raw
|
| 16 |
+
decision_function (no double-Platt). Ensemble: its SVM keeps
|
| 17 |
+
probability=True because soft voting needs predict_proba; the outer
|
| 18 |
+
sigmoid recalibrates the combined soft-vote score.
|
| 19 |
+
- Calibrated models evaluated on held-out Ivy/TCGA/CPTAC
|
| 20 |
+
|
| 21 |
+
Data-path assumptions (confirmed by user; the disjoint one is asserted below):
|
| 22 |
+
- ComBat harmonisation was fit on TRAINING data only; held-out never harmonised.
|
| 23 |
+
- Train and held-out patients are disjoint.
|
| 24 |
+
|
| 25 |
+
Requires precise_selectors.py on the PYTHONPATH (same folder is easiest).
|
| 26 |
+
|
| 27 |
+
Outputs per signature group (LM22, GBM):
|
| 28 |
+
- models_v4_{sig}/scenario_{1,2,3}/*_gmm_model.joblib
|
| 29 |
+
- models_v4_{sig}/scenario_{1,2,3}/*_svm_model.joblib (uncalibrated)
|
| 30 |
+
- models_v4_{sig}/scenario_{1,2,3}/*_ens_model.joblib (uncalibrated)
|
| 31 |
+
- models_v4_{sig}/scenario_{1,2,3}/*_svm_cal_model.joblib (calibrated)
|
| 32 |
+
- models_v4_{sig}/scenario_{1,2,3}/*_ens_cal_model.joblib (calibrated)
|
| 33 |
+
- nested_results_v4_{sig}.json (held-out metrics for calibrated models)
|
| 34 |
+
- nested_features_v4_{sig}.json (selected radiomics per label/scenario/model)
|
| 35 |
+
- nested_cv_v4_{sig}.json (inner CV results for uncalibrated models)
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
import logging
|
| 39 |
+
import warnings
|
| 40 |
+
import os
|
| 41 |
+
import time
|
| 42 |
+
import json
|
| 43 |
+
|
| 44 |
+
import numpy as np
|
| 45 |
+
import pandas as pd
|
| 46 |
+
from tqdm import tqdm
|
| 47 |
+
|
| 48 |
+
from sklearn.exceptions import ConvergenceWarning
|
| 49 |
+
from sklearn.mixture import GaussianMixture
|
| 50 |
+
from sklearn.preprocessing import StandardScaler
|
| 51 |
+
from sklearn.svm import SVC
|
| 52 |
+
from sklearn.ensemble import RandomForestClassifier, HistGradientBoostingClassifier, VotingClassifier
|
| 53 |
+
from sklearn.pipeline import Pipeline
|
| 54 |
+
from sklearn.model_selection import StratifiedKFold, RandomizedSearchCV
|
| 55 |
+
from sklearn.calibration import CalibratedClassifierCV
|
| 56 |
+
from sklearn.metrics import (
|
| 57 |
+
accuracy_score, precision_score, recall_score,
|
| 58 |
+
f1_score, balanced_accuracy_score, matthews_corrcoef,
|
| 59 |
+
brier_score_loss
|
| 60 |
+
)
|
| 61 |
+
from joblib import dump
|
| 62 |
+
|
| 63 |
+
# LassoSelector must be importable (NOT defined here in __main__) so joblib can
|
| 64 |
+
# pickle it for parallel CV and reload saved models later.
|
| 65 |
+
from precise_selectors import LassoSelector
|
| 66 |
+
|
| 67 |
+
# -------------------------
|
| 68 |
+
# Logging & warnings
|
| 69 |
+
# -------------------------
|
| 70 |
+
logging.basicConfig(
|
| 71 |
+
filename='Leakage_Free_PRECISE_v4.log',
|
| 72 |
+
level=logging.INFO,
|
| 73 |
+
format='%(asctime)s - %(levelname)s - %(message)s'
|
| 74 |
+
)
|
| 75 |
+
warnings.filterwarnings('ignore', category=UserWarning)
|
| 76 |
+
warnings.filterwarnings('ignore', category=ConvergenceWarning)
|
| 77 |
+
|
| 78 |
+
# NOTE: joblib.Memory caching was removed. It hashes each pipeline step with
|
| 79 |
+
# standard pickle, which cannot resolve a custom transformer and raised the
|
| 80 |
+
# PicklingError. The parallel search path uses cloudpickle and is fine.
|
| 81 |
+
|
| 82 |
+
# -------------------------
|
| 83 |
+
# JSON-safe converters
|
| 84 |
+
# -------------------------
|
| 85 |
+
def _convert_obj(o):
|
| 86 |
+
if hasattr(o, 'tolist') and not isinstance(o, (dict, list, str, bytes)):
|
| 87 |
+
try:
|
| 88 |
+
return o.tolist()
|
| 89 |
+
except Exception:
|
| 90 |
+
return str(o)
|
| 91 |
+
if isinstance(o, dict):
|
| 92 |
+
return {k: _convert_obj(v) for k, v in o.items()}
|
| 93 |
+
if isinstance(o, (list, tuple)):
|
| 94 |
+
return [_convert_obj(v) for v in o]
|
| 95 |
+
if isinstance(o, (np.integer, np.floating, np.bool_)):
|
| 96 |
+
return o.item()
|
| 97 |
+
return o
|
| 98 |
+
|
| 99 |
+
def _cv_results_to_serializable(cv_dict):
|
| 100 |
+
out = {}
|
| 101 |
+
for k, v in cv_dict.items():
|
| 102 |
+
if hasattr(v, 'tolist'):
|
| 103 |
+
try:
|
| 104 |
+
out[k] = v.tolist()
|
| 105 |
+
except Exception:
|
| 106 |
+
out[k] = str(v)
|
| 107 |
+
else:
|
| 108 |
+
out[k] = _convert_obj(v)
|
| 109 |
+
return out
|
| 110 |
+
|
| 111 |
+
# -------------------------
|
| 112 |
+
# Scenario definitions
|
| 113 |
+
# -------------------------
|
| 114 |
+
scenarios_LM22 = {
|
| 115 |
+
1: {
|
| 116 |
+
'train_radiomics': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Radiomics/neuro_combat_radiomic_CGGA_Rem_CP_TC.csv",
|
| 117 |
+
'train_immune': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Genome/Heldout/heldout_Ivy/Cbx_LOOCV_heldout_Ivy_Lm22/CIBERSORTx_Job49_Results.csv",
|
| 118 |
+
'heldout_radiomics': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Radiomics/Radiomics_LOOCV_test_Ivy.csv",
|
| 119 |
+
'heldout_immune': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Genome/Testing/IvyGAP/Test_Ivy_LM22/CIBERSORTx_Job55_Results.csv"
|
| 120 |
+
},
|
| 121 |
+
2: {
|
| 122 |
+
'train_radiomics': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Radiomics/neuro_combat_radiomic_CGGA_Rem_CP_ivy.csv",
|
| 123 |
+
'train_immune': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Genome/Heldout/heldout_TCGA/Cbx_heldoutTCGA_Lm22/CIBERSORTx_Job47_Results.csv",
|
| 124 |
+
'heldout_radiomics': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Radiomics/Radiomics_LOOCV_test_TCGA.csv",
|
| 125 |
+
'heldout_immune': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Genome/Testing/TCGA/Cbx_TCGA_Test_LM22/CIBERSORTx_Job53_Results.csv"
|
| 126 |
+
},
|
| 127 |
+
3: {
|
| 128 |
+
'train_radiomics': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Radiomics/neuro_combat_radiomic_CGGA_Rem_TC_ivy.csv",
|
| 129 |
+
'train_immune': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Genome/Heldout/heldout_CPTAC/CBx_LOOCV_heldout_CPTAC_LM22/CIBERSORTx_Job51_Results.csv",
|
| 130 |
+
'heldout_radiomics': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Radiomics/Radiomics_LOOCV_test_CPTAC.csv",
|
| 131 |
+
'heldout_immune': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Genome/Testing/CPTAC/Test_CPTAC_LM22/CIBERSORTx_Job57_Results.csv"
|
| 132 |
+
}
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
scenarios_GBM = {
|
| 136 |
+
1: {
|
| 137 |
+
'train_radiomics': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Radiomics/neuro_combat_radiomic_CGGA_Rem_CP_TC.csv",
|
| 138 |
+
'train_immune': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Genome/Heldout/heldout_Ivy/Cbx_LOOCV_heldout_Ivy_GBM/CIBERSORTx_Job50_Results.csv",
|
| 139 |
+
'heldout_radiomics': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Radiomics/Radiomics_LOOCV_test_Ivy.csv",
|
| 140 |
+
'heldout_immune': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Genome/Testing/IvyGAP/Test_Ivy_GBM/CIBERSORTx_Job56_Results.csv"
|
| 141 |
+
},
|
| 142 |
+
2: {
|
| 143 |
+
'train_radiomics': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Radiomics/neuro_combat_radiomic_CGGA_Rem_CP_ivy.csv",
|
| 144 |
+
'train_immune': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Genome/Heldout/heldout_TCGA/Cbx_LOOCV_TCGA_heldout_GBM/CIBERSORTx_Job48_Results.csv",
|
| 145 |
+
'heldout_radiomics': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Radiomics/Radiomics_LOOCV_test_TCGA.csv",
|
| 146 |
+
'heldout_immune': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Genome/Testing/TCGA/TCGA_test_GBM/CIBERSORTx_Job54_Results.csv"
|
| 147 |
+
},
|
| 148 |
+
3: {
|
| 149 |
+
'train_radiomics': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Radiomics/neuro_combat_radiomic_CGGA_Rem_TC_ivy.csv",
|
| 150 |
+
'train_immune': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Genome/Heldout/heldout_CPTAC/Cbx_LOOCV_heldout_CPTAC_GBM/CIBERSORTx_Job52_Results.csv",
|
| 151 |
+
'heldout_radiomics': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Radiomics/Radiomics_LOOCV_test_CPTAC.csv",
|
| 152 |
+
'heldout_immune': r"C:/Users/pg22/Downloads/PRECISE-GBM/LOOCV_withoutHarm/Genome/Testing/CPTAC/Test_CPTAC_GBM/CIBERSORTx_Job58_Results.csv"
|
| 153 |
+
}
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
signature_groups = {
|
| 157 |
+
'LM22': scenarios_LM22,
|
| 158 |
+
'GBM': scenarios_GBM
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
# -------------------------
|
| 162 |
+
# Hyperparameter grids
|
| 163 |
+
# -------------------------
|
| 164 |
+
param_dist_svm = {
|
| 165 |
+
'clf__C': [1, 10],
|
| 166 |
+
'clf__gamma': [0.01, 0.1],
|
| 167 |
+
'clf__kernel': ['rbf']
|
| 168 |
+
}
|
| 169 |
+
param_dist_ensemble = {
|
| 170 |
+
'ensemble__svm__classifier__C': [1],
|
| 171 |
+
'ensemble__svm__classifier__kernel': ['rbf'],
|
| 172 |
+
'ensemble__rf__n_estimators': [100, 200],
|
| 173 |
+
'ensemble__rf__max_depth': [None],
|
| 174 |
+
'ensemble__gb__max_iter': [100],
|
| 175 |
+
'ensemble__gb__learning_rate': [0.1]
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
# -------------------------
|
| 179 |
+
# Main v3 loop
|
| 180 |
+
# -------------------------
|
| 181 |
+
for sig_name, scenarios in signature_groups.items():
|
| 182 |
+
all_results = {}
|
| 183 |
+
all_features = {}
|
| 184 |
+
all_cv = {}
|
| 185 |
+
|
| 186 |
+
for scen_id in [1, 2, 3]:
|
| 187 |
+
os.makedirs(f"models_v4_{sig_name}/scenario_{scen_id}", exist_ok=True)
|
| 188 |
+
|
| 189 |
+
for scen_id, paths in scenarios.items():
|
| 190 |
+
logging.info(f"[v4:{sig_name}] Starting scenario {scen_id}")
|
| 191 |
+
t0 = time.time()
|
| 192 |
+
|
| 193 |
+
# Load radiomics + immune
|
| 194 |
+
rad_tr_full = pd.read_csv(paths['train_radiomics'], index_col=0)
|
| 195 |
+
imm_tr_full = pd.read_csv(paths['train_immune'], index_col=0)
|
| 196 |
+
rad_ho_full = pd.read_csv(paths['heldout_radiomics'], index_col=0)
|
| 197 |
+
imm_ho_full = pd.read_csv(paths['heldout_immune'], index_col=0)
|
| 198 |
+
|
| 199 |
+
# index align WITHIN train and WITHIN held-out
|
| 200 |
+
common_tr = rad_tr_full.index.intersection(imm_tr_full.index)
|
| 201 |
+
rad_tr_full = rad_tr_full.loc[common_tr].sort_index()
|
| 202 |
+
imm_tr_full = imm_tr_full.loc[common_tr].sort_index()
|
| 203 |
+
|
| 204 |
+
common_ho = rad_ho_full.index.intersection(imm_ho_full.index)
|
| 205 |
+
rad_ho_full = rad_ho_full.loc[common_ho].sort_index()
|
| 206 |
+
imm_ho_full = imm_ho_full.loc[common_ho].sort_index()
|
| 207 |
+
|
| 208 |
+
# --- guard: train and held-out patients must be disjoint ---
|
| 209 |
+
overlap = set(rad_tr_full.index).intersection(set(rad_ho_full.index))
|
| 210 |
+
if overlap:
|
| 211 |
+
raise ValueError(
|
| 212 |
+
f"[v4:{sig_name}:{scen_id}] Train/held-out patient overlap "
|
| 213 |
+
f"({len(overlap)} IDs, e.g. {list(overlap)[:5]}). "
|
| 214 |
+
f"Held-out must be disjoint from train."
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
# --- guard: radiomics feature columns must match train vs held-out ---
|
| 218 |
+
if list(rad_tr_full.columns) != list(rad_ho_full.columns):
|
| 219 |
+
common_rad = rad_tr_full.columns.intersection(rad_ho_full.columns)
|
| 220 |
+
if common_rad.empty:
|
| 221 |
+
raise ValueError(f"[v4:{sig_name}:{scen_id}] No shared radiomics columns train vs held-out.")
|
| 222 |
+
rad_tr_full = rad_tr_full[common_rad]
|
| 223 |
+
rad_ho_full = rad_ho_full[common_rad]
|
| 224 |
+
logging.warning(f"[v4:{sig_name}:{scen_id}] Restricted to {len(common_rad)} shared radiomics columns.")
|
| 225 |
+
|
| 226 |
+
scen_results = {}
|
| 227 |
+
scen_features = {}
|
| 228 |
+
scen_cv = {}
|
| 229 |
+
|
| 230 |
+
inner_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
|
| 231 |
+
|
| 232 |
+
immune_cols = imm_tr_full.columns.intersection(imm_ho_full.columns)
|
| 233 |
+
if immune_cols.empty:
|
| 234 |
+
raise ValueError(f"[v4:{sig_name}:{scen_id}] No matching immune features between train and held-out")
|
| 235 |
+
|
| 236 |
+
logging.info(f"[v4:{sig_name}:{scen_id}] {len(immune_cols)} immune features: {immune_cols.tolist()}")
|
| 237 |
+
|
| 238 |
+
rad_cols = rad_tr_full.columns.tolist() # radiomics-only feature space
|
| 239 |
+
|
| 240 |
+
for col in tqdm(immune_cols, desc=f"{sig_name} v4:{scen_id}"):
|
| 241 |
+
try:
|
| 242 |
+
# --- per-label join to avoid X/y mismatches ---
|
| 243 |
+
df_tr_label = rad_tr_full.join(imm_tr_full[[col]], how="inner").dropna(subset=[col])
|
| 244 |
+
df_ho_label = rad_ho_full.join(imm_ho_full[[col]], how="inner").dropna(subset=[col])
|
| 245 |
+
|
| 246 |
+
if df_tr_label.shape[0] == 0 or df_ho_label.shape[0] == 0:
|
| 247 |
+
logging.warning(f"[v4:{sig_name}:{scen_id}] {col}: no samples after join/dropna; skipping.")
|
| 248 |
+
continue
|
| 249 |
+
|
| 250 |
+
# Features = radiomics ONLY; label source = this immune column ONLY
|
| 251 |
+
X_tr = df_tr_label[rad_cols].values
|
| 252 |
+
y_tr_vals = df_tr_label[col].values.reshape(-1, 1)
|
| 253 |
+
X_ho = df_ho_label[rad_cols].values
|
| 254 |
+
y_ho_vals = df_ho_label[col].values.reshape(-1, 1)
|
| 255 |
+
|
| 256 |
+
# GMM labels: fit on TRAIN immune, apply to held-out (no held-out leakage)
|
| 257 |
+
gmm = GaussianMixture(n_components=2, random_state=42)
|
| 258 |
+
y_tr = gmm.fit_predict(y_tr_vals)
|
| 259 |
+
if len(np.unique(y_tr)) < 2:
|
| 260 |
+
logging.warning(f"[v4:{sig_name}:{scen_id}] {col}: GMM yielded one class only; skipping.")
|
| 261 |
+
continue
|
| 262 |
+
y_ho = gmm.predict(y_ho_vals)
|
| 263 |
+
|
| 264 |
+
m0, m1 = gmm.means_.flatten()
|
| 265 |
+
if m0 < m1: # class 1 = higher-mean component
|
| 266 |
+
y_tr = 1 - y_tr
|
| 267 |
+
y_ho = 1 - y_ho
|
| 268 |
+
|
| 269 |
+
gmm_model_path = f"models_v4_{sig_name}/scenario_{scen_id}/{sig_name}_v4_scen{scen_id}_{col}_gmm_model.joblib"
|
| 270 |
+
dump(gmm, gmm_model_path)
|
| 271 |
+
logging.info(f"[v4:{sig_name}:{scen_id}] Saved GMM model to {gmm_model_path}")
|
| 272 |
+
|
| 273 |
+
# =========================================================
|
| 274 |
+
# SVM: nested CV. Selection is a PIPELINE STEP -> refit inside
|
| 275 |
+
# every fold, so the inner CV is truly nested. X is the FULL
|
| 276 |
+
# radiomics matrix; scale -> select -> clf.
|
| 277 |
+
# probability=False: the single calibrating sigmoid is applied
|
| 278 |
+
# by CalibratedClassifierCV to the raw decision_function below,
|
| 279 |
+
# so there is NO sigmoid-on-sigmoid. (Tuning uses predict.)
|
| 280 |
+
# =========================================================
|
| 281 |
+
pipe_svm = Pipeline([
|
| 282 |
+
('scaler', StandardScaler()),
|
| 283 |
+
('select', LassoSelector()),
|
| 284 |
+
('clf', SVC(class_weight='balanced', probability=False, random_state=42))
|
| 285 |
+
])
|
| 286 |
+
|
| 287 |
+
search_svm = RandomizedSearchCV(
|
| 288 |
+
pipe_svm, param_dist_svm, n_iter=5,
|
| 289 |
+
cv=inner_cv, scoring='balanced_accuracy',
|
| 290 |
+
n_jobs=-1, refit=True, error_score='raise'
|
| 291 |
+
)
|
| 292 |
+
search_svm.fit(X_tr, y_tr)
|
| 293 |
+
cv_svm = _cv_results_to_serializable(search_svm.cv_results_)
|
| 294 |
+
|
| 295 |
+
svm_model_path = f"models_v4_{sig_name}/scenario_{scen_id}/{sig_name}_v4_scen{scen_id}_{col}_svm_model.joblib"
|
| 296 |
+
dump(search_svm.best_estimator_, svm_model_path)
|
| 297 |
+
logging.info(f"[v4:{sig_name}:{scen_id}] Saved SVM model to {svm_model_path}")
|
| 298 |
+
|
| 299 |
+
# =========================================================
|
| 300 |
+
# Ensemble: nested CV (selection inside pipeline as above)
|
| 301 |
+
# NOTE: soft voting needs predict_proba from every member, so this
|
| 302 |
+
# SVM keeps probability=True. The outer CalibratedClassifierCV then
|
| 303 |
+
# recalibrates the *combined* soft-vote score (one sigmoid on the
|
| 304 |
+
# averaged output) -- not a double sigmoid on a single SVM margin.
|
| 305 |
+
# =========================================================
|
| 306 |
+
base_pipe = Pipeline([
|
| 307 |
+
('scaler', StandardScaler()),
|
| 308 |
+
('classifier', SVC(class_weight='balanced', probability=True, random_state=42))
|
| 309 |
+
])
|
| 310 |
+
|
| 311 |
+
ensemble = VotingClassifier([
|
| 312 |
+
('svm', base_pipe),
|
| 313 |
+
('rf', RandomForestClassifier(class_weight='balanced', random_state=42)),
|
| 314 |
+
('gb', HistGradientBoostingClassifier(random_state=42))
|
| 315 |
+
], voting='soft', weights=[1, 1, 1], n_jobs=-1)
|
| 316 |
+
|
| 317 |
+
pipe_ens = Pipeline([
|
| 318 |
+
('scaler', StandardScaler()),
|
| 319 |
+
('select', LassoSelector()),
|
| 320 |
+
('ensemble', ensemble)
|
| 321 |
+
])
|
| 322 |
+
|
| 323 |
+
search_ens = RandomizedSearchCV(
|
| 324 |
+
pipe_ens, param_dist_ensemble, n_iter=3,
|
| 325 |
+
cv=inner_cv, scoring='balanced_accuracy',
|
| 326 |
+
n_jobs=-1, refit=True, error_score='raise'
|
| 327 |
+
)
|
| 328 |
+
search_ens.fit(X_tr, y_tr)
|
| 329 |
+
cv_ens = _cv_results_to_serializable(search_ens.cv_results_)
|
| 330 |
+
|
| 331 |
+
ens_model_path = f"models_v4_{sig_name}/scenario_{scen_id}/{sig_name}_v4_scen{scen_id}_{col}_ens_model.joblib"
|
| 332 |
+
dump(search_ens.best_estimator_, ens_model_path)
|
| 333 |
+
logging.info(f"[v4:{sig_name}:{scen_id}] Saved Ensemble model to {ens_model_path}")
|
| 334 |
+
|
| 335 |
+
scen_cv[col] = {'svm_cv': cv_svm, 'ensemble_cv': cv_ens}
|
| 336 |
+
|
| 337 |
+
# --- record features actually chosen by the final refit ---
|
| 338 |
+
svm_sel = search_svm.best_estimator_.named_steps['select']
|
| 339 |
+
ens_sel = search_ens.best_estimator_.named_steps['select']
|
| 340 |
+
scen_features[col] = {
|
| 341 |
+
'svm': [rad_cols[i] for i in svm_sel.get_support(indices=True)],
|
| 342 |
+
'ensemble': [rad_cols[i] for i in ens_sel.get_support(indices=True)]
|
| 343 |
+
}
|
| 344 |
+
if getattr(svm_sel, 'all_features_fallback_', False) or getattr(ens_sel, 'all_features_fallback_', False):
|
| 345 |
+
logging.warning(f"[v4:{sig_name}:{scen_id}] {col}: LASSO selected 0 features on final refit; kept all (check alphas).")
|
| 346 |
+
|
| 347 |
+
# =========================================================
|
| 348 |
+
# Calibration on TRAIN ONLY (internal CV -> leak-free).
|
| 349 |
+
# cv=5 refits clones per calibration fold, so selection is also
|
| 350 |
+
# refit inside calibration folds. Held-out never seen.
|
| 351 |
+
# SVM has probability=False -> this sigmoid is fit on the raw
|
| 352 |
+
# decision_function (single Platt, no double sigmoid).
|
| 353 |
+
# =========================================================
|
| 354 |
+
svm_cal = CalibratedClassifierCV(search_svm.best_estimator_, cv=5, method="sigmoid")
|
| 355 |
+
svm_cal.fit(X_tr, y_tr)
|
| 356 |
+
dump(svm_cal, f"models_v4_{sig_name}/scenario_{scen_id}/{sig_name}_v4_scen{scen_id}_{col}_svm_cal_model.joblib")
|
| 357 |
+
|
| 358 |
+
ens_cal = CalibratedClassifierCV(search_ens.best_estimator_, cv=5, method="sigmoid")
|
| 359 |
+
ens_cal.fit(X_tr, y_tr)
|
| 360 |
+
dump(ens_cal, f"models_v4_{sig_name}/scenario_{scen_id}/{sig_name}_v4_scen{scen_id}_{col}_ens_cal_model.joblib")
|
| 361 |
+
|
| 362 |
+
# --- Held-out predictions (calibrated); full radiomics in ---
|
| 363 |
+
prob_svm = svm_cal.predict_proba(X_ho)[:, 1]
|
| 364 |
+
y_pred_svm = (prob_svm >= 0.5).astype(int)
|
| 365 |
+
|
| 366 |
+
prob_ens = ens_cal.predict_proba(X_ho)[:, 1]
|
| 367 |
+
y_pred_ens = (prob_ens >= 0.5).astype(int)
|
| 368 |
+
|
| 369 |
+
# --- Metrics ---
|
| 370 |
+
def metrics(y_true, y_pred, y_prob):
|
| 371 |
+
return {
|
| 372 |
+
'Accuracy': accuracy_score(y_true, y_pred),
|
| 373 |
+
'Precision': precision_score(y_true, y_pred, zero_division=1),
|
| 374 |
+
'Recall': recall_score(y_true, y_pred, zero_division=1),
|
| 375 |
+
'F1 Score': f1_score(y_true, y_pred, zero_division=1),
|
| 376 |
+
'Balanced Accuracy': balanced_accuracy_score(y_true, y_pred),
|
| 377 |
+
'MCC': matthews_corrcoef(y_true, y_pred),
|
| 378 |
+
'Brier': brier_score_loss(y_true, y_prob),
|
| 379 |
+
'N': int(len(y_true))
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
scen_results[col] = {
|
| 383 |
+
'SVM': metrics(y_ho, y_pred_svm, prob_svm),
|
| 384 |
+
'Ensemble': metrics(y_ho, y_pred_ens, prob_ens)
|
| 385 |
+
}
|
| 386 |
+
|
| 387 |
+
except Exception as e:
|
| 388 |
+
logging.error(f"[v4:{sig_name}:{scen_id}] ERROR for column {col}: {e}")
|
| 389 |
+
print(f"[ERROR v4] {sig_name}:{scen_id}, column {col}: {e}")
|
| 390 |
+
|
| 391 |
+
all_results[scen_id] = scen_results
|
| 392 |
+
all_features[scen_id] = scen_features
|
| 393 |
+
all_cv[scen_id] = scen_cv
|
| 394 |
+
|
| 395 |
+
dt = time.time() - t0
|
| 396 |
+
logging.info(f"[v4:{sig_name}] scenario {scen_id} done in {dt/60:.1f} min")
|
| 397 |
+
print(f"{sig_name} v4:{scen_id} complete in {dt/60:.1f} min")
|
| 398 |
+
|
| 399 |
+
with open(f"nested_results_v4_{sig_name}.json", 'w') as f:
|
| 400 |
+
json.dump(_convert_obj(all_results), f, indent=2)
|
| 401 |
+
with open(f"nested_features_v4_{sig_name}.json", 'w') as f:
|
| 402 |
+
json.dump(_convert_obj(all_features), f, indent=2)
|
| 403 |
+
with open(f"nested_cv_v4_{sig_name}.json", 'w') as f:
|
| 404 |
+
json.dump(_convert_obj(all_cv), f, indent=2)
|
| 405 |
+
|
| 406 |
+
print(f"[OK] v4 {sig_name} group complete: scenarios={list(all_results.keys())}")
|
| 407 |
+
|
| 408 |
+
print("All v4 signature groups processed.")
|
precise_selectors.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
precise_selectors.py
|
| 3 |
+
|
| 4 |
+
Custom sklearn transformers for the PRECISE-GBM pipeline.
|
| 5 |
+
|
| 6 |
+
Kept in a SEPARATE, IMPORTABLE module (NOT in the training script's __main__)
|
| 7 |
+
so that:
|
| 8 |
+
1. joblib / pickle can resolve the class by reference during parallel CV
|
| 9 |
+
(a class defined in __main__ raises
|
| 10 |
+
"Can't pickle <class '__main__.LassoSelector'>"), and
|
| 11 |
+
2. models saved with joblib.dump() can be RELOADED in a fresh session or in
|
| 12 |
+
retrain_helper.py, because the reference resolves to
|
| 13 |
+
precise_selectors.LassoSelector rather than __main__.LassoSelector.
|
| 14 |
+
|
| 15 |
+
Keep this file on the PYTHONPATH (simplest: same folder as the training and
|
| 16 |
+
retrain scripts).
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
from sklearn.base import BaseEstimator, TransformerMixin
|
| 21 |
+
from sklearn.linear_model import Lasso
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class LassoSelector(BaseEstimator, TransformerMixin):
|
| 25 |
+
"""LASSO feature selection as a pipeline step (refit inside every CV fold).
|
| 26 |
+
|
| 27 |
+
Two-step alpha fallback: try each alpha in order, keep the first that
|
| 28 |
+
yields a non-empty support. If nothing survives any alpha for a fold,
|
| 29 |
+
keep ALL features and record it via `all_features_fallback_` so frequent
|
| 30 |
+
fallback (alphas too aggressive for the fold size) is auditable.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(self, alphas=(0.1, 0.01), max_iter=10000, random_state=42):
|
| 34 |
+
self.alphas = alphas
|
| 35 |
+
self.max_iter = max_iter
|
| 36 |
+
self.random_state = random_state
|
| 37 |
+
|
| 38 |
+
def fit(self, X, y):
|
| 39 |
+
X = np.asarray(X)
|
| 40 |
+
y = np.asarray(y).ravel()
|
| 41 |
+
self.n_features_in_ = X.shape[1]
|
| 42 |
+
support = None
|
| 43 |
+
for alpha in self.alphas:
|
| 44 |
+
lasso = Lasso(alpha=alpha, max_iter=self.max_iter, random_state=self.random_state, tol=1e-4)
|
| 45 |
+
lasso.fit(X, y)
|
| 46 |
+
idx = np.flatnonzero(lasso.coef_ != 0)
|
| 47 |
+
if idx.size > 0:
|
| 48 |
+
support = idx
|
| 49 |
+
break
|
| 50 |
+
if support is None:
|
| 51 |
+
support = np.arange(self.n_features_in_)
|
| 52 |
+
self.all_features_fallback_ = True
|
| 53 |
+
else:
|
| 54 |
+
self.all_features_fallback_ = False
|
| 55 |
+
self.support_ = support
|
| 56 |
+
return self
|
| 57 |
+
|
| 58 |
+
def transform(self, X):
|
| 59 |
+
return np.asarray(X)[:, self.support_]
|
| 60 |
+
|
| 61 |
+
def get_support(self, indices=False):
|
| 62 |
+
if indices:
|
| 63 |
+
return self.support_
|
| 64 |
+
mask = np.zeros(self.n_features_in_, dtype=bool)
|
| 65 |
+
mask[self.support_] = True
|
| 66 |
+
return mask
|