Skip to content

Add row-wise predictive scores and paired comparison intervals - #49

Draft
BenSaefken wants to merge 2 commits into
OpenTabular:mainfrom
BenSaefken:codex/rowwise-scores-paired-differences
Draft

BenSaefken wants to merge 2 commits into
OpenTabular:mainfrom
BenSaefken:codex/rowwise-scores-paired-differences

Conversation

@BenSaefken

@BenSaefken BenSaefken commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

Two fitted candidates can now be compared on the same held-out observations with a paired interval for their difference in predictive loss. For example, result.score_differences(reference="GAMLSS", score="crps") reports the weighted mean loss of each candidate minus the reference, its standard error and interval. Negative differences favor the candidate.

Design and score definitions

nampy.diagnostics.proper_scores operates on a DistributionPrediction. Each requested loss has a read-only vector in the original row order. The implementation uses these negatively oriented definitions, with $q_p=F^{-1}(p)$.

Loss Definition
Log $-\log f(y)$ using the law's density or mass
Quantile $(\mathbf{1}{y<q\tau}-\tau)(q_\tau-y)$
Central interval $(u-l)+2[(l-y)++(y-u)+]/\alpha$, with $l=q_{\alpha/2}$ and $u=q_{1-\alpha/2}$
CRPS $\int (F(z)-\mathbf{1}_{z\ge y})^2,dz=E\lvert X-y\rvert-\tfrac12 E\lvert X-X'\rvert$ on the finite-first-absolute-moment domain, for independent draws

Sources for the scoring rules and their evaluation are Matheson & Winkler (1976), Gneiting & Raftery (2007) and Jordan, Krüger & Lerch (2019).

Normal CRPS uses $\sigma[z(2\Phi(z)-1)+2\phi(z)-1/\sqrt{\pi}]$. For Gamma(shape $a$, rate $b$), let $A(t)=t(2F_{a,b}(t)-1)-(a/b)(2F_{a+1,b}(t)-1)$. Its CRPS is $A(y)-1/[bB(1/2,a)]$. Expanding over atom/atom, atom/base and base/base pairs gives a vectorized score for fixed-atom mixtures with Gamma or Normal bases. The Cauchy case uses the finite CDF integral, including the CDF cross terms for atoms, even though its energy expectations diverge. Quadrature remains available for cancellation-prone rows and other laws. Scheuerer & Möller (2015), Jordan, Krüger & Lerch (2019), Appendix A.

For Student-t, the squared-tail integral diverges for $df\le1/2$. At $df=1$ the standard Cauchy score is $(2/\pi)[\log 2+y\arctan y-\tfrac12\log(1+y^2)]$. For $1/2&lt;df&lt;1$, evaluation reports the number of unavailable rows because the implemented tail estimate cannot certify the answer. A missing first moment alone does not imply infinite CRPS. Numerical integration checks its estimated error plus tail and rounding bounds against a relative tolerance of $10^{-8}$. The count-law path caps work at 100,000 steps per row; for instance, a negative-binomial forecast with mean 3,215 and dispersion 1.35 can exceed the budget. One unresolved row makes that requested score vector unavailable.

Signed infinite losses are retained, including negative log loss of $-\infty$ at a density pole. A NaN evaluation on valid observed rows raises an error naming the loss and the affected row count. Missing observations or predictions stay NaN. Unavailable paired differences identify which side has nonfinite loss and on how many positive-weight rows.

paired_score_difference applies common positive weights normalized to one. For $d_i=S_i(C)-S_i(R)$ the independent-row estimate is $\bar d=\sum_i w_i d_i$ with $\mathrm{SE}^2=\sum_i w_i^2(d_i-\bar d)^2/(1-\sum_i w_i^2)$. The interval is $\bar d\pm z_{(1+L)/2}\mathrm{SE}$ at level $L$. Moving-block and whole-group bootstrap replicates renormalize their sampled weights. The replicate SD estimates the standard error and empirical percentiles give the interval. A nonfinite score on any positive-weight row makes that pair unavailable, including infinity on both sides. The table explains failures. An unusable reference raises.

compare_distributions accepts scores, tau and alpha. Optional scores have independent failure reporting. The existing default likelihood ranking and to_frame() columns are preserved. Log differences require matching reference measures and mixed-law atom sets. The other three scores share the response scale across measures. The additive fields on DistributionComparison are requested_scores, tau, alpha and validation_weight, and those on DistributionComparisonRow are scores and score_errors. The public API inventory includes the new signatures and symbols. The diagnostics and comparison method are indexed in the generated reference. The guide, downloadable recipes, changelog and a seeded cross-backend example are included.

Alternatives considered. Putting metrics on fitting backends would duplicate definitions. A Monte Carlo CRPS would add simulation noise to close comparisons. A fixed quantile grid can miss tails or atom jumps. Separate intervals for the two means would discard their within-row covariance. All uncertainty estimates here condition on the fitted forecasts and use paired observations.

Numerical and statistical evidence

An independent test agent derived references from the formulas without seeing the implementation. Tests cover all supplied scalar laws and compositions, including heavy tails, a truncated tail, finite and unbounded count support, atoms, Box–Cox laws, extreme outcomes, missing rows and unavailable operations. The suite also checks the integrated pinball identity, a seeded Monte Carlo energy identity, shift/scale behavior and empirical propriety of all four scores.

  • Across the independent reference cases, the largest observed relative CRPS discrepancy was $6.35\times10^{-13}$ (BCPE). The largest absolute discrepancy was $4.84\times10^{-8}$ at an exponential observation of $10^7$, or $4.84\times10^{-15}$ relative. These are observed errors on the tested parameters.
  • Gaussian CRPS agreed with properscoring.crps_gaussian to $1.11\times10^{-16}$ absolute error. The long-tailed lognormal result agreed with the 40-digit mpmath calculation at float64 rounding.
  • With training-only early stopping, the seeded CPU LinRegLSS stopped after 71 epochs (validation log loss, patience 30). On the 64 held-out rows, neural minus GAMLSS CRPS was 0.0072, SE 0.0036, 95% interval [0.0002, 0.0142]. The difference is small and favors GAMLSS here. The neural fit can also model variation in scale and uses an inner validation split. The repeated run took 34.44 s end to end, including 13.82 s for fitting and comparison; the cold run took 54.49 s.

Coverage of nominal 95% intervals in 2,000 simulated datasets, 512 rows each, true mean difference zero. The stationary Gaussian AR(1) had $\rho=0.65$. Seeds were 271828 for data and 271829 for resampling, with 999 replicates and moving blocks of length 24.

Rows and interval Covered Coverage
Independent rows, analytic 1904/2000 95.20%
AR(1), analytic 1271/2000 63.55%
AR(1), block bootstrap 1853/2000 92.65%

Initial validation at 95c590a (Windows, Python 3.12.16)

  • Passed ruff check nampy tests examples, mypy --follow-imports=skip nampy/contracts.py nampy/neural/contracts.py nampy/gam/fit/state.py and python tests/repository_hygiene.py.
  • Broad run of tests/public_api, tests/neural/test_distribution_comparison.py, tests/neural/test_documented_component_contracts.py and tests/docs yielded 716 passed, 47 skipped, 4 failed. All failures were in documentation. The global reference audit requires a fresh fingerprint for the entire implementation and all existing examples, and the audit compares raw file bytes with normalized execution hashes on a CRLF checkout. The EPUB fixture requires Pandoc. A detailed-figure manifest hashes the raw bytes of existing example scripts. The tutorial gallery test compares Windows paths with a POSIX path literal.
  • The focused post-review run of scoring, pairing, comparison, import boundaries, the real neural fit and the reference target yielded 91 passed. A separate final zero-weight log-array regression passed. Focused numeric regressions cover overflow, cancellation and masked rows. A fresh reviewer independently reproduced and verified the fixes.
  • python examples/example_paired_scores.py passed. check_short_examples.py passed both content assertions, then exited on Windows because its temporary directory was still the process working directory during cleanup.
  • Installed the declared documentation extras into the existing development environment. The three new downloadable reference examples executed successfully. The strict Sphinx HTML build stopped on a notebook because Pandoc is unavailable. check_documentation.py found missing pages in the incomplete output. check_sidebar_navigation.py could not run without Playwright. check_reference_contracts.py failed the global fingerprint audit described above. No notebook was edited.
  • The full pytest tests/ run is left to CI. The upstream CI run on this base commit spent 68 min 24 s on the Python 3.12 test step alone, beyond the local one-hour budget.

At that initial commit the Windows reference audit reported 379 stale existing example records and zero failures for the three new pages. The final strict Sphinx attempt emitted no warning before stopping at missing Pandoc.

Follow-up validation

  • Independent random-grid and CDF-integral checks cover Gamma, zero- and multi-atom Gamma, Normal and Cauchy mixtures. Tests include negative outcomes, observations at atoms, extreme shapes, tiny mixture weights, density poles and side-specific nonfinite diagnostics. Standard Cauchy CRPS is 0.44127120 at zero and 1.33863673 at two.
  • On this Windows CPU, the median of five warmed single-thread runs on 200,000 rows was 0.342 s for Gamma, 0.483 s for zero-adjusted Gamma and 0.277 s for a two-atom Normal mixture. There are no timing assertions.
  • The three project quality gates and commit hooks passed. The environment used Python 3.12.16, NumPy 1.26.4, SciPy 1.17.1 and CPU Torch 2.13.0.
  • The detached core.autocrlf=false checkout reproduced the supplied Linux baseline fingerprint exactly. The initial GitHub logs showed the same 382 reference failures in Docs and both full CI suites at 95c590a.
  • The full tests/diagnostics run yielded 406 passed, 15 failed. The 15 failures persisted in the canonical checkout: test_mgcv_sos_plots.py::test_sos_prepared_grid_and_predictions with 30-30-10-True-False, 30-30-40-True-False, 0-90-8-True-False, 180--90-8-True-False, 750-150-10-True-True, -390--150-10-True-False, 0-0-9-False-True, and 20-450-6-True-True, three cases of test_sos_generic_scheme_dispatch (schemes 2, 3, 4), and the four test_plot_extensions.py::test_derivative_plot_matches_mgcv cases (orders 1 and 2 × ps and bs). All failed to find a static R fixture for the computed key before comparing numerical results. Those fixtures and plotting implementations are unchanged from upstream.
  • Before refreshing records, tests/public_api (including the three focused files and the new closed-form grid), tests/docs, the neural comparison and the two affected diagnostics modules yielded 744 passed, 47 skipped, 18 failed in the calibrated checkout. The public API and neural comparison had no failures. In addition to the 15 above, the global reference audit found stale records, the EPUB fixture lacked Pandoc, and test_every_tutorial_has_one_track_and_the_gallery_is_linked compared a Windows path with applications/index.rst.
  • The completed score-specific run yielded 48 passed in the closed-form and proper-score files. The Gamma/mixture tests compare against the original quadrature with relative tolerance $10^{-10}$, including observations at atoms, below support, and a high-shape cancellation case.

Reference refresh blocked at the requested stop condition. The original checker ran in the calibrated detached worktree with the project on PYTHONPATH. Its new implementation fingerprint was 31344d16a9881aff70350a063d79a6424370d8ef85aa202a5dbf3654a10348ab. All 890 checked library, example, runner and project files matched their Git blobs. 215/410 examples passed before statistical_reference/estimators/CoxGAM raised:

RuntimeError: Fixed-smoothing Cox coefficient fitting failed: Warning: Desired error not necessarily achieved due to precision loss.

The run stopped there. The remaining 194 examples were not evaluated. The same Cox failure was independently reported on Linux main. No partial receipts, schemas, previews, or generated RST noise were committed. The global reference contract still needs a successful 410-example run and a final manifest-only commit.

Limits and questions for maintainers

Intervals are pointwise and describe holdout sampling, conditional on these fits. Block length, row order and independent group definitions belong to the caller. Selection on the same data and refitting uncertainty require a different design. Extreme parameter values can exceed the numerical bounds. The quadrature fallback scores one row at a time. Other continuous laws such as lognormal and Weibull currently take that path.

Would maintainers keep the single quantile probability and single central interval per comparison, and the explicit failure for a pair with nonfinite loss?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant