File size: 4,565 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 106 107 108 | #!/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()
|