Revertir el diagnóstico NUTS opcional con PyMC

This commit is contained in:
2026-12-03 07:17:35 -06:00
parent 17a60ff68d
commit a1e2e07e0c
4 changed files with 0 additions and 94 deletions
-18
View File
@@ -18,21 +18,3 @@ se deben resolver antes de entrenar con datos reales.
No se añadieron PyMC ni otras dependencias al entorno de producción. El modelo
se mantiene únicamente como código de investigación, sin registro, promoción,
servicio de predicciones ni entrenamiento con datos de pacientes.
## Diagnóstico sintético NUTS
El extra opcional `models[bayes]` instala PyMC y ArviZ; no se habilita en
la imagen habitual. En un entorno de desarrollo con ese extra se puede
generar un artefacto JSON aislado con:
```python
from models.cacu.bayes_development.synthetic_diagnostics import evaluate
evaluate("/tmp/diagnostico-bayes.json")
```
El generador usa únicamente datos simulados y el modelo transversal de
prevalencia original, no lee gold ni MLflow y no publica predicciones. El
artefacto incluye R-hat, ESS bulk/tail, divergencias, valores verdaderos,
intervalos y errores de recuperación. La comparación con el PIM actual se
marca como no comparable porque no comparten verosimilitud ni estimando.
Esta prueba no valida el modelo longitudinal ni su uso clínico.
@@ -1,51 +0,0 @@
"""NUTS diagnostics on synthetic prevalence only; no patient or registry access."""
import json
from pathlib import Path
import numpy as np
from scipy.stats import norm
from models.cacu.bayes_development import prevalence_gibbs
def evaluate(path, *, seed=2026, n=300, draws=500, tune=500):
"""Write an isolated JSON artifact; the fitted model is not a longitudinal PIM."""
import arviz as az
import pymc as pm
rng = np.random.default_rng(seed)
truth = np.array([-1.2, 0.7])
kappa = 0.7
X = np.column_stack([np.ones(n), rng.integers(0, 2, n)])
disease = rng.random(n) < norm.cdf(X @ truth)
r = rng.binomial(1, 0.7, n)
y = np.where(r == 1, disease & (rng.random(n) < kappa), np.nan)
model = prevalence_gibbs.pymc_model(X, r, y, np.zeros(2), np.eye(2) * 4,
kappa_ab=(7000, 3000))
with model:
trace = pm.sample(draws=draws, tune=tune, chains=2, cores=1, random_seed=seed,
progressbar=False, compute_convergence_checks=False)
summary = az.summary(trace, var_names=['beta', 'kappa'], kind='all')
parameters = {}
for name, expected in [('beta[0]', truth[0]), ('beta[1]', truth[1]), ('kappa', kappa)]:
row = summary.loc[name]
samples = trace.posterior['kappa'].values if name == 'kappa' else trace.posterior['beta'].values[..., int(name[5])]
low, high = np.quantile(samples, [0.025, 0.975])
parameters[name] = {
'truth': float(expected), 'mean': float(row['mean']),
'error': float(row['mean'] - expected), 'interval_95': [float(low), float(high)],
'covers_truth': bool(low <= expected <= high), 'rhat': float(row['r_hat']),
'ess_bulk': float(row['ess_bulk']), 'ess_tail': float(row['ess_tail']),
}
result = {
'scope': 'synthetic_cross_sectional_prevalence_only', 'seed': seed, 'n': n,
'draws_per_chain': draws, 'tune_per_chain': tune, 'chains': 2,
'divergences': int(trace.sample_stats['diverging'].values.sum()),
'parameters': parameters,
'current_pim_comparison': {'status': 'not_comparable', 'reason':
'The prevalence probit model and the current interval-censored incidence PIM '
'do not have the same likelihood or estimand.'},
}
Path(path).write_text(json.dumps(result, indent=2, allow_nan=False) + '\n')
return result
-4
View File
@@ -30,10 +30,6 @@ dependencies = [
[project.optional-dependencies]
# Where a Dask cluster runs the long batches (testing here); the product runs without it.
dask = ["dask[distributed]>=2026.8.0,<2026.9"] # as the testing cluster runs
bayes = [
"arviz>=0.17",
"pymc>=5.10",
]
[build-system]
requires = ["uv_build>=0.12,<0.13"]
-21
View File
@@ -1,21 +0,0 @@
import json
import pytest
pytest.importorskip('pymc')
pytest.importorskip('arviz')
from models.cacu.bayes_development.synthetic_diagnostics import evaluate
def test_nuts_synthetic_artifact(tmp_path):
path = tmp_path / 'diagnostics.json'
report = evaluate(path, n=80, draws=40, tune=40, seed=31)
assert json.loads(path.read_text()) == report
assert report['scope'] == 'synthetic_cross_sectional_prevalence_only'
assert report['current_pim_comparison']['status'] == 'not_comparable'
assert report['chains'] == 2 and report['divergences'] >= 0
for parameter in report['parameters'].values():
assert parameter['ess_bulk'] > 0 and parameter['ess_tail'] > 0
assert parameter['rhat'] > 0
assert parameter['error'] == pytest.approx(parameter['mean'] - parameter['truth'])