File size: 4,190 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 | #!/usr/bin/env python3
"""Cable clusters before vs after contact, in the ACT encoder space.
Contact onset is detected per episode from finger torque, so "pre" really means
the GelSight has not touched the cable yet. That split is what makes the tactile
question answerable: anything decodable pre-contact must be visual.
Panels: t-SNE of each phase separately (clusters by diameter), and the diameter
regression axis fitted within each phase. If pre-contact already separates as
well as post-contact, touch adds nothing to cable identity.
"""
import argparse
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression, RidgeCV
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 main():
ap = argparse.ArgumentParser()
ap.add_argument("--cache", default="outputs/pca/cache_cable_contact.npz")
ap.add_argument("--out", default="outputs/pca/cable_contact_clusters.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, ph = d["feats"], d["y"], d["eps"], d["phase"]
dia = np.array([DIA[t] for t in y])
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
order = sorted(set(y), key=lambda s: DIA[s])
plt.rcParams.update({"font.family": ["DejaVu Sans"], "font.size": 11})
fig, axes = plt.subplots(2, 2, figsize=(13, 11))
for col, (pname, label) in enumerate([("pre", "pre-contact (GelSight untouched)"),
("post", "post-contact (cable in hand)")]):
w = ph == pname
Xp = X[w]
Xc = Xp - Xp.mean(0)
Z = PCA(n_components=30).fit_transform(Xc)
emb = TSNE(n_components=2, perplexity=args.perplexity, init="pca",
random_state=0).fit_transform(Z)
trp, tep, yp = tr[w], te[w], y[w]
clf = make_pipeline(StandardScaler(), LogisticRegression(max_iter=3000)).fit(Xp[trp], yp[trp])
acc = clf.score(Xp[tep], yp[tep])
ax = axes[0, col]
for t in order:
m = tep & (yp == t)
ax.scatter(emb[m, 0], emb[m, 1], s=16, alpha=0.65, edgecolors="none",
c=COLOR[DIA[t]], label=NAME[DIA[t]])
ax.set_xlabel("t-SNE 1"); ax.set_ylabel("t-SNE 2")
ax.set_title(f"{label}\nt-SNE — {acc:.1%} accuracy (chance 33.3%)", fontsize=12)
if col == 0:
ax.legend(frameon=False, title="cable diameter")
reg = make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-2, 4, 25))).fit(
Xp[trp], dia[w][trp])
pred = reg.predict(Xp)
r2 = reg.score(Xp[tep], dia[w][tep])
ax = axes[1, col]
for t in order:
m = tep & (yp == t)
ax.scatter(pred[m], Z[m, 1], s=16, alpha=0.65, edgecolors="none",
c=COLOR[DIA[t]], label=NAME[DIA[t]])
for v in (1.7, 2.6, 4.5):
ax.axvline(v, color=COLOR[v], lw=1.1, ls="--", alpha=0.7)
ax.set_xticks([1.7, 2.6, 4.5])
ax.set_xlabel("predicted cable diameter [mm]"); ax.set_ylabel("PC2")
ax.set_title(f"diameter axis — held-out $R^2$ = {r2:.2f}", fontsize=12)
print(f" {pname:4s} accuracy {acc:.1%} diameter R^2 {r2:.2f}", flush=True)
for t in order:
m = tep & (yp == t)
print(f" {NAME[DIA[t]]:>7} -> {pred[m].mean():.2f} +- {pred[m].std():.2f} mm", flush=True)
for ax in axes.ravel():
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout(); fig.savefig(args.out, dpi=150, bbox_inches="tight")
print(f"\nwrote {args.out}")
if __name__ == "__main__":
main()
|