File size: 9,129 Bytes
eea47ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
"""Visualize motivation evidence for CTA, given a feature .npz dumped by
scripts/analysis/dump_cta_features.py.

Produces three figures:

  1) ``hist_<key>.pdf`` for key in {l_av, l_va, asym}
     Per-class histogram + KDE. The asym histogram is THE figure that
     directly demonstrates the detection signal.

  2) ``scatter_lva_lav.pdf``
     L_AV vs L_VA scatter plot. Shows whether fake samples collapse onto a
     near-diagonal manifold (i.e. V is fully determined by A under the
     generator), while real samples stay off-diagonal.

  3) ``tsne_residual.pdf``
     2-up: t-SNE of the V-prediction residual (left) and A-prediction
     residual (right), colored by real/fake. Lets you see which residual
     direction carries more class-separating information.

The script avoids any non-stdlib dependency beyond numpy / matplotlib /
sklearn (already required by the project for compute_extra_metrics.py).

Usage
-----
    python3 scripts/analysis/visualize_motivation.py \\
        --npz outputs/analysis/cta_features_oursval.npz \\
        --out-dir outputs/analysis/figs_oursval

    # subsample t-SNE to speed up (default 2000)
    python3 scripts/analysis/visualize_motivation.py \\
        --npz <...>.npz --out-dir <...>/figs --tsne-n 1000
"""
from __future__ import annotations

import argparse
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np


def _palette():
    return {0: "#2E86C1", 1: "#E74C3C"}  # blue=real, red=fake


def _label_name(y: int) -> str:
    return "real" if y == 0 else "fake"


# ---------------------------------------------------------------------------
# 1) Histograms
# ---------------------------------------------------------------------------
def plot_histogram(values, labels, out_path, title, xlabel, bins=60):
    fig, ax = plt.subplots(figsize=(6.0, 4.0))
    pal = _palette()
    lo = float(np.percentile(values, 0.5))
    hi = float(np.percentile(values, 99.5))
    edges = np.linspace(lo, hi, bins + 1)
    for y in (0, 1):
        v = values[labels == y]
        if len(v) == 0:
            continue
        ax.hist(v, bins=edges, density=True, alpha=0.55,
                color=pal[y], edgecolor="white", linewidth=0.4,
                label=f"{_label_name(y)} (n={len(v)}, mean={v.mean():.4f})")
    ax.axvline(0.0, color="0.4", linestyle="--", linewidth=0.8, alpha=0.7)
    ax.set_xlabel(xlabel)
    ax.set_ylabel("density")
    ax.set_title(title)
    ax.legend(frameon=False, loc="best")
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    fig.tight_layout()
    fig.savefig(out_path, dpi=200)
    fig.savefig(out_path.with_suffix(".png"), dpi=200)
    plt.close(fig)
    print(f"[viz] wrote {out_path}")


# ---------------------------------------------------------------------------
# 2) L_AV vs L_VA scatter
# ---------------------------------------------------------------------------
def plot_scatter(l_av, l_va, labels, out_path, max_points_per_class=1500):
    fig, ax = plt.subplots(figsize=(5.5, 5.0))
    pal = _palette()
    rng = np.random.default_rng(0)
    for y in (1, 0):
        mask = labels == y
        x = l_av[mask]
        z = l_va[mask]
        if len(x) > max_points_per_class:
            idx = rng.choice(len(x), size=max_points_per_class, replace=False)
            x = x[idx]; z = z[idx]
        ax.scatter(x, z, s=8, c=pal[y], alpha=0.45, edgecolors="none",
                   label=f"{_label_name(y)} (n={mask.sum()})")
    lo = float(min(l_av.min(), l_va.min()))
    hi = float(max(l_av.max(), l_va.max()))
    pad = (hi - lo) * 0.05
    ax.plot([lo - pad, hi + pad], [lo - pad, hi + pad],
            color="0.3", linestyle="--", linewidth=0.8, alpha=0.8, label="y = x")
    ax.set_xlim(lo - pad, hi + pad)
    ax.set_ylim(lo - pad, hi + pad)
    ax.set_xlabel(r"$L_{A \to V}$  (A->V prediction MSE)")
    ax.set_ylabel(r"$L_{V \to A}$  (V->A prediction MSE)")
    ax.set_title("Per-sample prediction-loss asymmetry")
    ax.legend(frameon=False, loc="best")
    ax.set_aspect("equal", adjustable="box")
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    fig.tight_layout()
    fig.savefig(out_path, dpi=200)
    fig.savefig(out_path.with_suffix(".png"), dpi=200)
    plt.close(fig)
    print(f"[viz] wrote {out_path}")


# ---------------------------------------------------------------------------
# 3) Residual t-SNE
# ---------------------------------------------------------------------------
def _tsne(x, n, seed=0):
    if len(x) > n:
        rng = np.random.default_rng(seed)
        idx = rng.choice(len(x), size=n, replace=False)
        x = x[idx]
    else:
        idx = np.arange(len(x))
    try:
        from sklearn.manifold import TSNE
    except ImportError as e:
        raise SystemExit(
            "[viz] sklearn is required for t-SNE. Install: pip install scikit-learn"
        ) from e
    tsne = TSNE(
        n_components=2, perplexity=min(30, max(5, len(x) // 50)),
        init="pca", learning_rate="auto", random_state=seed,
    )
    return tsne.fit_transform(x), idx


def plot_residual_tsne(r_av, r_va, labels, out_path, n=2000):
    fig, axes = plt.subplots(1, 2, figsize=(11, 5))
    pal = _palette()
    for ax, x, name in [(axes[0], r_av, r"$r_{A \to V}$  (V token residual)"),
                        (axes[1], r_va, r"$r_{V \to A}$  (A token residual)")]:
        emb, idx = _tsne(x, n=n)
        y = labels[idx]
        for cls in (1, 0):
            m = y == cls
            ax.scatter(emb[m, 0], emb[m, 1], s=10, c=pal[cls], alpha=0.55,
                       edgecolors="none", label=f"{_label_name(cls)} ({m.sum()})")
        ax.set_title(name)
        ax.set_xticks([]); ax.set_yticks([])
        for s in ax.spines.values():
            s.set_visible(False)
        ax.legend(frameon=False, loc="best")
    fig.suptitle("t-SNE of cross-modal prediction residuals", fontsize=11)
    fig.tight_layout()
    fig.savefig(out_path, dpi=200)
    fig.savefig(out_path.with_suffix(".png"), dpi=200)
    plt.close(fig)
    print(f"[viz] wrote {out_path}")


# ---------------------------------------------------------------------------
def write_per_generator_summary(asym, labels, generators, out_path):
    rows = [("group", "n", "asym_mean", "asym_median", "asym_std")]
    rows.append(("real (all)", int((labels == 0).sum()),
                 float(asym[labels == 0].mean()),
                 float(np.median(asym[labels == 0])),
                 float(asym[labels == 0].std())))
    fakes = labels == 1
    if fakes.any():
        for g in sorted(set(generators[fakes].tolist())):
            sel = fakes & (generators == g)
            v = asym[sel]
            rows.append((f"fake/{g}", int(sel.sum()),
                         float(v.mean()), float(np.median(v)), float(v.std())))
        rows.append(("fake (all)", int(fakes.sum()),
                     float(asym[fakes].mean()), float(np.median(asym[fakes])),
                     float(asym[fakes].std())))
    with open(out_path, "w") as f:
        f.write(",".join(map(str, rows[0])) + "\n")
        for r in rows[1:]:
            f.write(f"{r[0]},{r[1]},{r[2]:.6f},{r[3]:.6f},{r[4]:.6f}\n")
    print(f"[viz] wrote {out_path}")


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--npz", required=True, help="Path to dump_cta_features.py output.")
    p.add_argument("--out-dir", required=True, help="Directory for figures + summary csv.")
    p.add_argument("--tsne-n", type=int, default=2000, help="t-SNE subsample size.")
    args = p.parse_args()

    npz_path = Path(args.npz).resolve()
    out_dir = Path(args.out_dir).resolve()
    out_dir.mkdir(parents=True, exist_ok=True)

    print(f"[viz] loading {npz_path}")
    data = np.load(npz_path, allow_pickle=True)
    l_av = data["l_av"].astype(np.float64)
    l_va = data["l_va"].astype(np.float64)
    asym = data["asym"].astype(np.float64)
    label = data["label"].astype(np.int64)
    gen = data["generator"].astype(object)
    r_av = data["r_av"].astype(np.float32)
    r_va = data["r_va"].astype(np.float32)
    meta = data["meta"].item() if "meta" in data.files else {}
    print(f"[viz]   n={len(l_av)}  reals={(label==0).sum()}  fakes={(label==1).sum()}")
    if meta:
        print(f"[viz]   meta: {meta}")

    plot_histogram(l_av, label, out_dir / "hist_l_av.pdf",
                   r"Distribution of $L_{A \to V}$", r"$L_{A \to V}$")
    plot_histogram(l_va, label, out_dir / "hist_l_va.pdf",
                   r"Distribution of $L_{V \to A}$", r"$L_{V \to A}$")
    plot_histogram(asym, label, out_dir / "hist_asym.pdf",
                   r"Asymmetry score $s = L_{V \to A} - L_{A \to V}$",
                   r"$s_\mathrm{asym}$")

    plot_scatter(l_av, l_va, label, out_dir / "scatter_lva_lav.pdf")
    plot_residual_tsne(r_av, r_va, label, out_dir / "tsne_residual.pdf",
                       n=args.tsne_n)
    write_per_generator_summary(asym, label, gen,
                                out_dir / "per_generator_asym.csv")

    print("[viz] DONE.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())