From d8b1aaf76b756f92bd21da23ba18b885e7a1d884 Mon Sep 17 00:00:00 2001 From: Sathsreehari K <157597529+sath17-o@users.noreply.github.com> Date: Thu, 24 Sep 2026 02:11:49 +0530 Subject: [PATCH 1/3] Add Stage16 precision and lesion-level F1 closure --- notebooks/GraphMS_Segmentation_Audit.ipynb | 109 ++++++++++++++++++++- 1 file changed, 108 insertions(+), 1 deletion(-) diff --git a/notebooks/GraphMS_Segmentation_Audit.ipynb b/notebooks/GraphMS_Segmentation_Audit.ipynb index 34380b1..d88de6e 100644 --- a/notebooks/GraphMS_Segmentation_Audit.ipynb +++ b/notebooks/GraphMS_Segmentation_Audit.ipynb @@ -384,6 +384,110 @@ "print(f\"- r(log lesion burden, DSC): {r_logburden_dsc:.4f}\")\n" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Stage16 extended segmentation metrics — precision and lesion-level F1\n", + "\n", + "The guide's clean cross-validated evaluation harness also asks for **precision** and **lesion-F1**. This section evaluates the already-frozen 93 Stage16 masks only; it performs **no training, neural inference, threshold tuning, or model selection**.\n", + "\n", + "- **Precision** is computed per case as `TP / (TP + FP)` and averaged within each outer fold, matching the case-mean style of the primary Stage16 table.\n", + "- **Lesion F1 — any overlap** uses 26-connected lesion components and maximum bipartite one-to-one matching whenever predicted and expert lesions overlap.\n", + "- **Lesion F1 — IoU≥0.10** uses the same matching but requires component-pair IoU of at least 0.10.\n", + "- The headline extension is the equal-weight mean ± sample SD across the five outer-fold values.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from scipy import ndimage\n", + "from scipy.sparse import csr_matrix\n", + "from scipy.sparse.csgraph import maximum_bipartite_matching\n", + "\n", + "_STAGE16_STRUCT26 = np.ones((3,3,3), dtype=np.uint8)\n", + "\n", + "def _stage16_label26(mask):\n", + " return ndimage.label(mask, structure=_STAGE16_STRUCT26)[0]\n", + "\n", + "def _stage16_lesion_counts(pred, gt, iou_threshold=0.0):\n", + " pl = _stage16_label26(pred); gl = _stage16_label26(gt)\n", + " npred, ngt = int(pl.max()), int(gl.max())\n", + " if npred == 0 and ngt == 0: return 0, 0, 0\n", + " if npred == 0: return 0, 0, ngt\n", + " if ngt == 0: return 0, npred, 0\n", + " both = (pl > 0) & (gl > 0)\n", + " if not both.any(): return 0, npred, ngt\n", + " pair = pl[both].astype(np.int64) * (ngt + 1) + gl[both].astype(np.int64)\n", + " uniq, cnt = np.unique(pair, return_counts=True)\n", + " pi, gi = uniq // (ngt + 1), uniq % (ngt + 1)\n", + " ps = np.bincount(pl.ravel(), minlength=npred + 1)\n", + " gs = np.bincount(gl.ravel(), minlength=ngt + 1)\n", + " keep = []\n", + " for pidx, gidx, inter in zip(pi, gi, cnt):\n", + " ok = inter > 0 if iou_threshold <= 0 else inter / (ps[pidx] + gs[gidx] - inter) >= iou_threshold\n", + " if ok: keep.append((int(pidx - 1), int(gidx - 1)))\n", + " if not keep: return 0, npred, ngt\n", + " rows = [x[0] for x in keep]; cols = [x[1] for x in keep]\n", + " graph = csr_matrix((np.ones(len(rows), dtype=np.int8), (rows, cols)), shape=(npred, ngt))\n", + " match = maximum_bipartite_matching(graph, perm_type='column')\n", + " tp = int((match >= 0).sum())\n", + " return tp, npred - tp, ngt - tp\n", + "\n", + "def _stage16_lesion_f1(tp, fp, fn):\n", + " den = 2 * tp + fp + fn\n", + " return 1.0 if den == 0 else float(2 * tp / den)\n", + "\n", + "extended_case_rows = []\n", + "for row in audit.sort_values(['fold','case']).itertuples(index=False):\n", + " gt = load_bool(Path(row.gt_path))\n", + " pred = load_bool(Path(row.mask_path))\n", + " assert gt.shape == pred.shape, f'{row.case}: GT/pred shape mismatch'\n", + " precision = 1.0 if (int(row.TP) + int(row.FP)) == 0 else float(int(row.TP)/(int(row.TP)+int(row.FP)))\n", + " a = _stage16_lesion_counts(pred, gt, 0.0)\n", + " s = _stage16_lesion_counts(pred, gt, 0.10)\n", + " extended_case_rows.append({\n", + " 'case': str(row.case), 'fold': int(row.fold), 'Precision': precision,\n", + " 'LesionTP_any': a[0], 'LesionFP_any': a[1], 'LesionFN_any': a[2],\n", + " 'LesionTP_IoU010': s[0], 'LesionFP_IoU010': s[1], 'LesionFN_IoU010': s[2],\n", + " })\n", + "\n", + "extended_case = pd.DataFrame(extended_case_rows)\n", + "assert len(extended_case) == 93 and extended_case['case'].nunique() == 93\n", + "\n", + "fold_extended_rows = []\n", + "for fold, g in extended_case.groupby('fold', sort=True):\n", + " fold_extended_rows.append({\n", + " 'fold': int(fold), 'n_cases': int(len(g)),\n", + " 'Precision_case_mean': float(g['Precision'].mean()),\n", + " 'LesionF1_any_overlap': _stage16_lesion_f1(int(g.LesionTP_any.sum()), int(g.LesionFP_any.sum()), int(g.LesionFN_any.sum())),\n", + " 'LesionF1_IoU_ge_0_10': _stage16_lesion_f1(int(g.LesionTP_IoU010.sum()), int(g.LesionFP_IoU010.sum()), int(g.LesionFN_IoU010.sum())),\n", + " 'LesionTP_any': int(g.LesionTP_any.sum()), 'LesionFP_any': int(g.LesionFP_any.sum()), 'LesionFN_any': int(g.LesionFN_any.sum()),\n", + " 'LesionTP_IoU010': int(g.LesionTP_IoU010.sum()), 'LesionFP_IoU010': int(g.LesionFP_IoU010.sum()), 'LesionFN_IoU010': int(g.LesionFN_IoU010.sum()),\n", + " })\n", + "stage16_extended_by_fold = pd.DataFrame(fold_extended_rows)\n", + "stage16_extended_summary = pd.DataFrame([\n", + " {'Metric':'Precision_case_macro','Mean':float(stage16_extended_by_fold.Precision_case_mean.mean()),'Fold_SD':float(stage16_extended_by_fold.Precision_case_mean.std(ddof=1))},\n", + " {'Metric':'LesionF1_any_overlap','Mean':float(stage16_extended_by_fold.LesionF1_any_overlap.mean()),'Fold_SD':float(stage16_extended_by_fold.LesionF1_any_overlap.std(ddof=1))},\n", + " {'Metric':'LesionF1_IoU_ge_0_10','Mean':float(stage16_extended_by_fold.LesionF1_IoU_ge_0_10.mean()),'Fold_SD':float(stage16_extended_by_fold.LesionF1_IoU_ge_0_10.std(ddof=1))},\n", + "])\n", + "_expected={'Precision_case_macro':(0.7777367871281908,0.03918803792976655),'LesionF1_any_overlap':(0.7443683925600513,0.029949631773044393),'LesionF1_IoU_ge_0_10':(0.7302964674334995,0.03321153951229785)}\n", + "for r in stage16_extended_summary.itertuples(index=False):\n", + " em,es=_expected[r.Metric]\n", + " assert np.isclose(r.Mean,em,atol=1e-12) and np.isclose(r.Fold_SD,es,atol=1e-12), (r.Metric,r.Mean,r.Fold_SD)\n", + "display(stage16_extended_by_fold.style.format({'Precision_case_mean':'{:.6f}','LesionF1_any_overlap':'{:.6f}','LesionF1_IoU_ge_0_10':'{:.6f}'}))\n", + "display(stage16_extended_summary.style.format({'Mean':'{:.6f}','Fold_SD':'{:.6f}'}))\n", + "stage16_extended_by_fold.to_csv('/content/STAGE16_EXTENDED_SEGMENTATION_BY_FOLD.csv',index=False)\n", + "stage16_extended_summary.to_csv('/content/STAGE16_EXTENDED_SEGMENTATION_SUMMARY.csv',index=False)\n", + "print('Extended Stage16 closure:')\n", + "for r in stage16_extended_summary.itertuples(index=False):\n", + " print(f'- {r.Metric}: {r.Mean:.6f} ± {r.Fold_SD:.6f}')\n", + "print('No training / new inference / retuning performed.')\n" + ] + }, { "cell_type": "markdown", "metadata": {}, @@ -793,6 +897,8 @@ " '/content/SEGMENTATION_MULTI_CASE_QUALITATIVE.png',\n", " '/content/SEGMENTATION_BOUNDARY_FOCUSED.png',\n", " '/content/SEGMENTATION_QUALITATIVE_CASE_SELECTION.csv',\n", + " '/content/STAGE16_EXTENDED_SEGMENTATION_BY_FOLD.csv',\n", + " '/content/STAGE16_EXTENDED_SEGMENTATION_SUMMARY.csv',\n", "]\n", "\n", "for label, row in selected.iterrows():\n", @@ -803,7 +909,7 @@ "empty = [str(x) for x in artifacts if x.exists() and x.stat().st_size == 0]\n", "if missing or empty:\n", " raise RuntimeError(f'Diagnostics export incomplete. Missing={missing}; empty={empty}')\n", - "assert len(artifacts) == 17, f'Expected 17 diagnostic artifacts, found {len(artifacts)}'\n", + "assert len(artifacts) == 19, f'Expected 19 diagnostic artifacts, found {len(artifacts)}'\n", "\n", "zip_path = Path('/content/GraphMS_Segmentation_Diagnostics.zip')\n", "with ZipFile(zip_path, 'w', compression=ZIP_DEFLATED) as zf:\n", @@ -814,6 +920,7 @@ "print('Included files:', len(artifacts))\n", "\n", "\n", + "\n", "\n" ] } From 80c2a87edcaf56e65b02f537c7fd30f81e9f42de Mon Sep 17 00:00:00 2001 From: Sathsreehari K <157597529+sath17-o@users.noreply.github.com> Date: Thu, 24 Sep 2026 02:12:06 +0530 Subject: [PATCH 2/3] Document extended Stage16 detection metrics --- docs/GUIDE_CLOSURE.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/docs/GUIDE_CLOSURE.md b/docs/GUIDE_CLOSURE.md index bb00196..0206367 100644 --- a/docs/GUIDE_CLOSURE.md +++ b/docs/GUIDE_CLOSURE.md @@ -44,3 +44,16 @@ The historical branch scoreboard uses **series/case-weighted mean DSC**. The fin ## Closure boundary All 16 prescribed stages are traceable. Remaining guide ideas that would require genuinely new experiments—new pretraining/transfer learning, new hard-negative or small-lesion-aware training, or new external validation—are outside the frozen submission and are not simulated, backfilled, or claimed as completed. + + +## Extended Stage16 precision / lesion-F1 closure + +The frozen 93-case Stage16 masks were re-evaluated without retraining, new neural inference, threshold tuning, or model selection to add the remaining guide-requested detection metrics. + +| Metric | Equal-fold mean ± sample SD | +|---|---:| +| Segmentation precision (case-macro) | 0.777737 ± 0.039188 | +| Lesion F1 — any overlap | 0.744368 ± 0.029950 | +| Lesion F1 — IoU >= 0.10 | 0.730296 ± 0.033212 | + +Precision is computed per case and averaged within each outer fold. Lesion F1 uses 26-connected components and maximum bipartite one-to-one matching, with either any overlap or component-pair IoU >= 0.10. These are development five-fold descriptive metrics from the same frozen masks as the primary Stage16 result. From 5dbea1789fdfe75571a0814b6e3d185a9a36e990 Mon Sep 17 00:00:00 2001 From: Sathsreehari K <157597529+sath17-o@users.noreply.github.com> Date: Thu, 24 Sep 2026 02:12:10 +0530 Subject: [PATCH 3/3] Surface final Stage16 precision and lesion-F1 closure --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7d5c197..1b512e9 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ For reviewer-facing inspection of the frozen segmentation behavior, use the dedi It deterministically renders best/median/worst OOF cases as **FLAIR | expert ground truth | frozen prediction | TP/FP/FN error map**, adds a six-case qualitative diversity panel and an **HD95-driven boundary-focused panel**, then computes DSC/HD95 distributions, fold-wise DSC, lesion-burden quartiles, worst-case error direction, and a compact diagnostics bundle. The frozen 93-case record shows a residual low-lesion-burden / missed-lesion sensitivity weakness; see [`docs/SEGMENTATION_COHORT_DIAGNOSTICS.md`](docs/SEGMENTATION_COHORT_DIAGNOSTICS.md). No model or Stage11 retuning is performed. -Final guide-alignment closure is summarized in [`docs/GUIDE_CLOSURE.md`](docs/GUIDE_CLOSURE.md), including the same-cohort CNN/CATMIL/GAT/Hybrid comparison, morphology disposition, and the 16-stage implementation/evidence matrix. This adds no retraining or scientific-result changes. +Final guide-alignment closure is summarized in [`docs/GUIDE_CLOSURE.md`](docs/GUIDE_CLOSURE.md), including the same-cohort CNN/CATMIL/GAT/Hybrid comparison, morphology disposition, and the 16-stage implementation/evidence matrix. This adds no retraining or scientific-result changes. The final audit also adds the remaining no-training Stage16 precision and lesion-level F1 closure (any-overlap and IoU≥0.10 component matching) from the same frozen 93-case masks. ## Frozen scientific identity