Download src/postprocess_validation.py from xuyun/AcidGNet_HCT116: direct link, hf CLI and curl.
- Browser
- Download file 7.67 kB
-
https://huggingface.co/datasets/xuyun/AcidGNet_HCT116/resolve/main/src/postprocess_validation.py
- Command line
-
hf download hf://datasets/xuyun/AcidGNet_HCT116/src/postprocess_validation.py
-
curl -L -o postprocess_validation.py https://huggingface.co/datasets/xuyun/AcidGNet_HCT116/resolve/main/src/postprocess_validation.py
7.67 kB
| from __future__ import annotations | |
| import itertools | |
| import json | |
| from pathlib import Path | |
| import matplotlib as mpl | |
| mpl.use("Agg") | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import pandas as pd | |
| from sklearn.metrics import average_precision_score, brier_score_loss, roc_auc_score | |
| ROOT = Path(__file__).resolve().parents[1] | |
| SEED = 20260810 | |
| BOOTSTRAPS = 5000 | |
| def stratified_bootstrap(y: np.ndarray, p: np.ndarray, rng: np.random.Generator): | |
| pos = np.flatnonzero(y == 1) | |
| neg = np.flatnonzero(y == 0) | |
| aucs, aps, briers = [], [], [] | |
| for _ in range(BOOTSTRAPS): | |
| idx = np.r_[rng.choice(pos, len(pos), replace=True), rng.choice(neg, len(neg), replace=True)] | |
| aucs.append(roc_auc_score(y[idx], p[idx])) | |
| aps.append(average_precision_score(y[idx], p[idx])) | |
| briers.append(brier_score_loss(y[idx], p[idx])) | |
| return { | |
| "auroc_ci_low": np.quantile(aucs, 0.025), | |
| "auroc_ci_high": np.quantile(aucs, 0.975), | |
| "auprc_ci_low": np.quantile(aps, 0.025), | |
| "auprc_ci_high": np.quantile(aps, 0.975), | |
| "brier_ci_low": np.quantile(briers, 0.025), | |
| "brier_ci_high": np.quantile(briers, 0.975), | |
| } | |
| def exact_balanced_permutation(y: np.ndarray, p: np.ndarray): | |
| n = len(y) | |
| n_pos = int(y.sum()) | |
| observed_auc = roc_auc_score(y, p) | |
| observed_ap = average_precision_score(y, p) | |
| aucs, aps = [], [] | |
| for pos in itertools.combinations(range(n), n_pos): | |
| yp = np.zeros(n, dtype=int) | |
| yp[list(pos)] = 1 | |
| aucs.append(roc_auc_score(yp, p)) | |
| aps.append(average_precision_score(yp, p)) | |
| aucs = np.asarray(aucs) | |
| aps = np.asarray(aps) | |
| return { | |
| "permutations": len(aucs), | |
| "auroc_exact_p": float(np.mean(aucs >= observed_auc - 1e-12)), | |
| "auprc_exact_p": float(np.mean(aps >= observed_ap - 1e-12)), | |
| } | |
| def summarize_external(): | |
| pred = pd.read_csv(ROOT / "results/external_GSE200546_predictions.csv") | |
| rows = [] | |
| for i, (method, d) in enumerate(pred.groupby("method", sort=False)): | |
| y = d.y.to_numpy(dtype=int) | |
| p = d.prob.to_numpy(dtype=float) | |
| point = { | |
| "method": method, | |
| "n": len(d), | |
| "n_acid": int(y.sum()), | |
| "n_control": int((1 - y).sum()), | |
| "auroc": roc_auc_score(y, p), | |
| "auprc": average_precision_score(y, p), | |
| "brier": brier_score_loss(y, p), | |
| } | |
| point.update(stratified_bootstrap(y, p, np.random.default_rng(SEED + i))) | |
| point.update(exact_balanced_permutation(y, p)) | |
| rows.append(point) | |
| out = pd.DataFrame(rows) | |
| out.to_csv(ROOT / "results/external_GSE200546_uncertainty.csv", index=False) | |
| return out | |
| def summarize_strict_cv(): | |
| d = pd.read_csv(ROOT / "results/strict_cv_metrics.csv") | |
| out = ( | |
| d.groupby("method", sort=False) | |
| .agg( | |
| n_domains=("held_out", "nunique"), | |
| auroc_mean=("auroc", "mean"), | |
| auroc_min=("auroc", "min"), | |
| auroc_max=("auroc", "max"), | |
| auprc_mean=("auprc", "mean"), | |
| auprc_min=("auprc", "min"), | |
| auprc_max=("auprc", "max"), | |
| brier_mean=("brier", "mean"), | |
| ) | |
| .reset_index() | |
| ) | |
| out.to_csv(ROOT / "results/strict_cv_summary.csv", index=False) | |
| return d, out | |
| def revised_figures(cv: pd.DataFrame, uncertainty: pd.DataFrame): | |
| mpl.rcParams.update( | |
| { | |
| "font.family": "sans-serif", | |
| "font.sans-serif": ["Arial", "DejaVu Sans"], | |
| "svg.fonttype": "none", | |
| "pdf.fonttype": 42, | |
| "font.size": 7, | |
| "axes.spines.top": False, | |
| "axes.spines.right": False, | |
| } | |
| ) | |
| order = ["ExprLogReg", "MLP", "GCN", "AcidGNet", "SelfLoopGAT", "PermutedGraphGAT"] | |
| colors = dict(zip(order, ["#3F6FA0", "#82A6C8", "#76A996", "#C65D4B", "#D5A059", "#9182AB"])) | |
| fig, axes = plt.subplots(1, 2, figsize=(7.2, 2.75)) | |
| for ax, metric in zip(axes, ["auroc", "auprc"]): | |
| for j, method in enumerate(order): | |
| vals = cv.loc[cv.method == method, metric].to_numpy() | |
| ax.scatter(np.full_like(vals, j, dtype=float), vals, s=24, color=colors[method], zorder=3) | |
| ax.plot([j - 0.18, j + 0.18], [vals.mean(), vals.mean()], color="black", lw=1.2) | |
| ax.axhline(0.5, ls="--", lw=0.8, color="0.65") | |
| ax.set_xticks(range(len(order)), order, rotation=35, ha="right") | |
| ax.set_ylim(-0.03, 1.05) | |
| ax.set_ylabel(metric.upper()) | |
| ax.set_title("Strict leave-one-cell-line-out\n(each point is one held-out domain)") | |
| fig.tight_layout() | |
| for ext in ["png", "pdf", "svg"]: | |
| fig.savefig(ROOT / f"figures/Fig4_strict_ablation.{ext}", dpi=600 if ext == "png" else None, bbox_inches="tight") | |
| plt.close(fig) | |
| u = uncertainty.set_index("method").loc[order].reset_index() | |
| fig, axes = plt.subplots(1, 2, figsize=(7.2, 2.8)) | |
| for ax, metric, label in zip(axes, ["auroc", "auprc"], ["AUROC", "AUPRC"]): | |
| vals = u[metric].to_numpy() | |
| lo = vals - u[f"{metric}_ci_low"].to_numpy() | |
| hi = u[f"{metric}_ci_high"].to_numpy() - vals | |
| ax.bar(range(len(order)), vals, color=[colors[m] for m in order], width=0.72) | |
| ax.errorbar(range(len(order)), vals, yerr=np.vstack([lo, hi]), fmt="none", ecolor="black", capsize=2, lw=0.8) | |
| for j, row in u.iterrows(): | |
| ax.text(j, 0.03, f"p={row[f'{metric}_exact_p']:.2f}", ha="center", va="bottom", rotation=90, fontsize=5) | |
| ax.axhline(0.5, ls="--", lw=0.8, color="0.5") | |
| ax.set_xticks(range(len(order)), order, rotation=35, ha="right") | |
| ax.set_ylim(0, 1.08) | |
| ax.set_ylabel(label) | |
| ax.set_title(f"GSE200546 CLS1 external ranking\n95% stratified bootstrap CI; exact p") | |
| fig.suptitle("Cross-cancer technical validation only (n=8; not CRC)", y=1.04, fontsize=8) | |
| fig.tight_layout() | |
| for ext in ["png", "pdf", "svg"]: | |
| fig.savefig(ROOT / f"figures/Fig5_external_validation.{ext}", dpi=600 if ext == "png" else None, bbox_inches="tight") | |
| plt.close(fig) | |
| abl = pd.read_csv(ROOT / "results/external_node_ablation.csv") | |
| a = ( | |
| abl.groupby("symbol") | |
| .agg(abs_effect=("abs_effect_all", "mean"), abs_effect_sd=("abs_effect_all", "std")) | |
| .sort_values("abs_effect") | |
| .tail(20) | |
| ) | |
| fig, ax = plt.subplots(figsize=(5.2, 3.7)) | |
| ax.barh(a.index, a.abs_effect, xerr=a.abs_effect_sd.fillna(0), color="0.55") | |
| ax.set_xlabel("Mean absolute probability change") | |
| ax.set_title("Exploratory node ablation is non-interpretable\nExternal AcidGNet AUROC = 0.50; effects are <0.002") | |
| ax.ticklabel_format(axis="x", style="sci", scilimits=(0, 0)) | |
| fig.tight_layout() | |
| for ext in ["png", "pdf", "svg"]: | |
| fig.savefig(ROOT / f"figures/Fig6_node_ablation.{ext}", dpi=600 if ext == "png" else None, bbox_inches="tight") | |
| plt.close(fig) | |
| def main(): | |
| uncertainty = summarize_external() | |
| cv, cv_summary = summarize_strict_cv() | |
| revised_figures(cv, uncertainty) | |
| report = { | |
| "external_n": 8, | |
| "external_is_crc": False, | |
| "bootstrap_replicates": BOOTSTRAPS, | |
| "balanced_exact_permutations": 70, | |
| "strict_cv": cv_summary.set_index("method").round(4).to_dict("index"), | |
| "external": uncertainty.set_index("method").round(4).to_dict("index"), | |
| "interpretation": "No AcidGNet superiority; node-ablation ranks are not driver evidence.", | |
| } | |
| (ROOT / "logs/postprocess_validation_summary.json").write_text(json.dumps(report, indent=2), encoding="utf-8") | |
| print(json.dumps(report, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |