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/20_dados_reais.py from PowerMachine/khtst-rust: direct link, hf CLI and curl.
- Browser
- Download file 4.4 kB
-
https://huggingface.co/PowerMachine/khtst-rust/resolve/main/laboratorio/scripts/20_dados_reais.py
- Command line
-
hf download hf://PowerMachine/khtst-rust/laboratorio/scripts/20_dados_reais.py
-
curl -L -o 20_dados_reais.py https://huggingface.co/PowerMachine/khtst-rust/resolve/main/laboratorio/scripts/20_dados_reais.py
4.4 kB
| #!/usr/bin/env python3 | |
| """10_dados_reais.py — vetorização determinística dos DADOS REAIS do repositório. | |
| Fonte 1: `dados/shard_treino.jsonl` — os MESMOS 246 artigos reais da | |
| Wikipédia PT-BR usados pelo ciclo v0.21 (`resultados/suite_v021.json`, | |
| campo `fonte: "dados/shard_treino.jsonl"`). Cada artigo vira UM vetor de | |
| conceito de 64 dimensões por **feature hashing** de n-gramas de palavras | |
| (1–2 gramas), com sinal determinístico e normalização L2 — o mesmo | |
| regime "praticamente ortogonal" que motivou o critério relativo do v0.21 | |
| (r-63 §M: QE ≈ 0 ⇒ crescimento maximal no critério absoluto). | |
| Fonte 2: `sklearn.datasets.load_digits` — 1797 imagens reais de dígitos | |
| manuscritos, 64-D (a mesma dimensão do `d_lat` do repositório). | |
| Saída: `dados/vetores_wiki.npz`, `dados/vetores_digits.npz` + | |
| estatísticas publicadas (ortogonalidade média, normas, contagens). | |
| """ | |
| 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__))) | |
| def _hash_tokens(tokens, dim, semente): | |
| """Feature hashing assinado e determinístico (sem biblioteca externa).""" | |
| from lab.rng import RngDeterministico | |
| rng = RngDeterministico(semente) | |
| tabela = {} | |
| # 2^20 buckets de sinal, gerados uma vez (determinístico) | |
| sinais = {} | |
| for _ in range(4096): | |
| sinais[rng.uniforme()] = 1.0 # apenas para consumo determinístico do RNG | |
| def indice_token(t): | |
| if t not in tabela: | |
| h = 0 | |
| for ch in t: | |
| h = (h * 1315423911 + ord(ch)) & 0xFFFFFFFF | |
| tabela[t] = h | |
| return tabela[t] | |
| vetor = np.zeros(dim, dtype=np.float64) | |
| for t in tokens: | |
| h = indice_token(t) | |
| bucket = h % dim | |
| sinal = 1.0 if ((h >> 16) & 1) else -1.0 | |
| vetor[bucket] += sinal | |
| return vetor | |
| def featurizar_textos(textos, dim=64, n_min=1, n_max=2): | |
| vetores = [] | |
| for texto in textos: | |
| palavras = [w.lower() for w in texto.split() if w.isalnum()] | |
| tokens = [] | |
| for n in range(n_min, n_max + 1): | |
| tokens += ["_".join(palavras[i : i + n]) for i in range(len(palavras) - n + 1)] | |
| v = _hash_tokens(tokens, dim, 42) | |
| norma = np.linalg.norm(v) | |
| if norma > 0: | |
| v /= norma | |
| vetores.append(v) | |
| return np.array(vetores) | |
| def main() -> int: | |
| cfg = json.load(open(os.path.join(PASTA, "configs", "base_laboratorio.json")))["laboratorio"] | |
| os.makedirs(os.path.join(PASTA, "dados"), exist_ok=True) | |
| # ---- fonte 1: os artigos reais do repositório --------------------------- | |
| caminho = os.path.join(PASTA, "dados", "shard_treino.jsonl") | |
| textos = [json.loads(l)["texto"] for l in open(caminho, encoding="utf-8") if l.strip()] | |
| dw = cfg["dados_wiki"] | |
| vetores_wiki = featurizar_textos(textos, dw["dimensao"], dw["n_grama_min"], dw["n_grama_max"]) | |
| np.savez(os.path.join(PASTA, "dados", "vetores_wiki.npz"), vetores=vetores_wiki) | |
| # ortogonalidade média |cos| entre vetores distintos (regime do v0.21) | |
| gram = np.abs(vetores_wiki @ vetores_wiki.T) | |
| n = len(vetores_wiki) | |
| ortogonalidade = float((gram.sum() - np.trace(gram)) / (n * (n - 1))) | |
| # ---- fonte 2: dígitos manuscritos reais -------------------------------- | |
| from sklearn.datasets import load_digits | |
| dd = cfg["dados_digits"] | |
| ds = load_digits() | |
| X = ds.data.astype(np.float64) / 16.0 # [0,1] real, 64-D | |
| np.savez(os.path.join(PASTA, "dados", "vetores_digits.npz"), vetores=X, alvo=ds.target) | |
| saida = { | |
| "fonte": os.path.relpath(caminho, PASTA), | |
| "artigos_reais": n, | |
| "dimensao": int(vetores_wiki.shape[1]), | |
| "ortogonalidade_media_abs_cos": ortogonalidade, | |
| "norma_media_wiki": float(np.linalg.norm(vetores_wiki, axis=1).mean()), | |
| "digits_amostras": int(X.shape[0]), | |
| "digits_dimensao": int(X.shape[1]), | |
| "digits_classes": sorted(set(int(t) for t in ds.target)), | |
| "deterministico": True, | |
| "semente": dw["semente"], | |
| } | |
| with open(os.path.join(PASTA, "resultados", "dados_reais.json"), "w", encoding="utf-8") as f: | |
| json.dump(saida, f, indent=2, ensure_ascii=False) | |
| print(json.dumps(saida, indent=2, ensure_ascii=False)) | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |