File size: 4,366 Bytes
3c41fb5 | 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 | #!/usr/bin/env python3
"""Standalone figures: t-SNE, 3-D PCA (PC1-PC3), and 2-D PCA (PC1/PC2).
One plot per file so each can be dropped into a slide on its own. Every title
carries the held-out classification accuracy reachable from exactly the axes
drawn, so a reader can tell apart "looks separated" from "is separated".
Held-out episodes only; splits are by episode because frames within an episode
are near-duplicates.
"""
import argparse
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.manifold import TSNE
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
DIA = {"cable 1.70 sq": 1.7, "blue cable": 2.6, "cable 3.30 sq": 4.5}
NAME = {1.7: "1.7 mm", 2.6: "2.6 mm", 4.5: "4.5 mm"}
COLOR = {1.7: "#C05621", 2.6: "#2B6CB0", 4.5: "#2F855A"}
def acc(A, y, tr, cols=None):
Z = A if cols is None else A[:, cols]
c = make_pipeline(StandardScaler(), LogisticRegression(max_iter=3000)).fit(Z[tr], y[tr])
return c.score(Z[~tr], y[~tr])
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--cache", default="outputs/pca/cache_cable_feats.npz")
ap.add_argument("--outdir", default="outputs/pca")
ap.add_argument("--perplexity", type=float, default=30.0)
args = ap.parse_args()
d = np.load(args.cache, allow_pickle=True)
X, y, ep = d["feats"], d["y"], d["eps"]
rng = np.random.default_rng(0)
tr = np.zeros(len(y), bool)
for t in np.unique(y):
e = np.unique(ep[y == t])
tr |= np.isin(ep, rng.choice(e, size=int(len(e) * 0.7), replace=False))
te = ~tr
order = sorted(set(y), key=lambda s: DIA[s])
Xc = X - X.mean(0)
p = PCA(n_components=30).fit(Xc)
Z, evr = p.transform(Xc), p.explained_variance_ratio_
plt.rcParams.update({"font.family": ["DejaVu Sans"], "font.size": 12})
# --- 1) t-SNE only
emb = TSNE(n_components=2, perplexity=args.perplexity, init="pca",
random_state=0).fit_transform(Z)
fig, ax = plt.subplots(figsize=(7.2, 6.4))
for t in order:
m = te & (y == t)
ax.scatter(emb[m, 0], emb[m, 1], s=18, alpha=0.65, edgecolors="none",
c=COLOR[DIA[t]], label=NAME[DIA[t]])
ax.set_xlabel("t-SNE 1"); ax.set_ylabel("t-SNE 2")
ax.set_title(f"t-SNE (perplexity {args.perplexity:g})", fontsize=13)
ax.legend(frameon=False, title="cable diameter")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout(); fig.savefig(f"{args.outdir}/cable_tsne.png", dpi=160, bbox_inches="tight")
print(f"wrote {args.outdir}/cable_tsne.png")
# --- 2) 3-D PCA, default first three components
a3 = acc(Z, y, tr, [0, 1, 2])
fig = plt.figure(figsize=(7.6, 6.6))
ax = fig.add_subplot(111, projection="3d")
for t in order:
m = te & (y == t)
ax.scatter(Z[m, 0], Z[m, 1], Z[m, 2], s=11, alpha=0.55, edgecolors="none",
c=COLOR[DIA[t]], label=NAME[DIA[t]])
ax.set_xlabel("PC1"); ax.set_ylabel("PC2"); ax.set_zlabel("PC3")
ax.set_title(f"3-D PCA (PC1-PC3)\n{a3:.1%} accuracy (chance 33.3%)", fontsize=13)
ax.legend(frameon=False, title="cable diameter", loc="upper left")
ax.view_init(elev=18, azim=-60)
fig.tight_layout(); fig.savefig(f"{args.outdir}/cable_pca3d_pc123.png", dpi=160, bbox_inches="tight")
print(f"wrote {args.outdir}/cable_pca3d_pc123.png ({a3:.1%})")
# --- 3) 2-D PCA, default components
a2 = acc(Z, y, tr, [0, 1])
fig, ax = plt.subplots(figsize=(7.2, 6.4))
for t in order:
m = te & (y == t)
ax.scatter(Z[m, 0], Z[m, 1], s=18, alpha=0.65, edgecolors="none",
c=COLOR[DIA[t]], label=NAME[DIA[t]])
ax.set_xlabel(f"PC1 ({evr[0]:.1%} of variance)")
ax.set_ylabel(f"PC2 ({evr[1]:.1%} of variance)")
ax.set_title(f"PCA (PC1 vs PC2)\n{a2:.1%} accuracy (chance 33.3%)", fontsize=13)
ax.legend(frameon=False, title="cable diameter")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout(); fig.savefig(f"{args.outdir}/cable_pca2d_pc12.png", dpi=160, bbox_inches="tight")
print(f"wrote {args.outdir}/cable_pca2d_pc12.png ({a2:.1%})")
if __name__ == "__main__":
main()
|