Download scripts/plot_contact_pca3d.py from Kaz55/cable-representation-analysis: direct link, hf CLI and curl.
- Browser
- Download file 4.57 kB
-
https://huggingface.co/datasets/Kaz55/cable-representation-analysis/resolve/main/scripts/plot_contact_pca3d.py
- Command line
-
hf download hf://datasets/Kaz55/cable-representation-analysis/scripts/plot_contact_pca3d.py
-
curl -L -o plot_contact_pca3d.py https://huggingface.co/datasets/Kaz55/cable-representation-analysis/resolve/main/scripts/plot_contact_pca3d.py
4.57 kB
| #!/usr/bin/env python3 | |
| """3-D PCA of the ACT encoder space, before vs after contact. | |
| Each phase gets its own PCA -- reaching and manipulation are dominated by | |
| different directions, so a shared basis would misrepresent both. Contact onset is | |
| detected per episode from finger torque, so "pre" is genuinely before the | |
| GelSight touches anything. | |
| For each phase: the default PC1-PC3 triple and the best-separating triple found | |
| by scoring every 3-combination of the first 8 components on held-out episodes. | |
| Showing both keeps the best-triple choice honest. | |
| """ | |
| import argparse, itertools | |
| 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"} | |
| TITLE = {"pre": "pre-contact (GelSight untouched)", "post": "post-contact (cable in hand)"} | |
| def acc(Z, y, tr, cols): | |
| c = make_pipeline(StandardScaler(), LogisticRegression(max_iter=3000)) | |
| c.fit(Z[tr][:, list(cols)], y[tr]) | |
| return c.score(Z[~tr][:, list(cols)], y[~tr]) | |
| def draw(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=11, 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=11.5) | |
| ax.view_init(elev=18, azim=-60) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--cache", default="outputs/pca/cache/cache_cable_contact.npz") | |
| ap.add_argument("--outdir", default="outputs/pca/contact") | |
| args = ap.parse_args() | |
| d = np.load(args.cache, allow_pickle=True) | |
| X, y, ep, ph = d["feats"], d["y"], d["eps"], d["phase"] | |
| 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)) | |
| plt.rcParams.update({"font.family": ["DejaVu Sans"], "font.size": 11}) | |
| fig = plt.figure(figsize=(14, 11.5)) | |
| store = {} | |
| for row, pname in enumerate(["pre", "post"]): | |
| w = ph == pname | |
| Xp, yp, trp = X[w], y[w], tr[w] | |
| Xc = Xp - Xp.mean(0) | |
| p = PCA(n_components=10).fit(Xc) | |
| Z = p.transform(Xc) | |
| tep = ~trp | |
| best = max(itertools.combinations(range(8), 3), key=lambda c: acc(Z, yp, trp, c)) | |
| a_def, a_best = acc(Z, yp, trp, (0, 1, 2)), acc(Z, yp, trp, best) | |
| store[pname] = (Z, yp, tep, best, a_best) | |
| ax = fig.add_subplot(2, 2, row * 2 + 1, projection="3d") | |
| draw(ax, Z, yp, tep, (0, 1, 2), f"{TITLE[pname]}\nPC1-PC3 (default) — {a_def:.1%}") | |
| if row == 0: | |
| ax.legend(frameon=False, title="cable diameter", loc="upper left", fontsize=9.5) | |
| ax = fig.add_subplot(2, 2, row * 2 + 2, projection="3d") | |
| draw(ax, Z, yp, tep, best, | |
| f"best triple PC{best[0]+1}, PC{best[1]+1}, PC{best[2]+1} — {a_best:.1%}") | |
| print(f" {pname:4s} PC1-PC3 {a_def:.1%} best PC{best[0]+1},PC{best[1]+1},PC{best[2]+1} {a_best:.1%}", | |
| flush=True) | |
| fig.tight_layout() | |
| out = f"{args.outdir}/cable_contact_pca3d.png" | |
| fig.savefig(out, dpi=150, bbox_inches="tight") | |
| print(f"\nwrote {out}") | |
| # Rotating views -- depth structure is invisible in a still 3-D scatter. | |
| for pname in ["pre", "post"]: | |
| Z, yp, tep, best, a = store[pname] | |
| f2 = plt.figure(figsize=(7, 6.4)) | |
| ax = f2.add_subplot(111, projection="3d") | |
| draw(ax, Z, yp, tep, best, | |
| f"{TITLE[pname]}\nPC{best[0]+1}, PC{best[1]+1}, PC{best[2]+1} — {a:.1%}") | |
| ax.legend(frameon=False, title="cable diameter", loc="upper left", fontsize=9.5) | |
| FuncAnimation(f2, lambda i: (ax.view_init(elev=18, azim=i * 4), [])[1], | |
| frames=90, interval=80).save( | |
| f"{args.outdir}/cable_contact_pca3d_{pname}.gif", writer=PillowWriter(fps=12)) | |
| print(f"wrote {args.outdir}/cable_contact_pca3d_{pname}.gif") | |
| if __name__ == "__main__": | |
| main() | |