Download code/scripts/schema_report.py from eduzrh/LNPBench: direct link, hf CLI and curl.
- Browser
- Download file 6.11 kB
-
https://huggingface.co/datasets/eduzrh/LNPBench/resolve/main/code/scripts/schema_report.py
- Command line
-
hf download hf://datasets/eduzrh/LNPBench/code/scripts/schema_report.py
-
curl -L -o schema_report.py https://huggingface.co/datasets/eduzrh/LNPBench/resolve/main/code/scripts/schema_report.py
6.11 kB
| """Summarise the ontology / global-representation experiments. | |
| Reads every result CSV that contains the schema blocks and the reference | |
| PhysChem-Tree run, normalises them to ``(config, task, study, spearman)`` and | |
| emits: | |
| * ``results/schema_summary.csv`` -- per-config, per-study means | |
| * ``results/schema_paired.csv`` -- paired Wilcoxon of each config against the | |
| identity-free reference on the 20 shared external tasks | |
| * ``results/schema_results.md`` -- the markdown tables used in the report | |
| The reference is the plain chemistry block (``base``), which is the strongest | |
| published single model (PhysChem-Tree, 0.376), so every delta below is a delta | |
| against the current state of the art under the strict protocol. | |
| Usage:: | |
| python scripts/schema_report.py | |
| """ | |
| from __future__ import annotations | |
| from pathlib import Path | |
| from typing import List | |
| import numpy as np | |
| import pandas as pd | |
| from scipy.stats import spearmanr, wilcoxon | |
| RESULTS = Path("results") | |
| STUDIES = ["LM_2019", "BL_2023", "SL_2020", "ZC_2023"] | |
| PRETTY = { | |
| "base": "PhysChem-Tree (reference)", | |
| "base+onto": "+ontology / schema", | |
| "base+cb": "+global codebook", | |
| "base+onto+cb": "+ontology +codebook", | |
| "base+spec": "+spectral embedding", | |
| "onto": "ontology only", | |
| "cb": "codebook only", | |
| } | |
| def _load(paths: List[Path]) -> pd.DataFrame: | |
| frames = [] | |
| for p in paths: | |
| if not p.exists(): | |
| continue | |
| df = pd.read_csv(p) | |
| if "config" in df.columns and "spearman" in df.columns: | |
| keep = df[["config", "task", "study", "spearman"]].copy() | |
| elif "k_shot" in df.columns: | |
| keep = df[df.k_shot == 0][["task", "study", "spearman"]].copy() | |
| keep["config"] = "base" | |
| elif "model" in df.columns and "spearman" in df.columns: | |
| keep = df[df.seed == 0][["task", "study", "spearman"]].copy() if "seed" in df else df[["task", "study", "spearman"]].copy() | |
| keep["config"] = df["model"].iloc[0] | |
| else: | |
| continue | |
| frames.append(keep) | |
| if not frames: | |
| return pd.DataFrame(columns=["config", "task", "study", "spearman"]) | |
| out = pd.concat(frames, ignore_index=True) | |
| out = out.drop_duplicates(["config", "task"], keep="last") | |
| return out | |
| def main() -> None: | |
| df = _load([ | |
| RESULTS / "fewshot.csv", # k=0 rows -> base | |
| RESULTS / "schema_bench2.csv", # base+onto / base+cb / base+onto+cb | |
| RESULTS / "schema_bench1.csv", # optional extra configs | |
| RESULTS / "schema_bench_spec.csv", | |
| ]) | |
| if df.empty: | |
| print("no results found") | |
| return | |
| order = [c for c in PRETTY if c in df.config.unique()] | |
| order += [c for c in df.config.unique() if c not in order] | |
| df["config"] = pd.Categorical(df.config, order, ordered=True) | |
| df = df.sort_values(["config", "study", "task"]) | |
| # ---- per-study means --------------------------------------------------- | |
| piv = df.pivot_table(index="config", columns="study", values="spearman", aggfunc="mean") | |
| mean = df.groupby("config").spearman.agg(["size", "mean", "std"]).rename(columns={"size": "n_tasks"}) | |
| summary = mean.join(piv[STUDIES]).reset_index() | |
| summary.to_csv(RESULTS / "schema_summary.csv", index=False) | |
| # ---- paired tests against the reference -------------------------------- | |
| ref = df[df.config == "base"].set_index("task").spearman | |
| rows = [] | |
| for cfg in order: | |
| cur = df[df.config == cfg].set_index("task").spearman | |
| common = ref.index.intersection(cur.index) | |
| if cfg == "base" or len(common) < 5: | |
| continue | |
| a, b = cur[common].to_numpy(), ref[common].to_numpy() | |
| try: | |
| p = wilcoxon(a, b).pvalue | |
| except ValueError: | |
| p = float("nan") | |
| rows.append({ | |
| "config": cfg, "n": len(common), | |
| "mean": float(a.mean()), "ref_mean": float(b.mean()), | |
| "delta": float(a.mean() - b.mean()), | |
| "relative": float((a.mean() - b.mean()) / abs(b.mean())) if b.mean() else float("nan"), | |
| "wilcoxon_p": float(p), | |
| "n_tasks_improved": int((a > b).sum()), | |
| }) | |
| paired = pd.DataFrame(rows).sort_values("delta", ascending=False) | |
| paired.to_csv(RESULTS / "schema_paired.csv", index=False) | |
| # ---- markdown ---------------------------------------------------------- | |
| lines = ["# Ontology / schema and global-representation experiments", ""] | |
| lines.append("All numbers are full runs: 4 fully held-out studies x 5 published folds " | |
| "= 20 external tasks, seed 0, identical estimator (random forest, " | |
| "400 trees, `min_samples_leaf=2`), identical splits. Only the feature " | |
| "block changes.") | |
| lines.append("") | |
| lines.append("## Per-study Spearman") | |
| lines.append("") | |
| lines.append("| config | " + " | ".join(STUDIES) + " | mean | n |") | |
| lines.append("|---|" + "---|" * (len(STUDIES) + 2)) | |
| for _, r in summary.iterrows(): | |
| label = PRETTY.get(str(r["config"]), str(r["config"])) | |
| cells = [f"{r[s]:.3f}" if pd.notna(r.get(s)) else "–" for s in STUDIES] | |
| lines.append(f"| {label} | " + " | ".join(cells) + f" | **{r['mean']:.3f}** | {int(r['n_tasks'])} |") | |
| lines.append("") | |
| if len(paired): | |
| lines.append("## Paired Wilcoxon against the reference (20 tasks)") | |
| lines.append("") | |
| lines.append("| config | mean | reference | delta | relative | tasks improved | p |") | |
| lines.append("|---|---|---|---|---|---|---|") | |
| for _, r in paired.iterrows(): | |
| label = PRETTY.get(str(r["config"]), str(r["config"])) | |
| lines.append( | |
| f"| {label} | {r['mean']:.3f} | {r['ref_mean']:.3f} | {r['delta']:+.3f} | " | |
| f"{100*r['relative']:+.1f}% | {r['n_tasks_improved']}/{int(r['n'])} | {r['wilcoxon_p']:.4f} |" | |
| ) | |
| lines.append("") | |
| out = RESULTS / "schema_results.md" | |
| out.write_text("\n".join(lines)) | |
| print("\n".join(lines)) | |
| print("wrote", out) | |
| if __name__ == "__main__": | |
| main() |