File size: 2,162 Bytes
9220556
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

from pathlib import Path

import gradio as gr
import numpy as np
import plotly.graph_objects as go

ARTIFACT_DIR = Path(__file__).resolve().parent / "artifacts" / "factorial-code-forge"
DATA = np.load(ARTIFACT_DIR / "latent_comparison.npz")
METHODS = {
    "Observed mixtures": "observations",
    "Autoencoder control": "autoencoder_control",
    "Neural adversarial ablation": "neural_adversarial_ablation",
    "Predictability minimization": "predictability_minimization",
    "PCA whitened": "pca_whitened",
    "FastICA": "fastica",
}


def explore(method: str, points: int) -> tuple[go.Figure, dict]:
    key = METHODS[method]
    code = DATA[key][: int(points)]
    sources = DATA["sources"][: int(points)]
    figure = go.Figure(
        go.Scattergl(
            x=code[:, 0],
            y=code[:, 1],
            mode="markers",
            marker={
                "size": 4,
                "color": sources[:, 0],
                "colorscale": "Turbo",
                "opacity": 0.65,
            },
        )
    )
    figure.update_layout(
        title=f"{method}: learned two-dimensional code",
        xaxis_title="Coordinate 1",
        yaxis_title="Coordinate 2",
        template="plotly_dark",
    )
    return figure, {
        "absolute_correlation": round(float(abs(np.corrcoef(code.T)[0, 1])), 5),
        "points": len(code),
        "color": "true source 1 (evaluation only)",
    }


with gr.Blocks(title="Factorial Code Forge") as demo:
    gr.Markdown(
        "# Factorial Code Forge\n"
        "Inspect how different unsupervised methods reorganize two mixed, "
        "independent non-Gaussian sources."
    )
    with gr.Row():
        method = gr.Dropdown(
            list(METHODS), value="Predictability minimization", label="Code"
        )
        points = gr.Slider(250, 5_000, 2_000, step=250, label="Points")
    run = gr.Button("Reveal code", variant="primary")
    scatter = gr.Plot()
    metrics = gr.JSON()
    run.click(explore, [method, points], [scatter, metrics])
    demo.load(explore, [method, points], [scatter, metrics])


if __name__ == "__main__":
    demo.launch()