100 lines
3.6 KiB
Python
100 lines
3.6 KiB
Python
from __future__ import annotations
|
||
from pathlib import Path
|
||
import re, json
|
||
import pandas as pd
|
||
import matplotlib.pyplot as plt
|
||
|
||
class Visualizer:
|
||
"""
|
||
Liest results_{dataset}_{technique}.json und hält ein langes DataFrame.
|
||
• ein Record pro (dataset, technique, category, metric)
|
||
• keine Aggregation nötig – jede Datei enthält EINEN Wert je Metrik
|
||
"""
|
||
|
||
_PTN = re.compile(r"results_(?P<dataset>[^_]+)_(?P<technique>[^.]+)\.json$")
|
||
|
||
def __init__(self, json_dir: str | Path):
|
||
self.json_dir = Path(json_dir)
|
||
if not self.json_dir.exists():
|
||
raise FileNotFoundError(self.json_dir)
|
||
self.df = self._load_jsons()
|
||
|
||
# ------------------------------------------------------------------
|
||
# Public helpers
|
||
# ------------------------------------------------------------------
|
||
def datasets(self) -> list[str]:
|
||
return sorted(self.df["dataset"].unique())
|
||
|
||
def categories(self) -> list[str]:
|
||
return sorted(self.df["category"].unique())
|
||
|
||
def metrics_of(self, category: str) -> list[str]:
|
||
return sorted(self.df[self.df["category"] == category]["metric"].unique())
|
||
|
||
# -- Kernplot -------------------------------------------------------
|
||
def plot_category_by_tech(self,
|
||
dataset: str,
|
||
category: str,
|
||
figsize=(9, 5),
|
||
save: str | Path | None = None):
|
||
"""
|
||
Ein Balkendiagramm: alle Metriken dieser Kategorie,
|
||
gruppiert nach Technik, nur für EIN Dataset.
|
||
"""
|
||
sub = self.df[(self.df["dataset"] == dataset) &
|
||
(self.df["category"] == category)]
|
||
if sub.empty:
|
||
print(f"[⚠] Kein Eintrag für Dataset={dataset}, Cat={category}")
|
||
return
|
||
|
||
# Pivot: index = technique, columns = metrics
|
||
pivot = sub.pivot(index="technique", columns="metric", values="value")
|
||
# Interpret the metric name as latex code for maths
|
||
pivot.columns = [f"${c}$" for c in pivot.columns]
|
||
|
||
print(pivot)
|
||
fig, ax = plt.subplots(figsize=figsize)
|
||
pivot.plot(kind="bar", ax=ax)
|
||
ax.set_xlabel("") # X axis should have no title
|
||
ax.tick_params(axis='x', rotation=0) # X axis should have no title
|
||
|
||
|
||
|
||
ax.set_ylim(0, 100)
|
||
ax.set_yticklabels([f"{y}%" for y in ax.get_yticks()])
|
||
|
||
ax.grid(axis="y", linestyle="--", alpha=0.4)
|
||
ax.legend(loc="lower left") #best
|
||
# ax.legend(bbox_to_anchor=(1.02, 1), loc="lower left") #best
|
||
|
||
plt.tight_layout()
|
||
if save:
|
||
fig.savefig(save, dpi=150, bbox_inches="tight")
|
||
plt.close(fig)
|
||
return fig, ax
|
||
|
||
|
||
|
||
# ------------------------------------------------------------------
|
||
# intern
|
||
# ------------------------------------------------------------------
|
||
def _load_jsons(self) -> pd.DataFrame:
|
||
recs = []
|
||
for file in self.json_dir.glob("results_*_*.json"):
|
||
m = self._PTN.match(file.name)
|
||
if not m:
|
||
continue
|
||
dataset, tech = m.group("dataset"), m.group("technique")
|
||
data = json.load(open(file, "r"))
|
||
|
||
for cat, metrics in data.items():
|
||
for metric, val in metrics.items():
|
||
recs.append({"dataset": dataset,
|
||
"technique": tech,
|
||
"category": cat,
|
||
"metric": metric,
|
||
"value": val})
|
||
if not recs:
|
||
raise RuntimeError("Keine passenden JSON-Dateien gefunden.")
|
||
return pd.DataFrame.from_records(recs)
|