Repository navigation
Expand file tree
/
Copy pathplot_training.py
More file actions
124 lines (102 loc) · 5.29 KB
/
Copy pathplot_training.py
File metadata and controls
124 lines (102 loc) · 5.29 KB
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
#!/usr/bin/env python
"""Plot a training run's loss curves and validation metrics from its metrics.json, to spot over-fitting.
pixi run python plot_training.py output/partmaterialcatseg_paco_dms # works while training too
pixi run python plot_training.py output/partcatseg_paco_tabletop --smooth 50
Writes <run dir>/training_curves.png with one panel per loss (train vs held-out) plus one for the
validation metrics, and prints the numbers behind the over-fitting read-out.
Reading it: train loss falls throughout. Over-fitting shows as the held-out loss (val_*, from
ValLossHook, TEST.VAL_LOSS_PERIOD) flattening and then rising while train keeps falling, and as
validation mIoU peaking and then dropping. Runs without ValLossHook (e.g. the PACO-only run) have
only the train losses and the periodic mIoU.
"""
import argparse
import json
import os
from pathlib import Path
os.environ.setdefault("MPLBACKEND", "Agg")
import matplotlib.pyplot as plt # noqa: E402
import numpy as np # noqa: E402
TRAIN, VAL = "#2a78d6", "#eb6834" # categorical slots 1 and 2
INK, MUTED, GRID, SURFACE = "#0b0b0b", "#898781", "#e1e0d9", "#fcfcfb"
LOSSES = [("loss_sem_seg", "Part loss (PACO)"), ("loss_material", "Material loss (DMS)")]
METRICS = [("oracle_obj/mIoU-base", "Parts, PACO val (mIoU-base)"),
("material_seg/mIoU", "Materials, DMS val 1k (mIoU)")]
def read_metrics(path):
records = []
for line in open(path):
line = line.strip()
if line:
records.append(json.loads(line))
# a resumed run appends: keep the last record written for each iteration
by_iter = {}
for r in records:
by_iter.setdefault(r["iteration"], {}).update(r)
return [by_iter[i] for i in sorted(by_iter)]
def series(records, key):
pts = [(r["iteration"], r[key]) for r in records if key in r]
return (np.array([p[0] for p in pts]), np.array([p[1] for p in pts], dtype=float)) if pts else (None, None)
def smooth(y, window):
if len(y) < window:
return y
kernel = np.ones(window) / window
head = np.cumsum(y[:window - 1]) / np.arange(1, window) # partial windows at the start
return np.concatenate([head, np.convolve(y, kernel, mode="valid")])
def style(ax, title, ylabel):
ax.set_facecolor(SURFACE)
ax.set_title(title, loc="left", color=INK, fontsize=11)
ax.set_xlabel("iteration", color=MUTED)
ax.set_ylabel(ylabel, color=MUTED)
ax.grid(True, color=GRID, linewidth=0.6)
ax.tick_params(colors=MUTED, labelsize=8)
for side in ("top", "right"):
ax.spines[side].set_visible(False)
for side in ("left", "bottom"):
ax.spines[side].set_color(GRID)
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("run_dir", help="a training OUTPUT_DIR containing metrics.json")
ap.add_argument("--smooth", type=int, default=25, help="moving-average window over logged train points")
ap.add_argument("--out", help="default: <run_dir>/training_curves.png")
args = ap.parse_args()
run = Path(args.run_dir)
records = read_metrics(run / "metrics.json")
losses = [(k, t) for k, t in LOSSES if series(records, k)[0] is not None]
if not losses: # a PartCATSeg-only run logs a single loss
losses = [("total_loss", "Training loss")]
metrics = [(k, t) for k, t in METRICS if series(records, k)[0] is not None]
if not metrics and series(records, "oracle_obj/mIoU")[0] is not None:
metrics = [("oracle_obj/mIoU", "Parts, val (mIoU)")]
panels = len(losses) + (1 if metrics else 0)
fig, axes = plt.subplots(1, panels, figsize=(5.2 * panels, 3.8), facecolor=SURFACE, squeeze=False)
axes = axes[0]
print(f"{run}: {len(records)} logged iterations, last {records[-1]['iteration']}")
for ax, (key, title) in zip(axes, losses):
x, y = series(records, key)
ax.plot(x, y, color=TRAIN, linewidth=0.8, alpha=0.25)
ax.plot(x, smooth(y, args.smooth), color=TRAIN, linewidth=2, label=f"train (moving avg {args.smooth})")
vx, vy = series(records, f"val_{key}")
if vx is not None:
ax.plot(vx, vy, color=VAL, linewidth=2, marker="o", markersize=6, label="held-out")
best = int(np.argmin(vy))
print(f" {key}: train {smooth(y, args.smooth)[-1]:.4f} (smoothed, last) | held-out "
f"{vy[-1]:.4f} at {vx[-1]}, lowest {vy[best]:.4f} at {vx[best]}")
else:
print(f" {key}: train {smooth(y, args.smooth)[-1]:.4f} (smoothed, last); no held-out loss logged")
style(ax, title, "loss")
ax.legend(frameon=False, fontsize=8, labelcolor=INK)
if metrics:
ax = axes[-1]
colors = [TRAIN, VAL]
for (key, title), color in zip(metrics, colors):
x, y = series(records, key)
ax.plot(x, y, color=color, linewidth=2, marker="o", markersize=6, label=title)
best = int(np.argmax(y))
print(f" {key}: last {y[-1]:.2f} at {x[-1]}, best {y[best]:.2f} at {x[best]}")
style(ax, "Validation metrics", "mIoU (%)")
ax.legend(frameon=False, fontsize=8, labelcolor=INK)
fig.tight_layout()
out = Path(args.out) if args.out else run / "training_curves.png"
fig.savefig(out, dpi=130, facecolor=SURFACE)
print(f"saved {out}")
if __name__ == "__main__":
main()