File size: 4,910 Bytes
78be280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import json
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt

RUNS = Path("/workspace/runs")
TMAX_VALUES = [1, 2, 6, 10, 15]
STRATEGY = "strategy_3"


def run_dir(tmax: int) -> Path:
    return (
        RUNS
        / f"Segformer_B0_simplified_tmax_{tmax}"
        / "repeated_holdout"
        / "stratified_holdout_v1"
        / "phase_001"
        / "pct_100"
        / "repeat_01"
        / STRATEGY
        / "final"
    )


def load_json(p: Path):
    with open(p) as f:
        return json.load(f)


records = []
for tmax in TMAX_VALUES:
    d = run_dir(tmax)
    evaluation = load_json(d / "evaluation.json")
    summary = load_json(d / "summary.json")

    metrics = evaluation["metrics"]
    timing = evaluation["timing"]

    records.append(
        {
            "tmax": tmax,
            # Segmentation quality on the held-out test set (mean +/- std)
            "biou_contour_mean": metrics["biou_contour"]["mean"],
            "biou_contour_std": metrics["biou_contour"]["std"],
            "dice_mean": metrics["dice"]["mean"],
            "dice_std": metrics["dice"]["std"],
            "iou_mean": metrics["iou"]["mean"],
            "iou_std": metrics["iou"]["std"],
            # Training cost
            "train_total_s": summary["elapsed_seconds"],
            "train_to_best_s": summary["time_to_best_seconds"],
            "sec_per_epoch": summary["seconds_per_epoch_measured_mean"],
            "sec_per_epoch_std": summary["seconds_per_epoch_measured_std"],
            "best_epoch": summary["best_epoch"],
            # Inference cost (per image, test set)
            "infer_ms_mean": timing["mean_per_image_inference_ms"],
            "infer_ms_std": timing["std_per_image_inference_ms"],
        }
    )

tmax = [r["tmax"] for r in records]

print(f"{'tmax':>5} {'biou_contour':>18} {'dice':>18} {'iou':>18} {'train_total_s':>14} {'sec/epoch':>12} {'best_ep':>8} {'infer_ms/img':>16}")
for r in records:
    print(
        f"{r['tmax']:>5} "
        f"{r['biou_contour_mean']:.4f}+/-{r['biou_contour_std']:.4f} "
        f"{r['dice_mean']:.4f}+/-{r['dice_std']:.4f} "
        f"{r['iou_mean']:.4f}+/-{r['iou_std']:.4f} "
        f"{r['train_total_s']:>14.1f} "
        f"{r['sec_per_epoch']:>12.3f} "
        f"{r['best_epoch']:>8} "
        f"{r['infer_ms_mean']:>10.3f}+/-{r['infer_ms_std']:.3f}"
    )

import numpy as np


def add_labels(ax, bars, fmt="{:.2f}"):
    for b in bars:
        h = b.get_height()
        ax.annotate(
            fmt.format(h),
            xy=(b.get_x() + b.get_width() / 2, h),
            xytext=(0, 3),
            textcoords="offset points",
            ha="center",
            va="bottom",
            fontsize=8,
        )


x = np.arange(len(tmax))
labels = [str(t) for t in tmax]

fig, axes = plt.subplots(1, 3, figsize=(17, 5.5))
fig.suptitle(
    "Segformer-B0 simplified (strategy 3, phase 1) - metrics vs T_max",
    fontsize=14,
    fontweight="bold",
)

# ---- 1) Segmentation quality (test set) : grouped bars ----
ax = axes[0]
w = 0.27
b1 = ax.bar(x - w, [r["dice_mean"] for r in records], w, yerr=[r["dice_std"] for r in records], capsize=3, color="tab:blue", label="Dice")
b2 = ax.bar(x, [r["iou_mean"] for r in records], w, yerr=[r["iou_std"] for r in records], capsize=3, color="tab:green", label="IoU")
b3 = ax.bar(x + w, [r["biou_contour_mean"] for r in records], w, yerr=[r["biou_contour_std"] for r in records], capsize=3, color="tab:orange", label="bIoU contour")
add_labels(ax, b1)
add_labels(ax, b2)
add_labels(ax, b3)
ax.set_title("Segmentation quality (test set, mean +/- std)")
ax.set_xlabel("T_max")
ax.set_ylabel("score")
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.set_ylim(0, 1.05)
ax.grid(True, axis="y", alpha=0.3)
ax.legend()

# ---- 2) Training time : grouped bars ----
ax = axes[1]
w = 0.4
b1 = ax.bar(x - w / 2, [r["train_total_s"] for r in records], w, color="tab:red", label="total training time")
b2 = ax.bar(x + w / 2, [r["train_to_best_s"] for r in records], w, color="tab:orange", label="time to best checkpoint")
add_labels(ax, b1, fmt="{:.0f}")
add_labels(ax, b2, fmt="{:.0f}")
ax.set_title("Training time")
ax.set_xlabel("T_max")
ax.set_ylabel("seconds")
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.grid(True, axis="y", alpha=0.3)
ax.legend()

# ---- 3) Inference time (per image) : bars ----
ax = axes[2]
b1 = ax.bar(x, [r["infer_ms_mean"] for r in records], 0.6, yerr=[r["infer_ms_std"] for r in records], capsize=4, color="tab:purple", label="per-image inference (mean +/- std)")
add_labels(ax, b1)
ax.set_title("Inference time (test set)")
ax.set_xlabel("T_max")
ax.set_ylabel("ms / image")
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.grid(True, axis="y", alpha=0.3)
ax.legend()

fig.tight_layout(rect=[0, 0, 1, 0.96])
out = RUNS.parent / "tmax_biou_training_inference.png"
fig.savefig(out, dpi=150)
print(f"\nSaved figure to {out}")