Download scripts/plot_contact_pca.py from Kaz55/cable-representation-analysis: direct link, hf CLI and curl.
- Browser
- Download file 3.69 kB
-
https://huggingface.co/datasets/Kaz55/cable-representation-analysis/resolve/main/scripts/plot_contact_pca.py
- Command line
-
hf download hf://datasets/Kaz55/cable-representation-analysis/scripts/plot_contact_pca.py
-
curl -L -o plot_contact_pca.py https://huggingface.co/datasets/Kaz55/cable-representation-analysis/resolve/main/scripts/plot_contact_pca.py
3.69 kB
| #!/usr/bin/env python3 | |
| """PCA of the ACT encoder space, computed separately before and after contact. | |
| Each phase gets its own PCA: the dominant directions differ between reaching and | |
| manipulation, 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. | |
| Top row is the default PC1/PC2 view, bottom row the first three components in | |
| 3-D. Accuracies are from a probe on exactly the axes drawn, held-out episodes. | |
| """ | |
| 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.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][:, cols], y[tr]) | |
| return c.score(Z[~tr][:, cols], y[~tr]) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--cache", default="outputs/pca/cache_cable_contact.npz") | |
| ap.add_argument("--out", default="outputs/pca/cable_contact_pca.png") | |
| 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)) | |
| order = sorted(set(y), key=lambda s: DIA[s]) | |
| plt.rcParams.update({"font.family": ["DejaVu Sans"], "font.size": 11}) | |
| fig = plt.figure(figsize=(13, 11)) | |
| for col, 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, evr = p.transform(Xc), p.explained_variance_ratio_ | |
| tep = ~trp | |
| a2 = acc(Z, yp, trp, [0, 1]) | |
| ax = fig.add_subplot(2, 2, col + 1) | |
| for t in order: | |
| m = tep & (yp == t) | |
| ax.scatter(Z[m, 0], Z[m, 1], s=16, alpha=0.65, edgecolors="none", | |
| c=COLOR[DIA[t]], label=NAME[DIA[t]]) | |
| ax.set_xlabel(f"PC1 ({evr[0]:.1%})"); ax.set_ylabel(f"PC2 ({evr[1]:.1%})") | |
| ax.set_title(f"{TITLE[pname]}\nPCA PC1 vs PC2 — {a2:.1%} (chance 33.3%)", fontsize=12) | |
| ax.spines[["top", "right"]].set_visible(False) | |
| if col == 0: | |
| ax.legend(frameon=False, title="cable diameter") | |
| a3 = acc(Z, yp, trp, [0, 1, 2]) | |
| ax = fig.add_subplot(2, 2, col + 3, projection="3d") | |
| for t in order: | |
| m = tep & (yp == 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) — {a3:.1%}", fontsize=12) | |
| ax.view_init(elev=18, azim=-60) | |
| print(f" {pname:4s} PC1/PC2 {a2:.1%} PC1-PC3 {a3:.1%} " | |
| f"variance PC1 {evr[0]:.1%} PC2 {evr[1]:.1%} PC3 {evr[2]:.1%}", flush=True) | |
| fig.tight_layout(); fig.savefig(args.out, dpi=150, bbox_inches="tight") | |
| print(f"\nwrote {args.out}") | |
| if __name__ == "__main__": | |
| main() | |