Spaces:
Running
Running
Download workflow/scripts/plot_classwise_variant_metrics.py from lauransotomayor/hyperFVC: direct link, hf CLI and curl.
- Browser
- Download file 17 kB
-
https://huggingface.co/spaces/lauransotomayor/hyperFVC/resolve/main/workflow/scripts/plot_classwise_variant_metrics.py
- Command line
-
hf download hf://spaces/lauransotomayor/hyperFVC/workflow/scripts/plot_classwise_variant_metrics.py
-
curl -L -o plot_classwise_variant_metrics.py https://huggingface.co/spaces/lauransotomayor/hyperFVC/resolve/main/workflow/scripts/plot_classwise_variant_metrics.py
17 kB
| #!/usr/bin/env python3 | |
| """Plot aggregate class-wise F1 or IoU by model variant.""" | |
| from __future__ import annotations | |
| import argparse | |
| import os | |
| import re | |
| import sys | |
| from pathlib import Path | |
| try: | |
| import matplotlib.pyplot as plt | |
| import pandas as pd | |
| import seaborn as sns | |
| except ModuleNotFoundError as exc: | |
| env_python = Path(os.environ.get("ENV_PYTHON", "/home/laura/.local/share/mamba/envs/fvc_function/bin/python")) | |
| if env_python.exists() and Path(sys.executable).resolve() != env_python.resolve(): | |
| os.execv(str(env_python), [str(env_python), str(Path(__file__).resolve()), *sys.argv[1:]]) | |
| raise SystemExit( | |
| "matplotlib, pandas, and seaborn are required. Run with the project environment, for example: " | |
| f"{env_python} {Path(__file__).resolve()}" | |
| ) from exc | |
| VARIANT_LABELS = { | |
| "M1": "Baseline U-Net", | |
| "M2": "Spectral adapter", | |
| "M3": "Spectral adapter + NPV-weighted loss", | |
| "M4": "Spectral adapter + transformer", | |
| "M5": "Spectral adapter + transformer + NPV-weighted loss", | |
| } | |
| MODEL_ORDER = ["M1", "M2", "M3", "M4", "M5"] | |
| CLASS_ORDER = ["BE", "NPV", "PV"] | |
| SENSOR_ORDER = ["MICA", "FX10_FX17", "FX10", "FX17"] | |
| VALUE_TICKS = [index / 10 for index in range(11)] | |
| Y_AXIS_MAX = 1.14 | |
| ROBUST_LOG_PATTERN = "mica_robust_variants_s304_crop608_*/MICA_*_robust.log" | |
| def model_variant(variant: str) -> str | None: | |
| if "_aug_spec_transformer_weights" in variant: | |
| return "M5" | |
| if "_aug_spectral_weights" in variant: | |
| return "M3" | |
| if "_aug_spec_transformer" in variant: | |
| return "M4" | |
| if "_aug_spectral" in variant: | |
| return "M2" | |
| if variant.endswith("_aug") or variant == "_aug": | |
| return "M1" | |
| return None | |
| def parse_average_best_test_metrics(log_path: Path) -> dict[str, object] | None: | |
| text = log_path.read_text(errors="ignore") | |
| pattern = re.compile( | |
| r"Average Metrics Across All Best Models \(Test Set\):\s*\n" | |
| r"Accuracy:\s*[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?\s*\n" | |
| r"Precision:\s*.+?\n" | |
| r"Recall:\s*.+?\n" | |
| r"F1 Score:\s*(?P<f1>.+?)\n" | |
| r"IoU:\s*(?P<iou>.+?)\n" | |
| r"MIoU:\s*(?P<miou>[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)\s*\n" | |
| r"Average metrics across all blocks saved to\s*(?P<checkpoint>.+)", | |
| flags=re.MULTILINE, | |
| ) | |
| matches = list(pattern.finditer(text)) | |
| if not matches: | |
| return None | |
| match = matches[-1] | |
| f1_values = [float(value) for value in re.findall(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?", match.group("f1"))] | |
| iou_values = [float(value) for value in re.findall(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?", match.group("iou"))] | |
| if len(f1_values) < len(CLASS_ORDER) or len(iou_values) < len(CLASS_ORDER): | |
| return None | |
| checkpoint_dir = match.group("checkpoint").strip() | |
| return { | |
| "Sensor": "MICA", | |
| "Variant": "_" + Path(checkpoint_dir).name.removeprefix("MICA_").removesuffix("_s304_crop608_robust"), | |
| "Scale": "304px", | |
| "F1_BE": f1_values[0], | |
| "F1_NPV": f1_values[1], | |
| "F1_PV": f1_values[2], | |
| "IoU_BE": iou_values[0], | |
| "IoU_NPV": iou_values[1], | |
| "IoU_PV": iou_values[2], | |
| } | |
| def load_mica_robust_metrics(log_root: Path) -> pd.DataFrame: | |
| if not log_root.exists(): | |
| return pd.DataFrame() | |
| latest_by_model: dict[str, tuple[float, dict[str, object]]] = {} | |
| for log_path in log_root.glob(ROBUST_LOG_PATTERN): | |
| if log_path.name.endswith(".fault.log"): | |
| continue | |
| row = parse_average_best_test_metrics(log_path) | |
| if row is None: | |
| continue | |
| row["ModelVariant"] = model_variant(str(row["Variant"])) | |
| if row["ModelVariant"] not in MODEL_ORDER: | |
| continue | |
| modified_time = log_path.stat().st_mtime | |
| previous = latest_by_model.get(str(row["ModelVariant"])) | |
| if previous is None or modified_time >= previous[0]: | |
| latest_by_model[str(row["ModelVariant"])] = (modified_time, row) | |
| return pd.DataFrame([latest_by_model[variant][1] for variant in MODEL_ORDER if variant in latest_by_model]) | |
| def load_metrics(metrics_csv: Path, robust_log_root: Path, mica_source: str) -> pd.DataFrame: | |
| required_columns = { | |
| "Sensor", | |
| "Variant", | |
| "Scale", | |
| "F1_BE", | |
| "F1_NPV", | |
| "F1_PV", | |
| "IoU_BE", | |
| "IoU_NPV", | |
| "IoU_PV", | |
| } | |
| metrics = pd.read_csv(metrics_csv) | |
| missing = sorted(required_columns.difference(metrics.columns)) | |
| if missing: | |
| raise ValueError(f"Missing required columns in {metrics_csv}: {', '.join(missing)}") | |
| if mica_source == "robust": | |
| robust_metrics = load_mica_robust_metrics(robust_log_root) | |
| if not robust_metrics.empty: | |
| metrics = pd.concat([metrics[metrics["Sensor"] != "MICA"], robust_metrics], ignore_index=True) | |
| else: | |
| print( | |
| f"Warning: no MICA robust logs found under {robust_log_root}; using MICA rows from {metrics_csv}.", | |
| file=sys.stderr, | |
| ) | |
| metrics["ModelVariant"] = metrics["Variant"].map(model_variant) | |
| return metrics[metrics["ModelVariant"].isin(MODEL_ORDER)].copy() | |
| def filter_sensor_scope(metrics: pd.DataFrame, sensor_scope: str) -> pd.DataFrame: | |
| if sensor_scope == "all": | |
| scoped = metrics | |
| elif sensor_scope == "hyspec": | |
| scoped = metrics[metrics["Sensor"] != "MICA"] | |
| else: | |
| scoped = metrics[metrics["Sensor"] == "MICA"] | |
| if scoped.empty: | |
| raise ValueError(f"No metrics remain after applying --sensor-scope={sensor_scope}") | |
| return scoped.copy() | |
| def aggregate_class_metrics(metrics: pd.DataFrame, metric: str) -> pd.DataFrame: | |
| prefix = "F1" if metric == "f1" else "IoU" | |
| columns = [f"{prefix}_{class_name}" for class_name in CLASS_ORDER] | |
| summary = metrics.groupby("ModelVariant", sort=False)[columns].mean().reindex(MODEL_ORDER) | |
| summary.index.name = "Variant" | |
| summary = summary.rename(columns={f"{prefix}_{class_name}": class_name for class_name in CLASS_ORDER}) | |
| return summary | |
| def aggregate_sensor_class_metrics(metrics: pd.DataFrame, metric: str) -> pd.DataFrame: | |
| prefix = "F1" if metric == "f1" else "IoU" | |
| columns = [f"{prefix}_{class_name}" for class_name in CLASS_ORDER] | |
| summary = metrics.groupby(["Sensor", "ModelVariant"], sort=False)[columns].mean().reset_index() | |
| summary["Sensor"] = pd.Categorical(summary["Sensor"], categories=SENSOR_ORDER, ordered=True) | |
| summary["ModelVariant"] = pd.Categorical(summary["ModelVariant"], categories=MODEL_ORDER, ordered=True) | |
| summary = summary.sort_values(["Sensor", "ModelVariant"]) | |
| return summary.rename(columns={f"{prefix}_{class_name}": class_name for class_name in CLASS_ORDER}) | |
| def annotate_bars(ax: plt.Axes, fontsize: int = 8) -> None: | |
| for container in ax.containers: | |
| ax.bar_label(container, fmt="%.2f", fontsize=fontsize, padding=2, rotation=90) | |
| def add_variant_mean_line( | |
| ax: plt.Axes, | |
| mean_values: pd.Series, | |
| metric_label: str, | |
| color: str = "#fc3468", | |
| fontsize: int = 8, | |
| ) -> None: | |
| ordered_means = mean_values.reindex(MODEL_ORDER) | |
| x_positions = list(range(len(MODEL_ORDER))) | |
| ax.plot( | |
| x_positions, | |
| ordered_means, | |
| color=color, | |
| marker=".", | |
| markerfacecolor="pink", | |
| markeredgecolor=color, | |
| linewidth=1.8, | |
| linestyle="solid", | |
| markersize=11, | |
| label=f"Mean {metric_label}", | |
| zorder=5, | |
| ) | |
| for x_position, value in zip(x_positions, ordered_means): | |
| if pd.isna(value): | |
| continue | |
| ax.annotate( | |
| f"{value:.2f}", | |
| xy=(x_position, value), | |
| xytext=(0, 7), | |
| textcoords="offset points", | |
| ha="center", | |
| va="bottom", | |
| fontsize=fontsize, | |
| fontweight="bold", | |
| color=color, | |
| ) | |
| def save_grouped_bar( | |
| summary: pd.DataFrame, | |
| output_dir: Path, | |
| output_stem: str, | |
| metric_label: str, | |
| palette_name: str, | |
| ) -> None: | |
| plot_data = summary.reset_index().melt(id_vars="Variant", var_name="Class", value_name=metric_label) | |
| colors = sns.color_palette(palette_name, n_colors=len(CLASS_ORDER)) | |
| palette = dict(zip(CLASS_ORDER, colors)) | |
| fig, ax = plt.subplots(figsize=(7.6, 5.8)) | |
| sns.barplot( | |
| data=plot_data, | |
| x="Variant", | |
| y=metric_label, | |
| hue="Class", | |
| order=MODEL_ORDER, | |
| hue_order=CLASS_ORDER, | |
| palette=palette, | |
| edgecolor="white", | |
| linewidth=0.7, | |
| ax=ax, | |
| ) | |
| ax.set_xlabel("Model variant") | |
| ax.set_ylabel(metric_label) | |
| ax.set_ylim(0, Y_AXIS_MAX) | |
| ax.set_yticks(VALUE_TICKS) | |
| ax.grid(axis="y", linestyle="--", alpha=0.3) | |
| annotate_bars(ax, fontsize=12) | |
| add_variant_mean_line(ax, summary[CLASS_ORDER].mean(axis=1), metric_label, fontsize=14) | |
| ax.legend(title="Class / mean", frameon=False, ncols=4, loc="upper center", bbox_to_anchor=(0.5, 1.24)) | |
| fig.tight_layout() | |
| fig.savefig(output_dir / f"{output_stem}.png", dpi=300, bbox_inches="tight") | |
| fig.savefig(output_dir / f"{output_stem}.pdf", bbox_inches="tight") | |
| plt.close(fig) | |
| def save_sensor_faceted_bar( | |
| summary: pd.DataFrame, | |
| output_dir: Path, | |
| output_stem: str, | |
| metric_label: str, | |
| palette_name: str, | |
| ) -> None: | |
| plot_data = summary.melt( | |
| id_vars=["Sensor", "ModelVariant"], | |
| value_vars=CLASS_ORDER, | |
| var_name="Class", | |
| value_name=metric_label, | |
| ) | |
| plot_data["SensorLabel"] = plot_data["Sensor"].astype(str).str.replace("_", "-", regex=False) | |
| sensors = [sensor for sensor in SENSOR_ORDER if sensor in set(summary["Sensor"].astype(str))] | |
| colors = sns.color_palette(palette_name, n_colors=len(CLASS_ORDER)) | |
| palette = dict(zip(CLASS_ORDER, colors)) | |
| ncols = 2 if len(sensors) > 1 else 1 | |
| nrows = (len(sensors) + ncols - 1) // ncols | |
| fig, axes = plt.subplots(nrows, ncols, figsize=(5.8 * ncols, 5.0 * nrows), sharey=True) | |
| if nrows == 1 and ncols == 1: | |
| axes = [axes] | |
| else: | |
| axes = list(axes.flat) | |
| for ax, sensor in zip(axes, sensors): | |
| sensor_data = plot_data[plot_data["Sensor"].astype(str) == sensor] | |
| sns.barplot( | |
| data=sensor_data, | |
| x="ModelVariant", | |
| y=metric_label, | |
| hue="Class", | |
| order=MODEL_ORDER, | |
| hue_order=CLASS_ORDER, | |
| palette=palette, | |
| edgecolor="white", | |
| linewidth=0.6, | |
| ax=ax, | |
| ) | |
| sensor_label = sensor.replace("_", "-") | |
| ax.set_title(sensor_label) | |
| ax.set_xlabel("Model variant" if sensor == "FX10" else "") | |
| ax.set_ylabel(metric_label if ax is axes[0] else "") | |
| ax.set_ylim(0, Y_AXIS_MAX) | |
| ax.set_yticks(VALUE_TICKS) | |
| ax.grid(axis="y", linestyle="--", alpha=0.28) | |
| annotate_bars(ax, fontsize=14) | |
| sensor_summary = summary[summary["Sensor"].astype(str) == sensor].set_index("ModelVariant") | |
| add_variant_mean_line(ax, sensor_summary[CLASS_ORDER].mean(axis=1), metric_label, fontsize=14) | |
| if ax.legend_: | |
| ax.legend_.remove() | |
| for ax in axes[len(sensors) :]: | |
| ax.axis("off") | |
| handles, labels = axes[0].get_legend_handles_labels() | |
| fig.legend(handles, labels, title="Class / mean", loc="upper center", ncols=len(CLASS_ORDER) + 1, frameon=False) | |
| fig.tight_layout(rect=(0, 0, 1, 0.90)) | |
| fig.savefig(output_dir / f"{output_stem}.png", dpi=300, bbox_inches="tight") | |
| fig.savefig(output_dir / f"{output_stem}.pdf", bbox_inches="tight") | |
| plt.close(fig) | |
| def save_heatmap( | |
| summary: pd.DataFrame, | |
| output_dir: Path, | |
| output_stem: str, | |
| metric_label: str, | |
| palette_name: str, | |
| ) -> None: | |
| fig, ax = plt.subplots(figsize=(5.6, 5.2)) | |
| sns.heatmap( | |
| summary, | |
| annot=True, | |
| fmt=".2f", | |
| cmap=palette_name, | |
| linewidths=0.6, | |
| linecolor="white", | |
| vmin=0, | |
| vmax=1, | |
| cbar_kws={"label": metric_label, "shrink": 0.82, "pad": 0.02}, | |
| ax=ax, | |
| ) | |
| ax.set_xlabel("Class") | |
| ax.set_ylabel("Model variant") | |
| ax.tick_params(axis="x", rotation=0) | |
| ax.tick_params(axis="y", rotation=0) | |
| fig.tight_layout() | |
| fig.savefig(output_dir / f"{output_stem}.png", dpi=300, bbox_inches="tight") | |
| fig.savefig(output_dir / f"{output_stem}.pdf", bbox_inches="tight") | |
| plt.close(fig) | |
| def write_summary(summary: pd.DataFrame, output_dir: Path, output_stem: str) -> None: | |
| output = summary.reset_index() | |
| output.insert(1, "Model description", output["Variant"].map(VARIANT_LABELS)) | |
| output.to_csv(output_dir / f"{output_stem}.csv", index=False) | |
| def write_class_means(summary: pd.DataFrame, output_dir: Path, output_stem: str) -> None: | |
| class_means = summary[CLASS_ORDER].mean().rename_axis("Class").reset_index(name="Mean") | |
| class_means.to_csv(output_dir / f"{output_stem}.csv", index=False) | |
| def write_sensor_summary(summary: pd.DataFrame, output_dir: Path, output_stem: str) -> None: | |
| output = summary.copy() | |
| output.insert(2, "Model description", output["ModelVariant"].astype(str).map(VARIANT_LABELS)) | |
| output.to_csv(output_dir / f"{output_stem}.csv", index=False) | |
| def output_suffix(mica_source: str, sensor_scope: str) -> str: | |
| scope_suffix = "" if sensor_scope == "all" else f"_{sensor_scope}" | |
| mica_suffix = "" if mica_source == "robust" else "_csv_mica" | |
| return f"{scope_suffix}{mica_suffix}" | |
| def plot_classwise_metrics( | |
| metrics_csv: Path, | |
| output_dir: Path, | |
| robust_log_root: Path, | |
| mica_source: str, | |
| metric: str, | |
| sensor_scope: str, | |
| ) -> None: | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| sns.set_theme( | |
| context="paper", | |
| style="white", | |
| rc={ | |
| "font.size": 16, | |
| "axes.labelsize": 16, | |
| "axes.titlesize": 16, | |
| "legend.fontsize": 16, | |
| "legend.title_fontsize": 16, | |
| "xtick.labelsize": 14, | |
| "ytick.labelsize": 14, | |
| }, | |
| ) | |
| metrics = filter_sensor_scope(load_metrics(metrics_csv, robust_log_root, mica_source), sensor_scope) | |
| summary = aggregate_class_metrics(metrics, metric) | |
| metric_label = "F1 score" if metric == "f1" else "IoU" | |
| metric_stem = "f1" if metric == "f1" else "iou" | |
| bar_palette = "cubehelix" if metric == "f1" else "cubehelix" #twilight | |
| heatmap_palette = "mako" if metric == "f1" else "BuPu_r" | |
| suffix = output_suffix(mica_source, sensor_scope) | |
| sensor_summary = aggregate_sensor_class_metrics(metrics, metric) | |
| write_summary(summary, output_dir, f"classwise_{metric_stem}_by_variant{suffix}") | |
| write_class_means(summary, output_dir, f"classwise_{metric_stem}_class_means{suffix}") | |
| save_grouped_bar(summary, output_dir, f"classwise_{metric_stem}_by_variant_bar{suffix}", metric_label, bar_palette) | |
| save_heatmap(summary, output_dir, f"classwise_{metric_stem}_by_variant_heatmap{suffix}", metric_label, heatmap_palette) | |
| write_sensor_summary(sensor_summary, output_dir, f"classwise_{metric_stem}_by_sensor_variant{suffix}") | |
| save_sensor_faceted_bar( | |
| sensor_summary, | |
| output_dir, | |
| f"classwise_{metric_stem}_by_sensor_variant_bar{suffix}", | |
| metric_label, | |
| bar_palette, | |
| ) | |
| def parse_args() -> argparse.Namespace: | |
| repo_root = Path(__file__).resolve().parents[1] | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument( | |
| "--metrics-csv", | |
| type=Path, | |
| default=repo_root / "phase_3_models/performance_metrics/sensor_metrics.csv", | |
| help="CSV produced by scripts/collect_sensor_metrics.py.", | |
| ) | |
| parser.add_argument( | |
| "--output-dir", | |
| type=Path, | |
| default=repo_root / "figures", | |
| help="Directory for class-wise variant figures.", | |
| ) | |
| parser.add_argument( | |
| "--robust-log-root", | |
| type=Path, | |
| default=repo_root / "logs/sensor_profile_runs", | |
| help="Root containing MICA robust run logs used when --mica-source=robust.", | |
| ) | |
| parser.add_argument( | |
| "--mica-source", | |
| choices=("robust", "csv"), | |
| default="robust", | |
| help="Use MICA robust best-test logs for the MICA row, or MICA rows from the metrics CSV.", | |
| ) | |
| parser.add_argument( | |
| "--metric", | |
| choices=("f1", "iou"), | |
| default="f1", | |
| help="Class-wise metric to plot. Default: f1.", | |
| ) | |
| parser.add_argument( | |
| "--sensor-scope", | |
| choices=("all", "hyspec", "mica"), | |
| default="all", | |
| help="Sensor rows to aggregate: all, hyspec (exclude MICA), or mica only. Default: all.", | |
| ) | |
| return parser.parse_args() | |
| def main() -> None: | |
| args = parse_args() | |
| plot_classwise_metrics( | |
| args.metrics_csv, | |
| args.output_dir, | |
| args.robust_log_root, | |
| args.mica_source, | |
| args.metric, | |
| args.sensor_scope, | |
| ) | |
| if __name__ == "__main__": | |
| main() |