Repository navigation
Add row-wise predictive scores and paired comparison intervals - #49
Draft
BenSaefken wants to merge 2 commits into
Draft
BenSaefken wants to merge 2 commits into
BenSaefken wants to merge 2 commits into
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_scoresoperates on aDistributionPrediction. Each requested loss has a read-only vector in the original row order. The implementation uses these negatively oriented definitions, withSources 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<df<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_differenceapplies common positive weights normalized to one. Forcompare_distributionsacceptsscores,tauandalpha. Optional scores have independent failure reporting. The existing default likelihood ranking andto_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 onDistributionComparisonarerequested_scores,tau,alphaandvalidation_weight, and those onDistributionComparisonRowarescoresandscore_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.
properscoring.crps_gaussiantoCoverage 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.
Initial validation at 95c590a (Windows, Python 3.12.16)
ruff check nampy tests examples,mypy --follow-imports=skip nampy/contracts.py nampy/neural/contracts.py nampy/gam/fit/state.pyandpython tests/repository_hygiene.py.tests/public_api,tests/neural/test_distribution_comparison.py,tests/neural/test_documented_component_contracts.pyandtests/docsyielded 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.python examples/example_paired_scores.pypassed.check_short_examples.pypassed both content assertions, then exited on Windows because its temporary directory was still the process working directory during cleanup.check_documentation.pyfound missing pages in the incomplete output.check_sidebar_navigation.pycould not run without Playwright.check_reference_contracts.pyfailed the global fingerprint audit described above. No notebook was edited.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
core.autocrlf=falsecheckout reproduced the supplied Linux baseline fingerprint exactly. The initial GitHub logs showed the same 382 reference failures in Docs and both full CI suites at95c590a.tests/diagnosticsrun yielded 406 passed, 15 failed. The 15 failures persisted in the canonical checkout:test_mgcv_sos_plots.py::test_sos_prepared_grid_and_predictionswith30-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, and20-450-6-True-True, three cases oftest_sos_generic_scheme_dispatch(schemes 2, 3, 4), and the fourtest_plot_extensions.py::test_derivative_plot_matches_mgcvcases (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.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, andtest_every_tutorial_has_one_track_and_the_gallery_is_linkedcompared a Windows path withapplications/index.rst.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 was31344d16a9881aff70350a063d79a6424370d8ef85aa202a5dbf3654a10348ab. All 890 checked library, example, runner and project files matched their Git blobs. 215/410 examples passed beforestatistical_reference/estimators/CoxGAMraised: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?