File size: 4,125 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 104 105 | #!/usr/bin/env python3
"""3-D PCA of the ACT encoder space, coloured by cable diameter.
Two 3-D views side by side:
left : PC1-PC3, the default first-three-components choice
right : PC1, PC3, PC4 -- the best-separating triple, found by scoring every
3-combination of the first 8 components on held-out episodes
Showing both matters: the default triple reaches only 57% while the best reaches
86%, and quoting the latter without the former would look like a cherry-picked
projection. Each title carries the accuracy obtainable from exactly those axes.
Also writes a rotating GIF of the right-hand view, since a static 3-D scatter
hides depth structure.
"""
import argparse
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
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(Z, y, tr, cols):
c = make_pipeline(StandardScaler(), LogisticRegression(max_iter=3000))
c.fit(Z[tr][:, cols], y[tr])
return c.score(Z[~tr][:, cols], y[~tr])
def scatter3d(ax, Z, y, te, cols, title):
for t in sorted(set(y), key=lambda s: DIA[s]):
m = te & (y == t)
ax.scatter(Z[m, cols[0]], Z[m, cols[1]], Z[m, cols[2]],
s=10, alpha=0.55, edgecolors="none", c=COLOR[DIA[t]], label=NAME[DIA[t]])
ax.set_xlabel(f"PC{cols[0]+1}"); ax.set_ylabel(f"PC{cols[1]+1}"); ax.set_zlabel(f"PC{cols[2]+1}")
ax.set_title(title, fontsize=12)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--cache", default="outputs/pca/cache_cable_feats.npz")
ap.add_argument("--out", default="outputs/pca/cable_pca3d.png")
ap.add_argument("--gif", default="outputs/pca/cable_pca3d_rotating.gif")
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
Xc = X - X.mean(0)
p = PCA(n_components=12).fit(Xc)
Z, evr = p.transform(Xc), p.explained_variance_ratio_
default_cols, best_cols = [0, 1, 2], [0, 2, 3]
a_def, a_best = acc(Z, y, tr, default_cols), acc(Z, y, tr, best_cols)
plt.rcParams.update({"font.family": ["DejaVu Sans"], "font.size": 11})
fig = plt.figure(figsize=(14, 6.4))
ax1 = fig.add_subplot(1, 2, 1, projection="3d")
scatter3d(ax1, Z, y, te, default_cols,
f"PC1-PC3 (default)\n{a_def:.1%} accuracy (chance 33.3%)")
ax2 = fig.add_subplot(1, 2, 2, projection="3d")
scatter3d(ax2, Z, y, te, best_cols,
f"PC1, PC3, PC4 (best triple)\n{a_best:.1%} accuracy")
ax2.legend(frameon=False, fontsize=10, loc="upper left")
for ax in (ax1, ax2):
ax.view_init(elev=18, azim=-60)
fig.tight_layout()
fig.savefig(args.out, dpi=150, bbox_inches="tight")
print(f"wrote {args.out}")
# Rotating view of the best triple -- depth is invisible in a still.
figr = plt.figure(figsize=(7, 6.4))
axr = figr.add_subplot(111, projection="3d")
scatter3d(axr, Z, y, te, best_cols, f"PC1, PC3, PC4 — {a_best:.1%} accuracy")
axr.legend(frameon=False, fontsize=10, loc="upper left")
def rot(i):
axr.view_init(elev=18, azim=i * 4)
return []
FuncAnimation(figr, rot, frames=90, interval=80).save(
args.gif, writer=PillowWriter(fps=12))
print(f"wrote {args.gif}")
print(f"\n variance: " + " ".join(f"PC{i+1} {evr[i]:.1%}" for i in (0, 1, 2, 3)))
print(f" PC1-PC3 {a_def:.1%}")
print(f" PC1,PC3,PC4 {a_best:.1%}")
if __name__ == "__main__":
main()
|