laboratório v0.22-lab: auditoria executável, correção do laço de regulação (lab-A1, opt-in) e medições em dados reais (wiki PT-BR + digits)
516193c verified Download laboratorio/scripts/34_bancada_som.py from PowerMachine/khtst-rust: direct link, hf CLI and curl.
- Browser
- Download file 5.37 kB
-
https://huggingface.co/PowerMachine/khtst-rust/resolve/main/laboratorio/scripts/34_bancada_som.py
- Command line
-
hf download hf://PowerMachine/khtst-rust/laboratorio/scripts/34_bancada_som.py
-
curl -L -o 34_bancada_som.py https://huggingface.co/PowerMachine/khtst-rust/resolve/main/laboratorio/scripts/34_bancada_som.py
5.37 kB
| #!/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()) | |