from pathlib import Path import re from sklearn.model_selection import StratifiedKFold, cross_val_predict from sklearn.calibration import CalibratedClassifierCV from sklearn.metrics import brier_score_loss, log_loss from scipy.stats import chi2 from lightgbm import LGBMClassifier import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, auc, roc_auc_score from sklearn.metrics import ( accuracy_score, precision_score, recall_score, f1_score, roc_auc_score, confusion_matrix, log_loss, brier_score_loss, roc_curve ) from sklearn.model_selection import StratifiedKFold, cross_val_predict from sklearn.calibration import CalibratedClassifierCV from lightgbm import LGBMClassifier import numpy as np def hosmer_lemeshow_test(y_true, y_pred_proba, num_groups=10): df = pd.DataFrame({'y_true': y_true, 'y_pred': y_pred_proba}) df['decile'] = pd.qcut(df['y_pred'], num_groups, labels=False, duplicates='drop') decile_stats = df.groupby('decile').apply(lambda x: pd.Series({ 'observed': x['y_true'].sum(), 'expected': x['y_pred'].sum(), })).reset_index() chi_square_stat = np.sum( (decile_stats['observed'] - decile_stats['expected']) ** 2 / (decile_stats['expected'] + 1e-8) ) df_chi = df['decile'].nunique() - 2 # summary summary = df.groupby('decile').apply( lambda x: pd.Series({ 'Sample Size': len(x), 'Positive Rate (%)': 100 * x['y_true'].mean(), 'Predicted Range': f"{x['y_pred'].min():.3f}–{x['y_pred'].max():.3f}" }) ).reset_index() return 1 - chi2.cdf(chi_square_stat, df_chi), summary def plot_calibration_with_y_pred(y_true:np.ndarray, y_pred_proba:np.ndarray, pvalue:float, brier_score:float, title:str, y_pred:float=None, num_groups:int=4): df = pd.DataFrame({'y_true': y_true, 'y_pred': y_pred_proba}) df['decile'] = pd.cut(df['y_pred'], bins=np.linspace(0, 1, num_groups+1), labels=False) decile_stats = df.groupby('decile').apply( lambda x: pd.Series({ 'observed': 100 * x['y_true'].mean(), 'predicted': 100 * x['y_pred'].mean() }) ).reset_index() fig, ax = plt.subplots(figsize=(8, 4.5)) x = np.arange(len(decile_stats)) width = 0.35 ax.bar(x - width/2, decile_stats['observed'], width, label='Observed', color='steelblue') ax.bar(x + width/2, decile_stats['predicted'], width, label='Predicted', color='orange') if y_pred is not None: ax.axhline( y=y_pred * 100, # 機率轉百分比 color="red", linestyle="--", linewidth=2, label=f"CLL Risk: {y_pred*100:.2f}%" # 或改成你要的單位文字 ) for i in range(len(x)): ax.text(x[i] - width/2, decile_stats['observed'][i] + 1, f"{decile_stats['observed'][i]:.1f}", ha='center', fontsize=8, color='steelblue', fontweight='bold') ax.text(x[i] + width/2, decile_stats['predicted'][i] + 1, f"{decile_stats['predicted'][i]:.1f}", ha='center', fontsize=8, color='orange', fontweight='bold') top_y = max(decile_stats['observed'].max(), decile_stats['predicted'].max()) ax.text(len(x)/2-0.5, top_y - 1, title, ha='center', fontsize=14, color='black') ax.text(len(x)/2-0.5, top_y - 5, f"HL p-value = {pvalue:.2f} Brier Score = {brier_score:.2f}", ha='center', fontsize=10, color='black') ax.set_xticks(x) ax.set_xticklabels(range(1, len(decile_stats) + 1)) ax.set_xlabel(f"{num_groups} Quantile Groups") ax.set_ylabel("Frequency (%)") ax.legend() ax.grid(True, linestyle='--', alpha=0.4) plt.tight_layout() return fig def _calibration_output_stem(title, output_name): """檔名用:output/calibration_{stem}.xlsx;僅英數與底線較安全。""" raw = output_name if output_name is not None else title stem = re.sub(r"[^\w\-]+", "_", str(raw).strip()).strip("_") return stem or "calibration" def _ensure_feature_frame(X, feature_names): """訓練/預測皆用具欄位名的 DataFrame,避免 ndarray 與欄位名不一致的 sklearn 警告。""" if isinstance(X, pd.DataFrame): return X.copy() X_arr = np.asarray(X) if X_arr.ndim != 2: raise ValueError("X must be 2-dimensional") n_features = X_arr.shape[1] if feature_names is not None: cols = list(feature_names) if len(cols) != n_features: raise ValueError( f"feature_names length ({len(cols)}) must match X columns ({n_features})" ) else: cols = [f"f{i}" for i in range(n_features)] return pd.DataFrame(X_arr, columns=cols) def _to_numeric_matrix(X, feature_names=None): """轉為純數值矩陣,避免 LightGBM 對 pandas 類別欄位推斷不一致。""" X_df = _ensure_feature_frame(X, feature_names) X_num = X_df.apply(pd.to_numeric, errors="coerce") if X_num.isnull().values.any(): raise ValueError("Input features contain non-numeric values after preprocessing.") return X_num.to_numpy(dtype=np.float64) def nested_cv_calibration( X, y, fix_params, title, calibration_method="isotonic", num_groups=10, output_name=None, feature_names=None, input_df=None, ): lgbm_params = {**fix_params} if "verbose" not in lgbm_params: lgbm_params["verbose"] = -1 # 關閉 [LightGBM] [Info] 訓練日誌 base_model = LGBMClassifier(**lgbm_params) cal_model = CalibratedClassifierCV(base_model, method=calibration_method, cv=5) X_mat = _to_numeric_matrix(X, feature_names) y_arr = np.asarray(y).ravel() # 1) 用 cross_val_predict 取得「校正後機率」做 decile 校正評估 y_prob = cross_val_predict(cal_model, X_mat, y_arr, method="predict_proba", cv=5)[:, 1] pval, summary = hosmer_lemeshow_test(y_arr, y_prob, num_groups=num_groups) brier_score = brier_score_loss(y_arr, y_prob) # 2) 若有提供 input_df:用「校正後模型」在全資料上訓練,再對個案預測機率 if input_df is not None: # 先在全資料上重新訓練校正模型,作為部署用模型 cal_model.fit(X_mat, y_arr) X_input_mat = _to_numeric_matrix(input_df, feature_names) if X_input_mat.shape[1] != X_mat.shape[1]: raise ValueError( f"input features ({X_input_mat.shape[1]}) do not match training features ({X_mat.shape[1]})." ) y_input_pred_proba = cal_model.predict_proba(X_input_mat)[:, 1] input_risk = float(y_input_pred_proba[0]) # 使用校正後機率 + 個案風險畫紅色虛線 fig = plot_calibration_with_y_pred( y_true=y_arr, y_pred_proba=y_prob, pvalue=pval, brier_score=brier_score, title=title, y_pred=input_risk, num_groups=num_groups, ) return fig # # save for web app # if output_name is None: # raise ValueError("output_name must be provided to save web plot reference files.") # plot_ref_root = Path(r"D:\BA cases\ZBA040124_揚波\CLL_prediction_web\plot_reference") # plot_ref_dir = plot_ref_root / str(output_name) # plot_ref_dir.mkdir(parents=True, exist_ok=True) # np.save(plot_ref_dir / "y_arr.npy", y_arr) # np.save(plot_ref_dir / "y_prob.npy", y_prob) # np.save(plot_ref_dir / "pval.npy", pval) # np.save(plot_ref_dir / "brier_score.npy", brier_score) # record_df = pd.DataFrame(metrics_list) # stem = _calibration_output_stem(title, output_name) # out_dir = Path("output") # out_dir.mkdir(parents=True, exist_ok=True) # out_path = out_dir / f"calibration_{stem}.xlsx" # with pd.ExcelWriter(out_path, engine="openpyxl") as writer: # summary.to_excel(writer, sheet_name="summary", index=False) # record_df.to_excel(writer, sheet_name="record", index=False) # print(f"Calibration tables saved: {out_path.resolve()}") # print(f"Hosmer–Lemeshow p-value: {pval:.4f}") # print(f"Brier Score: {brier_score:.4f}") # print(f"Log Loss: {log_loss(y_arr, y_prob):.4f}") # return y_prob, cal_model, summary, fold_roc_results, metrics_list def summarize_cv_metrics(metrics_list): import pandas as pd df = pd.DataFrame(metrics_list) mean_series = df.mean() std_series = df.std() summary_df = pd.DataFrame({ 'Mean': mean_series, 'Std': std_series }).round(4) print("Cross-Validation Metric Summary:") print(summary_df) return summary_df def calibration_ROC(fold_roc_results): mean_fpr = np.linspace(0, 1, 100) # 生成統一的 FPR 軸 tprs = [] aucs = [] for fpr, tpr, auc_score in fold_roc_results: interp_tpr = np.interp(mean_fpr, fpr, tpr) # 插值對齊 TPR interp_tpr[0] = 0.0 # 確保起點為 0 tprs.append(interp_tpr) aucs.append(auc_score) mean_tpr = np.mean(tprs, axis=0) std_tpr = np.std(tprs, axis=0) mean_auc = np.mean(aucs) std_auc = np.std(aucs) return mean_fpr, mean_tpr, std_tpr, mean_auc, std_auc