File size: 5,745 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#!/usr/bin/env python3
"""PCA of the ACT encoder representation, on the components that carry cable identity.

PCA is unsupervised: it ranks axes by variance, not by how well they separate
classes. In this model the cable axis is not PC1/PC2 -- those are dominated by
arm pose and grasp phase -- so the default projection hides it. Here the same
PCA is computed, then the two components with the highest between-class /
within-class variance ratio are plotted. Nothing is fitted to the labels; the
labels only choose which of the existing axes to look along.

Features are cached so the projection can be re-plotted without re-running the
policy over the dataset.
"""
import argparse, os
import numpy as np
import torch
import torch.nn.functional as F
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
plt.rcParams["font.family"] = ["Noto Sans CJK JP", "DejaVu Sans"]
from sklearn.decomposition import PCA

from lerobot.datasets.lerobot_dataset import LeRobotDataset
from lerobot.policies.act.modeling_act import ACTPolicy

COLORS = {"blue cable": "#2B6CB0", "cable 1.70 sq": "#C05621", "cable 3.30 sq": "#2F855A"}


def episode_task(ds, ep):
    t = ds.meta.episodes["tasks"][ep]
    return t[0] if isinstance(t, (list, np.ndarray)) else str(t)


def collect(args):
    ds = LeRobotDataset(args.repo_id)
    policy = ACTPolicy.from_pretrained(args.policy_path).to(args.device).eval()
    cap = {}
    policy.model.encoder.register_forward_hook(
        lambda m, i, o: cap.__setitem__("e", o.detach().mean(0).squeeze(0).float().cpu().numpy()))
    by = {}
    for ep in range(ds.meta.total_episodes):
        by.setdefault(episode_task(ds, ep), []).append(ep)
    rng = np.random.default_rng(0)
    feats, pix, lab, eps = [], [], [], []
    for task, e in sorted(by.items()):
        chosen = rng.choice(e, size=min(args.eps_per_task, len(e)), replace=False)
        print(f"  {task}: {len(chosen)} episodes", flush=True)
        for ep in chosen:
            lo = int(ds.meta.episodes["dataset_from_index"][ep])
            hi = int(ds.meta.episodes["dataset_to_index"][ep])
            for i in rng.choice(np.arange(lo, hi), size=min(args.frames_per_ep, hi - lo), replace=False):
                item = ds[int(i)]
                b = {k: v.unsqueeze(0).to(args.device) for k, v in item.items() if isinstance(v, torch.Tensor)}
                b["task"] = [task]
                with torch.no_grad():
                    policy.select_action(b)
                policy.reset()
                feats.append(cap["e"])
                gs = item["observation.images.gelsight1"].unsqueeze(0).float()
                pix.append(F.adaptive_avg_pool2d(gs, 16).flatten().numpy())
                lab.append(task); eps.append(ep)
    return np.array(feats), np.array(pix), np.array(lab), np.array(eps)


def sep_ratio(Z, y, k):
    g = [Z[y == t, k] for t in sorted(set(y))]
    return np.var([x.mean() for x in g]) / (np.mean([x.var() for x in g]) + 1e-12)


def panel(ax, Z, y, i, j, ratios, evr, title):
    for t in sorted(set(y)):
        m = y == t
        ax.scatter(Z[m, i], Z[m, j], s=9, alpha=0.55, edgecolors="none",
                   c=COLORS.get(t, "#666"), label=t)
    ax.set_xlabel(f"PC{i+1}  ({evr[i]:.1%} var, sep {ratios[i]:.2f})")
    ax.set_ylabel(f"PC{j+1}  ({evr[j]:.1%} var, sep {ratios[j]:.2f})")
    ax.set_title(title, fontsize=11)
    ax.spines[["top", "right"]].set_visible(False)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--repo-id", default="Kaz55/dg5f_ur5e_bluev2_cable170_330_270ep")
    ap.add_argument("--policy-path", required=True)
    ap.add_argument("--eps-per-task", type=int, default=30)
    ap.add_argument("--frames-per-ep", type=int, default=25)
    ap.add_argument("--device", default="cuda")
    ap.add_argument("--cache", default="outputs/pca/cache_cable_feats.npz")
    ap.add_argument("--out", default="outputs/pca/pca_cable_informative.png")
    args = ap.parse_args()

    if os.path.exists(args.cache):
        d = np.load(args.cache, allow_pickle=True)
        feats, pix, y = d["feats"], d["pix"], d["y"]
        print(f"cache から読み込み: {len(y)} frames", flush=True)
    else:
        feats, pix, y, eps = collect(args)
        np.savez_compressed(args.cache, feats=feats, pix=pix, y=y, eps=eps)
        print(f"collected {len(y)} frames -> {args.cache}", flush=True)

    fig, axes = plt.subplots(1, 3, figsize=(16.5, 5.2))
    Xc = feats - feats.mean(0)
    p = PCA(n_components=30).fit(Xc)
    Z = p.transform(Xc)
    evr = p.explained_variance_ratio_
    ratios = np.array([sep_ratio(Z, y, k) for k in range(30)])
    best = np.argsort(ratios)[::-1][:2]
    print(f"  分離に効く主成分: PC{best[0]+1} (sep {ratios[best[0]]:.2f}), PC{best[1]+1} (sep {ratios[best[1]]:.2f})",
          flush=True)

    panel(axes[0], Z, y, 0, 1, ratios, evr, "既定の PC1 vs PC2\nケーブル軸が乗っていない")
    panel(axes[1], Z, y, int(best[0]), int(best[1]), ratios, evr,
          f"分離に効く PC{best[0]+1} vs PC{best[1]+1}\n同じPCAの別の軸")
    axes[1].legend(frameon=False, fontsize=9)

    axes[2].bar(range(1, 31), ratios, color=["#C05621" if k in best else "#2B6CB0" for k in range(30)])
    axes[2].set_title("主成分ごとのケーブル分離度\n(クラス間分散 / クラス内分散)", fontsize=11)
    axes[2].set_xlabel("principal component"); axes[2].set_ylabel("separability")
    axes[2].spines[["top", "right"]].set_visible(False)

    fig.suptitle("PCA: どの主成分がケーブルを符号化しているか(ACT encoder, 512次元)", fontsize=13)
    fig.tight_layout()
    fig.savefig(args.out, dpi=150)
    print(f"wrote {args.out}", flush=True)


if __name__ == "__main__":
    main()