File size: 5,372 Bytes
516193c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""34_bancada_som.py — SOM de grade com DADOS REAIS (dígitos manuscritos).

Reproduz os experimentos de `src/som.rs` §5.1–5.2 sobre dados reais:

  1. auto-organização OBSERVADA: inicialização ALEATÓRIA (mapa começa
     desalinhado) ⇒ TE (vizinhança de Moore) cai de alto para ≈ baixo e
     o EQ cai — a grade se organiza e depois quantiza;
  2. inicialização PCA (controle): o mapa já nasce ordenado;
  3. Mahalanobis numa métrica natural para dados correlacionados: o EQ
     medido NA PRÓPRIA métrica de Mahalanobis cai vs Euclidiana.

Unidades publicadas e declaradas: EQ = distância quadrada; QE/pior
célula = norma L2; TE = fração com 2º melhor fora de Moore.
"""
import json
import os
import sys

import numpy as np

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
PASTA = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

from lab.som import CfgSom, SOMBatela  # noqa: E402
from lab.metricas import UNIDADE_EQ, UNIDADE_QE  # noqa: E402


def main() -> int:
    cfg_base = json.load(open(os.path.join(PASTA, "configs", "base_laboratorio.json")))["laboratorio"]
    s = cfg_base["som"]
    n_som = int(cfg_base["dados_digits"]["n_som"])
    semente = int(cfg_base["dados_digits"]["semente"])

    dados_all = np.load(os.path.join(PASTA, "dados", "vetores_digits.npz"))
    X = dados_all["vetores"]
    rng = np.random.default_rng(semente)
    idx = sorted(rng.choice(len(X), n_som, replace=False).tolist())
    dados = X[np.array(idx)]

    saida = {"fonte": "sklearn digits (1000 amostras reais, 64-D)", "n": n_som}

    # 1) auto-organização observada (init aleatória)
    cfg_rand = CfgSom(
        linhas=s["linhas"], lado=s["lado"], epocas=s["epocas"], sigma0=s["sigma0"],
        sigma1=s["sigma1"], taxa=s["taxa"], inicializacao="aleatoria", semente=semente,
    )
    som_rand = SOMBatela(cfg_rand, dados.shape[1])
    som_rand.inicializar(dados)
    hist_rand = som_rand.treinar(dados)
    saida["aleatoria"] = {
        "te_inicial": hist_rand[0]["te"], "te_final": hist_rand[-1]["te"],
        "eq_inicial": hist_rand[0]["eq"], "eq_final": hist_rand[-1]["eq"],
        "curva_eq": [h["eq"] for h in hist_rand], "curva_te": [h["te"] for h in hist_rand],
    }

    # 2) controle PCA (mapa já nasce ordenado)
    cfg_pca = CfgSom(**{**cfg_rand.__dict__, "inicializacao": "pca"})
    som_pca = SOMBatela(cfg_pca, dados.shape[1])
    som_pca.inicializar(dados)
    hist_pca = som_pca.treinar(dados)
    saida["pca"] = {
        "te_inicial": hist_pca[0]["te"], "te_final": hist_pca[-1]["te"],
        "eq_inicial": hist_pca[0]["eq"], "eq_final": hist_pca[-1]["eq"],
    }

    # 3) Mahalanobis na métrica natural (dados correlacionados de verdade)
    cfg_maha = CfgSom(**{**cfg_rand.__dict__, "metrica": "mahalanobis", "epocas": 40})
    som_maha = SOMBatela(cfg_maha, dados.shape[1])
    som_maha.inicializar(dados)
    som_maha.treinar(dados, medir=False)
    eq_m_eucl = som_rand.eq_mahalanobis(dados) if hasattr(som_rand, "eq_mahalanobis") else None
    som_rand._chol = None
    som_rand.preparar_mahalanobis(dados)
    eq_m_rand = som_rand.eq_mahalanobis(dados)
    eq_m_maha = som_maha.eq_mahalanobis(dados)
    saida["mahalanobis"] = {
        "eq_mahalanobis_som_euclidiano": eq_m_rand,
        "eq_mahalanobis_som_mahalanobis": eq_m_maha,
        "melhora_na_propria_metrica": eq_m_rand - eq_m_maha,
    }

    # determinismo: reexecução bit-a-bit
    som_rep = SOMBatela(cfg_rand, dados.shape[1])
    som_rep.inicializar(dados)
    som_rep.treinar(dados, medir=False)
    saida["determinismo"] = bool(np.array_equal(som_rand.prototipos, som_rep.prototipos))
    saida["te_inicial"] = hist_rand[0]["te"]
    saida["te_final"] = hist_rand[-1]["te"]
    saida["eq_inicial"] = hist_rand[0]["eq"]
    saida["eq_final"] = hist_rand[-1]["eq"]
    saida["unidade_eq"] = UNIDADE_EQ
    saida["unidade_qe"] = UNIDADE_QE

    print("[SOM] TE %.4f → %.4f (Moore) | EQ %.4f → %.4f | Mahalanobis: %.4f → %.4f (na própria métrica)" % (
        saida["te_inicial"], saida["te_final"], saida["eq_inicial"], saida["eq_final"],
        eq_m_rand, eq_m_maha), flush=True)

    import matplotlib

    matplotlib.use("Agg")
    import matplotlib.pyplot as plt

    fig, eixos = plt.subplots(1, 2, figsize=(10, 4), constrained_layout=True)
    eixos[0].plot([h["eq"] for h in hist_rand], color="#2471a3", label="EQ (aleatória)")
    eixos[0].plot([h["eq"] for h in hist_pca], color="#1e8449", label="EQ (PCA)")
    eixos[0].set_title("EQ — digits reais, grade 10×10")
    eixos[0].set_xlabel("época"); eixos[0].legend(fontsize=8); eixos[0].grid(alpha=0.3)
    eixos[1].plot([h["te"] for h in hist_rand], color="#2471a3", label="TE Moore (aleatória)")
    eixos[1].plot([h["te"] for h in hist_pca], color="#1e8449", label="TE Moore (PCA)")
    eixos[1].set_title("TE — auto-organização observada")
    eixos[1].set_xlabel("época"); eixos[1].legend(fontsize=8); eixos[1].grid(alpha=0.3)
    fig.savefig(os.path.join(PASTA, "resultados", "figuras", "bancada_som.png"), dpi=130)

    destino = os.path.join(PASTA, "resultados", "bancada_som.json")
    with open(destino, "w", encoding="utf-8") as f:
        json.dump(saida, f, indent=2, ensure_ascii=False)
    print(f"[ok] {destino}")
    return 0


if __name__ == "__main__":
    sys.exit(main())