File size: 3,935 Bytes
868ad5a | 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 | """第 2 周实验作图(在读得到 matplotlib 的环境里跑:class1 / rl)
pytorch_env 的 matplotlib 3.9.4 在 savefig 时必崩(0xc06d007f),所以训练与作图分开:
pytorch_env\\python.exe week2_lab.py -> week2-out/{results.json, fit_curve.npz, samples.npz}
class1\\python.exe plot_week2.py -> week2-out/01..04*.png
"""
import json
from pathlib import Path
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
HERE = Path(__file__).resolve().parent
OUT = HERE / "week2-out"
res = json.loads((OUT / "results.json").read_text(encoding="utf-8"))
print("loaded results:", sorted(res.keys()))
def save(fig, name):
p = OUT / name
fig.tight_layout()
fig.savefig(p, dpi=130)
plt.close(fig)
print("wrote", p.name, f"({p.stat().st_size / 1024:.1f} KiB)")
# ---- 01 函数拟合 ----
fit = res.get("function_fit")
if fit:
curve = np.load(OUT / "fit_curve.npz")
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
axes[0].plot(fit["history"], lw=1.2)
axes[0].set_xlabel("epoch")
axes[0].set_ylabel("MSE loss")
axes[0].set_title(f"Function fitting: training loss ({fit['epochs']} epochs)")
axes[0].set_yscale("log")
axes[0].grid(alpha=0.3, which="both")
axes[1].plot(curve["x"], curve["y_true"], label="target", lw=2)
axes[1].plot(curve["x"], curve["y_pred"], "--", label="network", lw=2)
axes[1].set_xlabel("x")
axes[1].set_ylabel("y")
axes[1].set_title(f"Fit result (MSE={fit['fit_mse']:.4f})")
axes[1].legend()
axes[1].grid(alpha=0.3)
save(fig, "01_function_fit.png")
# ---- 02 MNIST 学习曲线 ----
models = [("mlp", "MLP"), ("cnn", "CNN"), ("lstm", "LSTM"), ("gru", "GRU")]
present = [(k, n) for k, n in models if k in res]
if present:
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
for k, n in present:
axes[0].plot(res[k]["val_loss"], marker="o", label=f"{n} (test {res[k]['test_acc'] * 100:.2f}%)")
axes[1].plot([a * 100 for a in res[k]["val_acc"]], marker="o", label=n)
axes[0].set_xlabel("epoch")
axes[0].set_ylabel("validation loss")
axes[0].set_title("MNIST: validation loss")
axes[1].set_xlabel("epoch")
axes[1].set_ylabel("validation accuracy (%)")
axes[1].set_title("MNIST: validation accuracy")
for ax in axes:
ax.grid(alpha=0.3)
ax.legend()
ax.set_xticks(range(len(present[0]) and len(res[present[0][0]]["val_loss"])))
ax.set_xticklabels([f"{i + 1}" for i in range(len(res[present[0][0]]["val_loss"]))])
save(fig, "02_mnist_curves.png")
# ---- 03 模型对比 ----
if present:
names = [n for _, n in present]
accs = [res[k]["test_acc"] * 100 for k, _ in present]
secs = [res[k]["seconds"] for k, _ in present]
fig, ax = plt.subplots(figsize=(7.5, 4))
colors = ["#4c72b0", "#dd8452", "#55a868", "#c44e52"]
bars = ax.bar(names, accs, color=colors[:len(names)])
ax.set_ylabel("test accuracy (%)")
ax.set_ylim(max(0, min(accs) - 3), 100)
ax.set_title(f"MNIST test accuracy after {res[present[0][0]]['epochs']} epochs")
for b, a, s in zip(bars, accs, secs):
ax.text(b.get_x() + b.get_width() / 2, b.get_height() + 0.1,
f"{a:.2f}%\n{s:.0f}s", ha="center", va="bottom", fontsize=9)
ax.grid(alpha=0.3, axis="y")
save(fig, "03_model_compare.png")
# ---- 04 预测样例 ----
sp = OUT / "samples.npz"
if sp.exists():
d = np.load(sp)
fig, axes = plt.subplots(2, 4, figsize=(10, 5.2))
for i, ax in enumerate(axes.ravel()):
ax.imshow(d["images"][i], cmap="gray")
ok = int(d["preds"][i]) == int(d["labels"][i])
ax.set_title(f"true {int(d['labels'][i])} / pred {int(d['preds'][i])}",
color="green" if ok else "red", fontsize=9)
ax.axis("off")
fig.suptitle("MNIST CNN predictions")
save(fig, "04_predictions.png")
print("PLOTS DONE")
|