cable-representation-analysis / scripts /plot_cable_pca_tsne.py
Kaz55's picture
ACT encoder representation analysis: 3-cable + 4-size t-SNE, contact-phase PCA, diameter axis
3c41fb5 verified
Raw History Blame Contribute Delete
5.07 kB
#!/usr/bin/env python3
"""Cable separability in the ACT encoder space: PC1/PC2, 3-D PCA, and t-SNE.
Shows PC1/PC2 explicitly rather than jumping straight to the components that
happen to separate -- picking PC4/PC3 without showing the default view invites
the fair objection that the projection was cherry-picked. Each panel carries the
held-out classification accuracy obtainable from exactly the axes drawn, so the
figure can be read quantitatively instead of by eye.
All panels use held-out episodes. Splits are by EPISODE: frames within one
episode are near-duplicates, so a frame-level split leaks the answer.
"""
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 held_out_acc(Ztr, ytr, Zte, yte):
clf = make_pipeline(StandardScaler(), LogisticRegression(max_iter=3000))
clf.fit(Ztr, ytr)
return clf.score(Zte, yte)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--cache", default="outputs/pca/cache_cable_feats.npz")
ap.add_argument("--out", default="outputs/pca/cable_pca_tsne.png")
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
Xc = X - X.mean(0)
p = PCA(n_components=12).fit(Xc)
Z = p.transform(Xc)
evr = p.explained_variance_ratio_
plt.rcParams.update({"font.family": ["DejaVu Sans"], "font.size": 11})
fig = plt.figure(figsize=(18, 5.4))
def draw2d(ax, A, i, j, title, xlab, ylab):
for t in sorted(set(y), key=lambda s: DIA[s]):
m = te & (y == t)
ax.scatter(A[m, i], A[m, j], s=14, alpha=0.6, edgecolors="none",
c=COLOR[DIA[t]], label=NAME[DIA[t]])
ax.set_xlabel(xlab); ax.set_ylabel(ylab)
ax.set_title(title, fontsize=11.5)
ax.spines[["top", "right"]].set_visible(False)
# 1) the default projection, shown as-is
ax1 = fig.add_subplot(1, 4, 1)
a = held_out_acc(Z[tr][:, [0, 1]], y[tr], Z[te][:, [0, 1]], y[te])
draw2d(ax1, Z, 0, 1, f"PCA PC1 vs PC2\n{a:.1%} accuracy (chance 33.3%)",
f"PC1 ({evr[0]:.1%})", f"PC2 ({evr[1]:.1%})")
ax1.legend(frameon=False, fontsize=9)
# 2) the components that do carry cable identity
ax2 = fig.add_subplot(1, 4, 2)
a = held_out_acc(Z[tr][:, [3, 2]], y[tr], Z[te][:, [3, 2]], y[te])
draw2d(ax2, Z, 3, 2, f"PCA PC4 vs PC3\n{a:.1%} accuracy",
f"PC4 ({evr[3]:.1%})", f"PC3 ({evr[2]:.1%})")
# 3) 3-D PCA over the first three components
ax3 = fig.add_subplot(1, 4, 3, projection="3d")
a = held_out_acc(Z[tr][:, :3], y[tr], Z[te][:, :3], y[te])
for t in sorted(set(y), key=lambda s: DIA[s]):
m = te & (y == t)
ax3.scatter(Z[m, 0], Z[m, 1], Z[m, 2], s=9, alpha=0.5,
edgecolors="none", c=COLOR[DIA[t]], label=NAME[DIA[t]])
ax3.set_xlabel("PC1"); ax3.set_ylabel("PC2"); ax3.set_zlabel("PC3")
ax3.set_title(f"PCA 3-D (PC1-PC3)\n{a:.1%} accuracy", fontsize=11.5)
# 4) t-SNE, run on the PCA-reduced space as is standard
ax4 = fig.add_subplot(1, 4, 4)
emb = TSNE(n_components=2, perplexity=args.perplexity, init="pca",
random_state=0).fit_transform(Z[:, :30] if Z.shape[1] >= 30 else PCA(30).fit_transform(Xc))
for t in sorted(set(y), key=lambda s: DIA[s]):
m = te & (y == t)
ax4.scatter(emb[m, 0], emb[m, 1], s=14, alpha=0.6, edgecolors="none",
c=COLOR[DIA[t]], label=NAME[DIA[t]])
ax4.set_xlabel("t-SNE 1"); ax4.set_ylabel("t-SNE 2")
ax4.set_title(f"t-SNE (perplexity {args.perplexity:g})\nnon-linear; distances not metric",
fontsize=11.5)
ax4.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
fig.savefig(args.out, dpi=150, bbox_inches="tight")
print(f"wrote {args.out}\n")
for name, cols in (("PC1,PC2", [0, 1]), ("PC1-PC3", [0, 1, 2]),
("PC4,PC3", [3, 2]), ("PC1-PC10", list(range(10)))):
print(f" {name:9s} held-out accuracy {held_out_acc(Z[tr][:, cols], y[tr], Z[te][:, cols], y[te]):.1%}")
clf = make_pipeline(StandardScaler(), LogisticRegression(max_iter=3000)).fit(X[tr], y[tr])
print(f" {'full 512':9s} held-out accuracy {clf.score(X[te], y[te]):.1%} (chance 33.3%)")
if __name__ == "__main__":
main()