From 95c590a23a3ccb80a4a50390c54b7d8ac3e503c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20S=C3=A4fken?= Date: Fri, 27 Nov 2026 16:01:26 +0100 Subject: [PATCH 1/2] Add row-wise predictive scores and paired comparison intervals --- CHANGELOG.md | 3 + ...nampy.diagnostics.PairedScoreDifference.py | 6 + ...mpy.diagnostics.paired_score_difference.py | 6 + .../nampy.diagnostics.proper_scores.py | 14 + docs/_examples/reference/output_previews.json | 64 +++ docs/_examples/reference/output_schemas.json | 101 +++++ docs/_examples/reference/verification.json | 18 + docs/_ext/feature_reference.py | 3 +- docs/_ext/reference_symbols.py | 18 + docs/api/contracts.rst | 3 + docs/user_guide/distributional_comparison.rst | 57 ++- examples/example_paired_scores.py | 87 ++++ nampy/diagnostics/__init__.py | 3 + nampy/diagnostics/paired.py | 232 ++++++++++ nampy/diagnostics/scores.py | 381 ++++++++++++++++ nampy/models/comparison.py | 156 ++++++- .../test_distribution_comparison.py | 75 ++++ .../test_paired_score_difference.py | 155 +++++++ tests/public_api/test_proper_scores.py | 408 ++++++++++++++++++ 19 files changed, 1783 insertions(+), 7 deletions(-) create mode 100644 docs/_examples/reference/api/generated/nampy.diagnostics.PairedScoreDifference.py create mode 100644 docs/_examples/reference/api/generated/nampy.diagnostics.paired_score_difference.py create mode 100644 docs/_examples/reference/api/generated/nampy.diagnostics.proper_scores.py create mode 100644 examples/example_paired_scores.py create mode 100644 nampy/diagnostics/paired.py create mode 100644 nampy/diagnostics/scores.py create mode 100644 tests/public_api/test_paired_score_difference.py create mode 100644 tests/public_api/test_proper_scores.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 28aaa922..95816b7f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## 0.3.0 (unreleased) +- Add row-wise proper scores for predictive distributions and paired held-out + score differences with independent-row, moving-block or group intervals. + - Use one complete installation, `pip install nampy`, for statistical and neural models. Remove the `gam`, `neural`, `all`, and `igann-sparse` extras. - Add a first-class `GAMLSS` estimator with named multi-parameter formulas, diff --git a/docs/_examples/reference/api/generated/nampy.diagnostics.PairedScoreDifference.py b/docs/_examples/reference/api/generated/nampy.diagnostics.PairedScoreDifference.py new file mode 100644 index 00000000..fe7a9455 --- /dev/null +++ b/docs/_examples/reference/api/generated/nampy.diagnostics.PairedScoreDifference.py @@ -0,0 +1,6 @@ +"""Runnable reference example: api/generated/nampy.diagnostics.PairedScoreDifference.""" + +from nampy.diagnostics import paired_score_difference + +result = paired_score_difference([1.0, 1.4, 0.9], [1.1, 1.7, 1.0]) +print(result.standard_error) diff --git a/docs/_examples/reference/api/generated/nampy.diagnostics.paired_score_difference.py b/docs/_examples/reference/api/generated/nampy.diagnostics.paired_score_difference.py new file mode 100644 index 00000000..0e9cb13b --- /dev/null +++ b/docs/_examples/reference/api/generated/nampy.diagnostics.paired_score_difference.py @@ -0,0 +1,6 @@ +"""Runnable reference example: api/generated/nampy.diagnostics.paired_score_difference.""" + +from nampy.diagnostics import paired_score_difference + +result = paired_score_difference([1.0, 1.4, 0.9], [1.1, 1.7, 1.0]) +print(result.mean, result.lower, result.upper) diff --git a/docs/_examples/reference/api/generated/nampy.diagnostics.proper_scores.py b/docs/_examples/reference/api/generated/nampy.diagnostics.proper_scores.py new file mode 100644 index 00000000..c996168e --- /dev/null +++ b/docs/_examples/reference/api/generated/nampy.diagnostics.proper_scores.py @@ -0,0 +1,14 @@ +"""Runnable reference example: api/generated/nampy.diagnostics.proper_scores.""" + +import numpy as np +from nampy.distributions import DistributionPrediction, NormalLaw + +n = 24 +x = np.linspace(0, 1, n) +distribution = DistributionPrediction( + NormalLaw(), {'loc': 0.4 + np.sin(3 * x), 'scale': np.full(n, 0.2)}) +y = 0.4 + np.sin(3 * x) + 0.05 * np.cos(np.arange(n)) +from nampy.diagnostics import proper_scores + +result = proper_scores(distribution, y, scores=('log', 'crps')) +print(result['crps'].mean()) diff --git a/docs/_examples/reference/output_previews.json b/docs/_examples/reference/output_previews.json index cf1f94fa..acf3d933 100644 --- a/docs/_examples/reference/output_previews.json +++ b/docs/_examples/reference/output_previews.json @@ -152,6 +152,20 @@ "diagonal" ] }, + "api/generated/nampy.diagnostics.PairedScoreDifference": { + "fields": { + "lower": -0.29733093230267027, + "mean": -0.16666666666666669, + "standard_error": 0.06666666666666667, + "upper": -0.03600240103066307 + }, + "kind": "PairedScoreDifference", + "omitted_fields": [ + "level", + "method", + "n_rows" + ] + }, "api/generated/nampy.diagnostics.center_additive_prediction": { "fields": { "backend": "gam" @@ -218,6 +232,20 @@ ] ] }, + "api/generated/nampy.diagnostics.paired_score_difference": { + "fields": { + "lower": -0.29733093230267027, + "mean": -0.16666666666666669, + "standard_error": 0.06666666666666667, + "upper": -0.03600240103066307 + }, + "kind": "PairedScoreDifference", + "omitted_fields": [ + "level", + "method", + "n_rows" + ] + }, "api/generated/nampy.diagnostics.prepare_centiles": { "fields": { "n_excluded_x": 0, @@ -253,6 +281,42 @@ "bin_edges" ] }, + "api/generated/nampy.diagnostics.proper_scores": { + "crps": { + "kind": "array", + "omitted_by_axis": [ + 18 + ], + "shape": [ + 24 + ], + "values": [ + 0.0517, + 0.04819, + 0.0476, + 0.0516, + 0.04886, + 0.04714 + ] + }, + "log": { + "kind": "array", + "omitted_by_axis": [ + 18 + ], + "shape": [ + 24 + ], + "values": [ + -0.65925, + -0.68138, + -0.68509, + -0.65987, + -0.67715, + -0.68798 + ] + } + }, "api/generated/nampy.diagnostics.quantile_residuals": { "fields": {}, "kind": "QuantileResiduals", diff --git a/docs/_examples/reference/output_schemas.json b/docs/_examples/reference/output_schemas.json index f03569e3..194c0f04 100644 --- a/docs/_examples/reference/output_schemas.json +++ b/docs/_examples/reference/output_schemas.json @@ -841,6 +841,48 @@ "(5,)" ] ], + "api/generated/nampy.diagnostics.PairedScoreDifference": [ + [ + "result", + "nampy.diagnostics.paired.PairedScoreDifference", + "scalar record" + ], + [ + "result.mean", + "builtins.float", + "()" + ], + [ + "result.standard_error", + "builtins.float", + "()" + ], + [ + "result.lower", + "builtins.float", + "()" + ], + [ + "result.upper", + "builtins.float", + "()" + ], + [ + "result.level", + "builtins.float", + "()" + ], + [ + "result.method", + "builtins.str", + "()" + ], + [ + "result.n_rows", + "builtins.int", + "()" + ] + ], "api/generated/nampy.diagnostics.center_additive_prediction": [ [ "result", @@ -1024,6 +1066,48 @@ "(6,)" ] ], + "api/generated/nampy.diagnostics.paired_score_difference": [ + [ + "result", + "nampy.diagnostics.paired.PairedScoreDifference", + "scalar record" + ], + [ + "result.mean", + "builtins.float", + "()" + ], + [ + "result.standard_error", + "builtins.float", + "()" + ], + [ + "result.lower", + "builtins.float", + "()" + ], + [ + "result.upper", + "builtins.float", + "()" + ], + [ + "result.level", + "builtins.float", + "()" + ], + [ + "result.method", + "builtins.str", + "()" + ], + [ + "result.n_rows", + "builtins.int", + "()" + ] + ], "api/generated/nampy.diagnostics.prepare_centiles": [ [ "result", @@ -1310,6 +1394,23 @@ "(5,)" ] ], + "api/generated/nampy.diagnostics.proper_scores": [ + [ + "result", + "dict", + "2 named fields" + ], + [ + "result['log']", + "numpy.ndarray[float64]", + "(24,)" + ], + [ + "result['crps']", + "numpy.ndarray[float64]", + "(24,)" + ] + ], "api/generated/nampy.diagnostics.quantile_residuals": [ [ "result", diff --git a/docs/_examples/reference/verification.json b/docs/_examples/reference/verification.json index ae38f52f..93a14db6 100644 --- a/docs/_examples/reference/verification.json +++ b/docs/_examples/reference/verification.json @@ -65,6 +65,12 @@ "sha256": "911e85c3c6a1c6ae956ee0285f89675d45d0a4d2c3b322c0406c1fe088aed79b", "status": "passed" }, + "api/generated/nampy.diagnostics.PairedScoreDifference": { + "implementation_sha256": "62354d2123443b5d4f9a729c1c45dbf98fd9d8f18df0eee92cab4a01d44440f7", + "preview_version": 2, + "sha256": "b7b4002073607b3ec63a18ccfd5839cb21b8d335d96d64bccbef41c3d984cbf2", + "status": "passed" + }, "api/generated/nampy.diagnostics.center_additive_prediction": { "implementation_sha256": "1848dc11f130321f2cbbe54c16e2461e0638734c745d4ed9de61a9cf20301382", "preview_version": 2, @@ -89,6 +95,12 @@ "sha256": "033fc32ac4813132ebbf734ae6bf044851eea8a50140e6c083992908560d5ff8", "status": "passed" }, + "api/generated/nampy.diagnostics.paired_score_difference": { + "implementation_sha256": "62354d2123443b5d4f9a729c1c45dbf98fd9d8f18df0eee92cab4a01d44440f7", + "preview_version": 2, + "sha256": "29ab54b369f030481426ef17f08f6bcc26a605cfe7ebcc9d0d215d8e7b8d8991", + "status": "passed" + }, "api/generated/nampy.diagnostics.prepare_centiles": { "implementation_sha256": "1848dc11f130321f2cbbe54c16e2461e0638734c745d4ed9de61a9cf20301382", "preview_version": 2, @@ -107,6 +119,12 @@ "sha256": "c0e15ce0130907774e9cefd0ada814b9f1a716dcd6d590894ab5cd60c5550542", "status": "passed" }, + "api/generated/nampy.diagnostics.proper_scores": { + "implementation_sha256": "62354d2123443b5d4f9a729c1c45dbf98fd9d8f18df0eee92cab4a01d44440f7", + "preview_version": 2, + "sha256": "9ccf69682379bdbaca6e15f7baf2d1ef4f077104661396a9498a99a7da336fcb", + "status": "passed" + }, "api/generated/nampy.diagnostics.quantile_residuals": { "implementation_sha256": "1848dc11f130321f2cbbe54c16e2461e0638734c745d4ed9de61a9cf20301382", "preview_version": 2, diff --git a/docs/_ext/feature_reference.py b/docs/_ext/feature_reference.py index 8319c765..6e1ad5f0 100644 --- a/docs/_ext/feature_reference.py +++ b/docs/_ext/feature_reference.py @@ -1313,7 +1313,8 @@ def reference_targets(): } targets["GAM"] = "statistical_reference/GAM" targets.update(dict.fromkeys( - ("DistributionCandidate", "DistributionComparison", "DistributionComparisonRow", "compare_distributions"), + ("DistributionCandidate", "DistributionComparison", "DistributionComparisonRow", "compare_distributions", + "score_differences", "DistributionComparison.score_differences"), "user_guide/distributional_comparison", )) targets.update( diff --git a/docs/_ext/reference_symbols.py b/docs/_ext/reference_symbols.py index ac56765d..5100f84f 100644 --- a/docs/_ext/reference_symbols.py +++ b/docs/_ext/reference_symbols.py @@ -21,6 +21,7 @@ "center_additive_prediction", "explain_additive_prediction", "term_importance_table", "DistributionalEffects", "combine_distributional_effects", "prepare_distributional_effects", "quantile_residuals", "prepare_worm_plot", "prepare_centiles", "centile_calibration", + "proper_scores", "paired_score_difference", "PairedScoreDifference", ], "nampy.plotting": [ "add_density_shading", @@ -223,6 +224,9 @@ y = 0.4 + np.sin(3 * x) + 0.05 * np.cos(np.arange(n)) """ DIAGNOSTIC_EXAMPLES = { + "proper_scores": "from nampy.diagnostics import proper_scores\n\nresult = proper_scores(distribution, y, scores=('log', 'crps'))\nprint(result['crps'].mean())\n", + "paired_score_difference": "from nampy.diagnostics import paired_score_difference\n\nresult = paired_score_difference([1.0, 1.4, 0.9], [1.1, 1.7, 1.0])\nprint(result.mean, result.lower, result.upper)\n", + "PairedScoreDifference": "from nampy.diagnostics import paired_score_difference\n\nresult = paired_score_difference([1.0, 1.4, 0.9], [1.1, 1.7, 1.0])\nprint(result.standard_error)\n", "quantile_residuals": "from nampy.diagnostics import quantile_residuals\n\nresult = quantile_residuals(distribution, y, random_state=7)\nprint(type(result).__name__)\n", "prepare_worm_plot": "from nampy.diagnostics import prepare_worm_plot, quantile_residuals\n\nresiduals = quantile_residuals(distribution, y, random_state=7)\nresult = prepare_worm_plot(residuals, x=x, n_bins=4)\nprint(type(result).__name__)\n", "prepare_centiles": "from nampy.diagnostics import prepare_centiles\n\nresult = prepare_centiles(distribution, x, probs=(0.05, 0.5, 0.95))\nprint(result.quantiles.shape)\n", @@ -238,6 +242,14 @@ _WORM_DATA = "WormPlotData" _CENTILE_DATA = "CentileCurves" DIAGNOSTIC_PARAMETER_TYPES = { + "proper_scores": {"distribution": "DistributionPrediction", "y": _RESPONSE, + "scores": "str | iterable of str", "tau": "float", "alpha": "float"}, + "paired_score_difference": {"candidate": _RESPONSE, "reference": _RESPONSE, + "weights": _RESPONSE + " | None", "level": "float", "method": "str", + "block_length": "int | None", "groups": _RESPONSE + " | None", + "n_resamples": "int", "random_state": "int | numpy.random.Generator | None"}, + "PairedScoreDifference": {"mean": "float", "standard_error": "float", "lower": "float", + "upper": "float", "level": "float", "method": "str", "n_rows": "int"}, "quantile_residuals": { "distribution": "DistributionPrediction", "y": _RESPONSE, @@ -428,6 +440,8 @@ def example(module, name): if name == "prepared_from_interactions": return (CONTRACT_SETUP + "from nampy.plotting import prepared_from_interactions\nX['z'] = np.cos(np.arange(n))\nterms = {'x:z': (X.x * X.z).to_numpy()}\nresult = prepared_from_interactions(X, terms, num_bins=4)\nprint(type(result).__name__)\n") + if name in {"paired_score_difference", "PairedScoreDifference"}: + return DIAGNOSTIC_EXAMPLES[name] if name in DIAGNOSTIC_EXAMPLES: return DIAG_SETUP + DIAGNOSTIC_EXAMPLES[name] if name in {"prepared_from_contributions", "render_term_plots"}: @@ -456,6 +470,10 @@ def example(module, name): def return_description(module, name): + if name == "proper_scores": + return "``dict[str, numpy.ndarray]`` indexed by score name. Each read-only array has one loss per observation, with smaller values favoring the forecast." + if name in {"paired_score_difference", "PairedScoreDifference"}: + return "``PairedScoreDifference`` with the weighted mean loss difference, standard error and pointwise confidence interval on aligned validation rows." if name in {"CapabilityStatus", "DistributionFitStatus"}: return f"``{name}`` immutable record. Support and fit eligibility are separate: a supported prediction operation does not imply convergence or calibrated uncertainty." if name in {"FisherDiagnostics", "FisherInformationResult", "FisherGroupSummary", "FisherSnapshot"}: diff --git a/docs/api/contracts.rst b/docs/api/contracts.rst index b8b3d363..2a006032 100644 --- a/docs/api/contracts.rst +++ b/docs/api/contracts.rst @@ -39,6 +39,9 @@ predictions. Explanation functions operate on that shared representation. CentileCurves centile_calibration CentileCalibration + proper_scores + paired_score_difference + PairedScoreDifference Term metadata diff --git a/docs/user_guide/distributional_comparison.rst b/docs/user_guide/distributional_comparison.rst index f8f09e2e..d5325261 100644 --- a/docs/user_guide/distributional_comparison.rst +++ b/docs/user_guide/distributional_comparison.rst @@ -118,9 +118,9 @@ these automatically. If successful candidates have incompatible measures, all of those candidates remain unranked; their raw scores stay available for inspection. No arbitrary first candidate defines the ranking cohort. -A normalized zero probability gives log score ``-inf`` and ranks last, with its +A normalized zero probability gives log probability ``-inf`` and ranks last, with its count reported. It is distinct from a failed fit. NaN and positive-infinite log -scores are ineligible. Exact score ties share their minimum rank and preserve +probabilities are ineligible. Exact score ties share their minimum rank and preserve candidate order. The result never chooses a tie winner or automatically refits. Calibration and remaining limits @@ -136,10 +136,61 @@ skip calibration. Rowwise log probabilities are retained as read-only snapshots. Statistical EDF/AIC and neural training/regularization quantities are not pooled into a common criterion. Vector responses, censoring records, transformed-response -measure conversion, parallel execution and validation uncertainty intervals remain +measure conversion and parallel execution remain unsupported. No parity with GAMLSS RS/backfitting family searches is claimed; ``fitDistPred`` is a semantic reference for explicit held-out likelihood scoring. +Paired differences on held-out rows +----------------------------------- + +Suppose two models predict the same patients' outcomes. To compare the +forecasts on the response scale, request CRPS and subtract their losses +**within each patient** before estimating uncertainty. + +.. code-block:: python + + result = compare_distributions( + candidates, X_train, y_train, X_valid, y_valid, + scores=("crps", "quantile", "interval"), tau=0.9, alpha=0.1, + ) + table = result.score_differences(reference="lognormal", score="crps") + print(table[["candidate", "mean", "lower", "upper", "reason"]]) + +A negative mean favors the candidate. An interval spanning zero leaves the +direction uncertain at that confidence level. Each interval describes variation +over validation rows conditional on both fits. Selecting the best of many +candidates on these data requires separate evaluation. + +The log loss is the negative of the retained log probability and requires the +same reference measure for the pair. CRPS compares the full predictive CDF, +quantile loss evaluates the specified quantile, and interval loss evaluates +the central prediction interval with coverage ``1 - alpha``. These three losses +use response units and allow comparisons between a count law, a continuous law +and a law with atoms on the same outcome scale. Access the read-only arrays +through ``row.scores``, or call ``nampy.diagnostics.proper_scores`` directly on a +``DistributionPrediction``. In the comparison's optional arrays, zero-weight rows +are marked NaN. Optional scoring failures appear in ``row.score_errors``. + +CRPS uses the finite-first-absolute-moment domain. For example, a Student-t +forecast with at most one degree of freedom receives infinite CRPS because its +energy representation is undefined, even when the CDF integral alone would +converge. The Normal score uses the analytic expression. Numerical scores must +meet the documented tolerance or report a scoring error. + +By default the table uses a normal interval with the weighted paired standard +error. For serial observations, use ``method="block"`` with a ``block_length`` +and validation rows in time order. For independent clusters of dependent rows, +use ``method="group"`` with a label per row in ``groups``. Pass ``random_state=7`` +for reproducibility. Each bootstrap replicate resamples groups or contiguous +blocks, then renormalizes the selected weights. The interval uses bootstrap +percentiles. Its reliability depends on the number of independent groups or +blocks and the chosen block length. Zero-weight rows are removed before +inference. A missing or infinite loss on a positive-weight row makes a pair +unavailable. An unusable reference raises an error because every pair needs it. + +Run ``python examples/example_paired_scores.py`` for a seeded GAMLSS and neural +LSS comparison that prints the paired CRPS differences. + Runnable held-out comparison ---------------------------- diff --git a/examples/example_paired_scores.py b/examples/example_paired_scores.py new file mode 100644 index 00000000..32cde4e9 --- /dev/null +++ b/examples/example_paired_scores.py @@ -0,0 +1,87 @@ +"""Compare mean held-out CRPS of two normal location-scale regressions. + +A positive neural-minus-GAMLSS difference favors GAMLSS. The 95% interval +uses the same independent observations for both fits. Its uncertainty is +conditional on these two trained models. +""" + +from tempfile import TemporaryDirectory + +import numpy as np +import pandas as pd + +from nampy import GAMLSS +from nampy.models import LinRegLSS, compare_distributions +from nampy.neural.configuration import ( + GradientTrainingConfig, + ObjectiveConfig, + PreprocessingConfig, +) + + +def main(): + rng = np.random.default_rng(112) + X = pd.DataFrame({"x": rng.uniform(-1, 1, 192)}) + y = 0.4 + 1.2 * X.x.to_numpy() + rng.normal(0, 0.3, len(X)) + train = slice(0, 128) + holdout = slice(128, None) + + statistical = GAMLSS( + family="normal", + formula={"mu": "y ~ x", "sigma": "~1"}, + optimize_smoothing=False, + ) + with TemporaryDirectory(prefix="nampy-paired-scores-") as checkpoints: + neural = LinRegLSS( + objective=ObjectiveConfig(family="normal"), + preprocessing=PreprocessingConfig( + numerical_preprocessing="standardization" + ), + training=GradientTrainingConfig( + random_state=7, + max_epochs=3, + checkpoint_path=checkpoints, + trainer_kwargs={ + "accelerator": "cpu", + "devices": 1, + "logger": False, + "enable_model_summary": False, + "enable_progress_bar": False, + }, + ), + ) + comparison = compare_distributions( + {"GAMLSS": statistical, "neural_LSS": neural}, + X.iloc[train], + y[train], + X.iloc[holdout], + y[holdout], + scores=("crps",), + ) + table = comparison.score_differences(reference="GAMLSS", score="crps") + if table.reason.notna().any(): + raise RuntimeError(table[["candidate", "reason"]].to_string(index=False)) + print( + table[ + [ + "candidate", + "reference", + "mean", + "standard_error", + "lower", + "upper", + "n_rows", + ] + ].to_string(index=False, float_format="{:.4f}".format) + ) + neural_difference = table.loc[table.candidate == "neural_LSS"].iloc[0] + if neural_difference.lower > 0: + print("GAMLSS has lower held-out CRPS throughout the 95% interval.") + elif neural_difference.upper < 0: + print("The neural LSS has lower held-out CRPS throughout the 95% interval.") + else: + print("The 95% interval includes zero: these rows do not resolve a difference.") + + +if __name__ == "__main__": + main() diff --git a/nampy/diagnostics/__init__.py b/nampy/diagnostics/__init__.py index d842ad36..6a647d4b 100644 --- a/nampy/diagnostics/__init__.py +++ b/nampy/diagnostics/__init__.py @@ -3,6 +3,9 @@ from importlib import import_module _EXPORT_MODULES = { + "proper_scores": ".scores", + "PairedScoreDifference": ".paired", + "paired_score_difference": ".paired", "CentileCalibration": ".distribution", "CentileCurves": ".distribution", "QuantileResiduals": ".distribution", diff --git a/nampy/diagnostics/paired.py b/nampy/diagnostics/paired.py new file mode 100644 index 00000000..a857ca21 --- /dev/null +++ b/nampy/diagnostics/paired.py @@ -0,0 +1,232 @@ +"""Paired uncertainty for held-out predictive score differences.""" + +from __future__ import annotations + +from dataclasses import dataclass +from math import fsum +from numbers import Integral + +import numpy as np +import pandas as pd +from scipy.special import ndtri + + +@dataclass(frozen=True) +class PairedScoreDifference: + """Weighted candidate-minus-reference score difference on held-out rows. + + Parameters + ---------- + mean : float + Weighted mean difference. Negative values favor the candidate. + standard_error : float + Estimated sampling standard deviation of the weighted mean. + lower, upper : float + Endpoints of the two-sided interval. + level : float + Nominal coverage probability. + method : str + Interval method, one of ``iid``, ``block``, or ``group``. + n_rows : int + Number of paired rows with positive weight. + """ + + mean: float + standard_error: float + lower: float + upper: float + level: float + method: str + n_rows: int + + +def _sum_rows(values): + """Sum signed contributions accurately even when large values cancel.""" + return np.fromiter((fsum(row) for row in values), dtype=float, count=len(values)) + + +def _bootstrap_means(differences, weights, method, block_length, labels, count, rng): + weighted = weights * differences + n = len(weights) + if method == "group": + codes, unique = pd.factorize(labels, sort=False) + if np.any(codes < 0) or len(unique) < 2: + raise ValueError( + "groups requires at least two groups and no missing labels." + ) + order = np.argsort(codes, kind="stable") + by_group = np.split(weighted[order], np.cumsum(np.bincount(codes))[:-1]) + sums = _sum_rows(by_group) + masses = np.bincount(codes, weights=weights) + draws_per_sample = len(unique) + remainder = 0 + else: + if not isinstance(block_length, Integral) or not 1 <= block_length < n: + raise ValueError("block_length must be an integer from 1 to n_rows - 1.") + draws_per_sample, remainder = divmod(n, block_length) + windows = np.lib.stride_tricks.sliding_window_view + score_blocks = windows(weighted, block_length) + weight_blocks = windows(weights, block_length) + sums = _sum_rows(score_blocks) + masses = weight_blocks.sum(axis=1) + if remainder: + tail_sums = _sum_rows(score_blocks[:, :remainder]) + tail_masses = weight_blocks[:, :remainder].sum(axis=1) + + means = np.empty(count) + # Bound memory even when resampling many individual rows or groups. + batch = max(1, 100_000 // (draws_per_sample + 1)) + for start in range(0, count, batch): + size = min(batch, count - start) + indices = rng.integers(len(sums), size=(size, draws_per_sample)) + contributions = sums[indices] + totals = masses[indices].sum(axis=1) + if remainder: + final = rng.integers(len(sums), size=size) + contributions = np.column_stack((contributions, tail_sums[final])) + totals += tail_masses[final] + means[start : start + size] = _sum_rows(contributions) / totals + return means + + +def paired_score_difference( + candidate, + reference, + *, + weights=None, + level=0.95, + method="iid", + block_length=None, + groups=None, + n_resamples=2000, + random_state=None, +) -> PairedScoreDifference: + """Estimate a paired difference in negatively oriented predictive scores. + + Parameters + ---------- + candidate, reference : array-like, shape (n,) + Scores in matching row order. A negative mean favors the candidate. + Log scores must be computed with respect to the same reference measure. + weights : array-like, shape (n,), optional + Nonnegative finite row weights, normalized to sum to one. Zero-weight + rows are removed before any scoring or resampling. On retained rows, + a NaN or infinite score raises ValueError, including when both scores + are infinite. At least two positive-weight pairs are required. + level : float, default=0.95 + Coverage probability of the two-sided interval, strictly between 0 and 1. + method : {"iid", "block", "group"}, default="iid" + Normal approximation for independent rows, moving-block bootstrap on + the retained row order, or whole-group bootstrap. + block_length : int, optional + Required for "block", between 1 and n_rows - 1. Draw overlapping + contiguous blocks uniformly with replacement, without wraparound. + Truncate the last drawn block to reproduce the retained sample size. + groups : array-like, shape (n,), optional + Required for "group". Provide at least two distinct nonmissing labels + on retained rows. Sample as many groups as observed, with replacement, + keeping all rows and their weights each time a group is drawn. + n_resamples : int, default=2000 + Number of bootstrap replicates (at least two). Each replicate + renormalizes its row weights. + random_state : int or numpy.random.Generator, optional + Random generator or seed for bootstrap replicates. + + Returns + ------- + PairedScoreDifference + Mean, standard error and interval conditional on the fitted forecasts. + Bootstrap intervals use empirical percentiles and standard errors use + the sample standard deviation of the replicate means. + + Notes + ----- + For normalized weights w and paired differences d, the iid variance + estimate is sum(w**2 * (d - mean)**2) / (1 - sum(w**2)). Equal weights + give the sample variance of the differences divided by the sample size. + The interval is pointwise and does not account for model selection or fit + uncertainty. + """ + candidate = np.asarray(candidate, dtype=float) + reference = np.asarray(reference, dtype=float) + if candidate.ndim != 1 or candidate.shape != reference.shape: + raise ValueError("candidate and reference must be vectors with the same shape.") + if weights is None: + weights = np.ones(candidate.shape) + weights = np.asarray(weights, dtype=float) + if weights.shape != candidate.shape or not np.all( + np.isfinite(weights) & (weights >= 0) + ): + raise ValueError( + "weights must be a finite nonnegative vector matching the scores." + ) + if not np.isfinite(level) or not 0 < level < 1: + raise ValueError("level must be strictly between zero and one.") + if method not in ("iid", "block", "group"): + raise ValueError("method must be 'iid', 'block' or 'group'.") + if (method == "block") != (block_length is not None): + raise ValueError("Supply block_length exactly when method='block'.") + if (method == "group") != (groups is not None): + raise ValueError("Supply groups exactly when method='group'.") + + active = weights > 0 + weights = weights[active] + n = len(weights) + if n < 2: + raise ValueError("At least two positive-weight pairs are required.") + if not ( + np.isfinite(candidate[active]).all() and np.isfinite(reference[active]).all() + ): + raise ValueError("Paired scores must be finite on every positive-weight row.") + with np.errstate(over="raise", invalid="raise", divide="raise"): + differences = candidate[active] - reference[active] + weights = weights / weights.max() + weights /= weights.sum() + if np.any(weights == 0): + raise ValueError("Normalized positive weights are too small to represent.") + # When every value lies within a factor of two of the anchor, the + # subtraction is exact (Sterbenz's lemma). Otherwise centering first + # can erase smaller observations, especially in bootstrap samples. + anchor = differences[weights.argmax()] + if not np.all( + np.abs(differences * 0.5 - anchor * 0.5) + <= 0.5 * np.minimum(np.abs(differences), abs(anchor)) + ): + anchor = 0.0 + offsets = differences - anchor + center = fsum(weights * offsets) + mean = float(anchor + center) + tail = (1 - level) / 2 + if method == "iid": + # 1 - sum(w**2) == twice the sum of products of distinct weights. + # This form avoids cancellation when one row has almost all the weight. + denominator = 2 * (weights[1:] @ np.cumsum(weights[:-1])) + residuals = offsets - center + # Recover the part of the mean rounded away at a dominant row. + deviations = weights * (residuals - fsum(weights * residuals)) + se = np.hypot.reduce(deviations) / np.sqrt(denominator) + margin = -ndtri(tail) * se + lower, upper = mean - margin, mean + margin + else: + if not isinstance(n_resamples, Integral) or n_resamples < 2: + raise ValueError("n_resamples must be an integer of at least 2.") + labels = None + if groups is not None: + labels = np.asarray(groups, dtype=object) + if labels.shape != active.shape: + raise ValueError("groups must have the same shape as the scores.") + labels = labels[active] + means = _bootstrap_means( + offsets, + weights, + method, + block_length, + labels, + n_resamples, + np.random.default_rng(random_state), + ) + se = means.std(ddof=1) + lower, upper = anchor + np.quantile(means, [tail, 1 - tail]) + return PairedScoreDifference( + mean, float(se), float(lower), float(upper), level, method, n + ) diff --git a/nampy/diagnostics/scores.py b/nampy/diagnostics/scores.py new file mode 100644 index 00000000..f997b8ed --- /dev/null +++ b/nampy/diagnostics/scores.py @@ -0,0 +1,381 @@ +"""Proper scoring rules for row-aligned scalar predictive distributions.""" + +from __future__ import annotations + +import numpy as np +from scipy.integrate import cubature +from scipy.special import beta, ndtr + +from ..distributions import ( + AtomMixtureLaw, + BCCGLaw, + BCPELaw, + BCTLaw, + BetaBinomialLaw, + DistributionPrediction, + NegativeBinomialLaw, + NormalLaw, + StudentTLaw, + TruncatedLaw, +) +from ..distributions.observations import log_interval_mass +from .distribution import _vector + +_SCORES = ("log", "crps", "quantile", "interval") +# Binary-exact, with room for representable upper-tail probabilities. +_TAIL = 2.0**-49 +_RTOL = 1e-8 + + +def _score_options(scores, tau, alpha): + names = (scores,) if isinstance(scores, str) else tuple(scores) + if len(set(names)) != len(names) or any(s not in _SCORES for s in names): + raise ValueError(f"scores must contain distinct names from {_SCORES}.") + for name, value in (("tau", tau), ("alpha", alpha)): + if not np.isscalar(value) or not 0 < value < 1: + raise ValueError(f"{name} must be a probability strictly inside (0, 1).") + if "interval" in names and (alpha / 2 == 0 or 1 - alpha / 2 == 1): + raise ValueError("alpha gives interval probabilities outside float precision.") + return names + + +def _first_absolute_bound(row, y, lower, upper): + """Bound E|X-y| for the omitted tails, or return None for divergent E|X|.""" + if np.isfinite(lower) and np.isfinite(upper): + return max(abs(lower - y), abs(upper - y)) + law = row.law + if isinstance(law, AtomMixtureLaw): + mass = np.array([row.parameters[name][0] for name in law.mass_names]) + continuous = ( + 1 - mass.sum() + if law.continuous_mass_name is None + else row.parameters[law.continuous_mass_name][0] + ) + bound = mass @ np.abs(np.asarray(law.atoms) - y) + if continuous == 0: + return bound + base = _base_prediction(row) + lo, hi = base.quantile([0, 1])[0] + component = _first_absolute_bound(base, y, lo, hi) + return None if component is None else bound + continuous * component + if isinstance(law, TruncatedLaw) and "mean" not in row.spec.operations: + base = _base_prediction(row) + lo, hi = base.quantile([0, 1])[0] + bound = _first_absolute_bound(base, y, lo, hi) + log_mass = log_interval_mass( + base.law, + base.parameters, + base.context, + np.array([[law.lower]]), + np.array([[law.upper]]), + ).item() + if bound is None: + return None + with np.errstate(over="ignore", divide="ignore"): + bound /= np.exp(log_mass) + if not np.isfinite(bound): + raise ArithmeticError("Truncated CRPS tail bound exceeds float precision.") + return bound + mean = row.mean().item() + if not np.isfinite(mean): + # These families explicitly report an undefined moment. Other laws + # may simply overflow (e.g. lognormal with a large log-scale). + if isinstance(law, StudentTLaw) and row.parameters["df"][0] <= 1: + return None + if isinstance(law, (BCCGLaw, BCTLaw, BCPELaw)): + nu = row.parameters["nu"][0] + if -1 <= nu < 0: + return None + if isinstance(law, BCTLaw) and ( + nu == 0 or nu > 0 and 1 / nu >= row.parameters["tau"][0] + ): + return None + if isinstance(law, BCPELaw) and nu == 0: + tau = row.parameters["tau"][0] + if tau < 1 or tau == 1 and row.parameters["sigma"][0] >= np.sqrt(2): + return None + raise ArithmeticError("CRPS requires a representable first moment.") + if np.isfinite(lower): + return mean - lower + abs(y - lower) + if np.isfinite(upper): + return upper - mean + abs(y - upper) + # t tails can have a first absolute moment without a variance. + if isinstance(law, StudentTLaw) and row.parameters["df"][0] <= 2: + df = row.parameters["df"][0] + # E|T_df| = 2 sqrt(df) / ((df-1) B(1/2, df/2)). + spread = 2 * np.sqrt(df) / ((df - 1) * beta(0.5, df / 2)) + return abs(mean - y) + row.parameters["scale"][0] * spread + return abs(mean - y) + np.sqrt(row.variance().item()) + + +def _base_prediction(row): + base = row.law.base + return DistributionPrediction( + base, + {name: row.parameters[name] for name in base.spec.parameter_names}, + context=row.context, + ) + + +def _count_crps(row, y): + """Integrate constant CDF steps and bound the unvisited count tail.""" + if isinstance(row.law, BetaBinomialLaw): + stop = int(row.context["trials"][0]) + if stop > 100_000: + raise ArithmeticError( + "Count CRPS exceeds the supported 100000-step budget." + ) + k = np.arange(stop + 1) + pars = {name: np.broadcast_to(v, k.shape) for name, v in row.parameters.items()} + ctx = {"trials": np.full_like(k, stop)} + mass = np.exp(row.law.evaluate("log_prob", pars, context=ctx, values=k)) + if abs(mass.sum() - 1) > 1e-10 or not np.isfinite(mass).all(): + raise ArithmeticError("Beta-binomial mass does not sum to one accurately.") + cdf = np.cumsum(mass)[:-1] + sf = np.cumsum(mass[:0:-1])[::-1] + left = np.clip(y - k[:-1], 0, 1) + return ( + np.sum(left * cdf**2 + (1 - left) * sf**2) + max(-y, 0) + max(y - stop, 0) + ) + lower, upper = row.quantile([0, 1 - 1e-12])[0] + mean = row.mean().item() + if lower != 0 or not np.isfinite(upper) or upper > 100_000: + raise ArithmeticError("Count CRPS exceeds the supported 100000-step budget.") + stop = int(upper) + while stop <= 100_000: + k = np.arange(stop, dtype=float) + pars = {name: np.broadcast_to(v, k.shape) for name, v in row.parameters.items()} + ctx = {name: np.broadcast_to(v, k.shape) for name, v in row.context.items()} + # Split [k,k+1) at y, including when a continuous observation is + # scored against a discrete forecast. + left = np.clip(y - k, 0, 1) + cdf = row.law.evaluate("cdf", pars, context=ctx, values=k) + sf = row.law.evaluate("survival", pars, context=ctx, values=k) + value = np.sum(left * cdf**2 + (1 - left) * sf**2) + value += max(-y, 0) + max(y - stop, 0) + # Beyond stop: integral of S^2 <= S(stop) E[X]. Up to y replacing + # F^2 by 1 incurs at most 2 S(stop) per unit length. + error = row.survival(stop).item() * (mean + 2 * max(y - stop, 0)) + if error <= _RTOL * value: + return value + stop = 2 * stop + 1 + raise ArithmeticError("Count CRPS tail bound exceeds the requested tolerance.") + + +def _discrete_pinball_integral(row, y, qlo): + """Integrate the constant quantile plateaus on the retained probabilities.""" + left = _TAIL + atom = qlo + total = 0.0 + for _ in range(10000): + right = min(row.cdf(atom).item(), 1 - _TAIL) + if not np.isfinite(right) or right < left: + raise ArithmeticError("Discrete CDF and quantile operations disagree.") + # Integrate the linear probability weight exactly on each plateau. + weight = (1 - left) + (1 - right) if atom > y else left + right + total += abs(atom - y) * (right - left) * weight + if right == 1 - _TAIL: + return total + following = row.quantile(np.nextafter(right, 1.0)).item() + if not following > atom: + raise ArithmeticError("Discrete quantile jump cannot be resolved.") + left, atom = right, following + raise ArithmeticError("Discrete CRPS exceeds the 10000-atom enumeration budget.") + + +def _quantile_crps(row, y): + lower, qlo, qhi, upper = row.quantile([0, _TAIL, 1 - _TAIL, 1])[0] + bound = _first_absolute_bound(row, y, lower, upper) + if bound is None: + return np.inf + if lower == upper: + return abs(lower - y) + if not np.isfinite([qlo, qhi, bound]).all(): + raise ArithmeticError("CRPS quantiles or moment bound exceed float precision.") + if row.spec.response_kind == "discrete": + value = _discrete_pinball_integral(row, y, qlo) + error = 0 + else: + value, error = _continuous_pinball_integral(row, y) + # At p < eps, the contribution is bounded by p|y-Q| for Q<=y + # and by (Q(eps)-y)_+ otherwise. Apply the symmetric upper-tail bound. + omitted = 2 * _TAIL * (bound + max(qlo - y, 0) + max(y - qhi, 0)) + # Near a large location a float quantile may lose the whole spread. + # E|Q| <= E|Q-y| + |y| bounds the scale of quantile rounding. + rounding = 2 * np.finfo(float).eps * (bound + abs(y)) + if not np.isfinite(value) or omitted + rounding + error > _RTOL * value: + raise ArithmeticError( + f"{row.spec.name} CRPS could not resolve the quantile integral " + "to relative tolerance 1e-8." + ) + return value + + +def _continuous_pinball_integral(row, y): + splits = [row.cdf(y).item()] + for atom in row.spec.atom_locations or (): + splits.extend([row.cdf_left(atom).item(), row.cdf(atom).item()]) + if not np.all(np.isfinite(splits)): + raise ArithmeticError("CRPS requires finite CDF values.") + # On each half use t = min(p, 1-p), integrate in log(t). Splitting at + # F(y) and the ends of every atom's plateau keeps pinball kinks out of + # the quadrature panels. The t factor below is the log-scale Jacobian. + starts, widths, upper_half = [], [], [] + for high in (False, True): + knots = 1 - np.asarray(splits) if high else np.asarray(splits) + knots = np.unique(np.clip([_TAIL, *knots, 0.5], _TAIL, 0.5)) + log_knots = np.log(knots) + starts.extend(log_knots[:-1]) + widths.extend(np.diff(log_knots)) + upper_half.extend([high] * (len(knots) - 1)) + starts, widths, upper_half = map(np.asarray, (starts, widths, upper_half)) + + def integrand(x): + tail = np.exp(starts + x * widths) + probs = np.where(upper_half, 1 - tail, tail) + q = row.quantile(probs.ravel())[0].reshape(probs.shape) + # Keep the complement directly: 1 - (1 - tail) loses precision. + complement = np.where(upper_half, tail, 1 - tail) + loss = _pinball(y, q, probs, complement) + return 2 * np.sum(loss * tail * widths, axis=1) + + result = cubature(integrand, [0.0], [1.0], rtol=2e-10, max_subdivisions=256) + if result.status != "converged": + raise ArithmeticError(f"{row.spec.name} CRPS quadrature did not converge.") + return float(result.estimate), float(result.error) + + +def _pinball(y, q, probability, complement): + weight = np.where(y < q, complement, probability) + # Subtract first for nearby outcomes. Opposite signs can overflow the + # difference even when the probability-weighted loss fits in a float. + with np.errstate(over="ignore"): + delta = q - y + return np.where( + np.isinf(delta), np.abs(weight * q - weight * y), weight * np.abs(delta) + ) + + +def _crps(distribution, y): + if type(distribution.law) is NormalLaw: + loc = distribution.parameters["loc"] + sd = distribution.parameters["scale"] + with np.errstate(over="ignore", invalid="ignore"): + delta = y - loc + z = delta / sd + # Scale first only where the response difference overflows. + wide = np.isinf(delta) + z[wide] = y[wide] / sd[wide] - loc[wide] / sd[wide] + tilt = 2 * ndtr(z) - 1 + spread = np.sqrt(2 / np.pi) * np.exp(-0.5 * z**2) - 1 / np.sqrt(np.pi) + values = delta * tilt + sd * spread + values[wide] = sd[wide] * (z[wide] * tilt[wide] + spread[wide]) + return values + required = {"quantile", "cdf"} + if distribution.spec.response_kind == "mixed": + required.add("cdf_left") + if distribution.spec.atom_locations is None: + raise NotImplementedError( + "Mixed-law CRPS requires declared atom locations." + ) + counts = isinstance(distribution.law, (NegativeBinomialLaw, BetaBinomialLaw)) + if isinstance(distribution.law, BetaBinomialLaw): + required = {"log_prob"} + elif counts: + required.update(["mean", "survival"]) + missing = required.difference(distribution.spec.operations) + if missing: + raise NotImplementedError( + f"{distribution.spec.name} CRPS requires {sorted(missing)}." + ) + values = np.empty(len(y)) + for i in range(len(y)): + row = DistributionPrediction( + distribution.law, + {k: v[i : i + 1] for k, v in distribution.parameters.items()}, + context={k: v[i : i + 1] for k, v in distribution.context.items()}, + ) + values[i] = _count_crps(row, y[i]) if counts else _quantile_crps(row, y[i]) + return values + + +def proper_scores(distribution, y, *, scores=_SCORES, tau=0.5, alpha=0.1): + """Compute negatively oriented proper scores on aligned prediction rows. + + Parameters + ---------- + distribution : DistributionPrediction + Scalar conditional distributions for the held-out rows. + y : array-like of shape (n,) + Finite observations. NaN observations and missing predictions give NaN. + scores : str or sequence of str, optional + Select any of ``log``, ``crps``, ``quantile``, and ``interval`` (default: all). + tau : float, default=0.5 + Probability strictly inside (0, 1) for the pinball loss. + alpha : float, default=0.1 + Miscoverage probability for the central predictive interval. + + Returns + ------- + dict of str to ndarray + Read-only score vectors. Smaller values favor the forecast. A nonfinite + score on an observed row gives positive infinity. + + Notes + ----- + Log score is minus log density or mass. Pinball loss weights overprediction + by 1-tau and underprediction by tau. Interval score adds 2/alpha times + the distance outside the central interval to its width. + + CRPS uses the finite-first-absolute-moment domain of the energy formula. + A law reporting an undefined first moment (e.g., Student-t with df <= 1) + receives positive infinity. Normal CRPS uses its exact Gaussian expression. + Supplied count laws integrate CDF steps (up to 100,000). Other discrete + laws enumerate up to 10,000 quantile plateaus. For continuous and mixed + laws, CRPS integrates twice the pinball loss in probability space. + Estimated quadrature error, a first-moment bound on omitted tails and a + quantile rounding allowance must together be within 1e-8 relative to + the score, otherwise an ArithmeticError is raised. Declared atoms provide + quadrature breakpoints. + Unbounded laws need a first absolute moment bound, obtained from their + support, moments, or the supplied Student-t parameterization. + + References + ---------- + Matheson and Winkler (1976), Scoring Rules for Continuous Probability + Distributions. Gneiting and Raftery (2007), Strictly Proper Scoring Rules, + Prediction, and Estimation. Jordan, Krüger and Lerch (2019), Evaluating + Probabilistic Forecasts with scoringRules. + """ + names = _score_options(scores, tau, alpha) + y = _vector(y, distribution.n_rows, "y") + if np.isinf(y).any(): + raise ValueError("Observed y must be finite or NaN.") + valid = np.isfinite(y) & np.isfinite( + distribution.parameters[distribution.spec.parameter_names[0]] + ) + if not np.all(valid): + distribution = DistributionPrediction( + distribution.law, + {k: v[valid] for k, v in distribution.parameters.items()}, + context={k: v[valid] for k, v in distribution.context.items()}, + ) + y = y[valid] + result = {} + for name in names: + if name == "log": + value = -distribution.log_prob(y) + elif name == "crps": + value = _crps(distribution, y) + elif name == "quantile": + q = distribution.quantile(tau)[:, 0] + value = _pinball(y, q, tau, 1 - tau) + else: + lo, hi = distribution.quantile([alpha / 2, 1 - alpha / 2]).T + distance = np.maximum(lo - y, 0) + np.maximum(y - hi, 0) + value = (hi - lo) + 2 * distance / alpha + aligned = np.full(valid.shape, np.nan) + aligned[valid] = np.where(np.isfinite(value), value, np.inf) + aligned.setflags(write=False) + result[name] = aligned + return result diff --git a/nampy/models/comparison.py b/nampy/models/comparison.py index a7e46747..b0fa3713 100644 --- a/nampy/models/comparison.py +++ b/nampy/models/comparison.py @@ -5,7 +5,7 @@ import copy import warnings from collections.abc import Callable, Mapping -from dataclasses import dataclass, field, replace +from dataclasses import asdict, dataclass, field, replace from time import perf_counter from types import MappingProxyType from typing import Any, cast @@ -18,6 +18,8 @@ centile_calibration, centile_probabilities, ) +from ..diagnostics.paired import paired_score_difference +from ..diagnostics.scores import _score_options, proper_scores from ..distributions.prediction import DistributionPrediction @@ -82,6 +84,12 @@ class DistributionComparisonRow: calibration_error: str | None = None log_prob: np.ndarray | None = field(default=None, repr=False, compare=False) estimator: Any = field(default=None, repr=False, compare=False) + scores: Mapping[str, np.ndarray] = field( + default_factory=dict, repr=False, compare=False + ) + score_errors: Mapping[str, str] = field( + default_factory=dict, repr=False, compare=False + ) @dataclass(frozen=True) @@ -99,6 +107,107 @@ class DistributionComparison: results: tuple[DistributionComparisonRow, ...] response_units: str | None = None + validation_weight: np.ndarray | None = field( + default=None, repr=False, compare=False + ) + requested_scores: tuple[str, ...] = () + tau: float = 0.5 + alpha: float = 0.1 + + def score_differences( + self, + reference, + score="log", + *, + level=0.95, + method="iid", + block_length=None, + groups=None, + n_resamples=2000, + random_state=None, + ): + """Compare each candidate's loss with a named reference on the holdout. + + Parameters + ---------- + reference : str + Name of a successfully scored candidate. + score : {'log', 'crps', 'quantile', 'interval'} + Negative log probability is always retained. Request other scores + when fitting the comparison. + level : float + Confidence level for each pair. + method : {'iid', 'block', 'group'} + Independent-row normal interval or a bootstrap percentile interval. + block_length : int, optional + Number of successive positive-weight rows in a moving block. + groups : array-like, optional + Group labels in the original validation order. + n_resamples : int + Number of bootstrap replicates. + random_state : int or numpy.random.Generator, optional + Bootstrap seed or generator. + + Returns + ------- + pandas.DataFrame + One row per candidate in input order. A negative mean favors the + candidate. Unavailable pairs carry a reason and empty statistics. + Intervals are pointwise and conditional on the fitted models. + """ + import pandas as pd + + if score != "log" and score not in self.requested_scores: + raise ValueError( + f"Score {score!r} was not requested in compare_distributions." + ) + baseline = next((row for row in self.results if row.name == reference), None) + if baseline is None: + raise ValueError(f"Unknown reference candidate: {reference!r}.") + + def losses(row): + if score == "log" and row.status in {"ok", "incompatible_measure"}: + return -row.log_prob + if score in row.score_errors: + raise ValueError(row.score_errors[score]) + if score in row.scores: + return row.scores[score] + raise ValueError(row.failure_reason or row.status) + + reference_loss = losses(baseline) + options = { + "weights": self.validation_weight, + "level": level, + "method": method, + "block_length": block_length, + "groups": groups, + "n_resamples": n_resamples, + "random_state": random_state, + } + # Validate the reference and the shared resampling design once. + self_difference = paired_score_difference( + reference_loss, reference_loss, **options + ) + records = [] + for row in self.results: + record = {"candidate": row.name, "reference": reference, "score": score} + try: + if ( + score == "log" + and row.status == "incompatible_measure" + and row.measure != baseline.measure + ): + raise ValueError("Incompatible reference measures for log scores.") + result = ( + self_difference + if row is baseline + else paired_score_difference(losses(row), reference_loss, **options) + ) + record.update(asdict(result), reason=None) + except ValueError as error: + record["reason"] = str(error) + records.append(record) + return pd.DataFrame.from_records(records) @property def ranking(self) -> tuple[str, ...]: @@ -183,6 +292,20 @@ def _measure(distribution): return (spec.response_kind, ()) +def _response_scale_scores(distribution, observed, requested, tau, alpha): + values, errors = {}, {} + for rule in requested: + if rule == "log": + continue # Reuse the log probabilities from the existing ranking. + try: + values.update( + proper_scores(distribution, observed, scores=rule, tau=tau, alpha=alpha) + ) + except Exception as error: + errors[rule] = f"{type(error).__name__}: {error}" + return values, errors + + def compare_distributions( candidates: Mapping[str, Any], X_train, @@ -194,6 +317,9 @@ def compare_distributions( validation_weight=None, calibration_probs=(0.05, 0.5, 0.95), response_units: str | None = None, + scores=None, + tau=0.5, + alpha=0.1, ) -> DistributionComparison: """Fit explicit candidates and compare normalized held-out log probabilities. @@ -216,9 +342,17 @@ def compare_distributions( Response units and normalization are the probability law's contract; custom laws must retain any response-transform Jacobian. No cross-backend EDF/AIC or convergence equivalence is claimed. Execution is sequential. + + Set scores to a name or sequence drawn from log, crps, quantile and + interval to retain additional read-only row scores. The quantile uses + probability tau and the central interval uses miscoverage alpha. A failure + of an optional score is recorded in the candidate's score_errors. Use + score_differences to compare against a named reference with uncertainty. """ from sklearn.base import clone + requested = _score_options(scores, tau, alpha) if scores is not None else () + if not isinstance(candidates, Mapping) or not candidates: raise ValueError("candidates must be a nonempty named mapping.") if any(not isinstance(name, str) or not name for name in candidates): @@ -240,6 +374,7 @@ def compare_distributions( training_weights = _weights(sample_weight, len(train_y), "sample_weight") weights = _weights(validation_weight, len(valid_y), "validation_weight") active = weights > 0 + observed = np.where(active, valid_y, np.nan) normalized = weights[active] / weights.sum() n_active, weight_sum = int(active.sum()), float(weights.sum()) effective_n = float(1 / np.sum(normalized**2)) @@ -254,6 +389,7 @@ def compare_distributions( } rows = [] for name, config in configs.items(): + row_scores, score_errors = {}, {} model = None fit_status = DistributionFitStatus( "unknown", "unknown", "Fit has not completed." @@ -323,6 +459,12 @@ def compare_distributions( raise ValueError( "Prediction rows do not match the full validation split; omission/reordering is unsupported." ) + # The response-scale scores do not require a log density + # or a known dominating measure. + if requested: + row_scores, score_errors = _response_scale_scores( + distribution, observed, requested, tau, alpha + ) measure = _measure(distribution) stage = "score" log_prob = np.array( @@ -337,12 +479,15 @@ def compare_distributions( ) score = -np.inf if n_zero else float(np.sum(normalized * selected)) status = "ok" + if "log" in requested: + row_scores["log"] = np.where(active, -log_prob, np.nan) + row_scores["log"].setflags(write=False) if probabilities is not None: if {"cdf", "quantile"} <= distribution.spec.operations: try: calibration = centile_calibration( distribution, - np.where(active, valid_y, np.nan), + observed, probs=probabilities, ) except Exception as error: @@ -389,6 +534,8 @@ def compare_distributions( calibration_error=calibration_error, log_prob=log_prob, estimator=model, + scores=row_scores, + score_errors=score_errors, ) ) measures = {row.measure for row in rows if row.eligible} @@ -415,4 +562,7 @@ def compare_distributions( rank = position previous = rows[index].mean_log_prob rows[index] = replace(rows[index], rank=rank) - return DistributionComparison(tuple(rows), response_units) + weights.setflags(write=False) + return DistributionComparison( + tuple(rows), response_units, weights, requested, tau, alpha + ) diff --git a/tests/public_api/test_distribution_comparison.py b/tests/public_api/test_distribution_comparison.py index e72c597a..ae533340 100644 --- a/tests/public_api/test_distribution_comparison.py +++ b/tests/public_api/test_distribution_comparison.py @@ -331,6 +331,81 @@ def test_common_mixed_measure_is_rankable_and_unknown_atoms_are_explicit(): assert "atom_locations" in result.results[2].failure_reason +def test_paired_scores_keep_validation_rows_and_isolate_optional_errors(): + candidates = { + "ref": _Candidate(behavior="missing"), + "shifted": _Candidate(2.0), + "log_only": _Candidate(kind="log_only"), + "failed": _Candidate(behavior="raise_fit"), + } + weights = np.array([0.0, 2.0, 1.0]) + plain = compare_distributions(candidates, *_inputs(), validation_weight=weights) + result = compare_distributions( + candidates, + *_inputs(), + validation_weight=weights, + scores=["log", "quantile", "interval"], + tau=0.5, + ) + assert plain.ranking == result.ranking + assert list(plain.to_frame()) == list(result.to_frame()) + weights[:] = 1 + table = result.score_differences("ref", "quantile").set_index("candidate") + assert table.loc["ref", "mean"] == 0 + assert table.loc["shifted", "mean"] == -1 + assert table.loc["shifted", "n_rows"] == 2 + assert "quantile" in table.loc["log_only", "reason"] + assert "fit failed" in table.loc["failed", "reason"] + assert np.isnan(table.loc["failed", "lower"]) + assert np.isnan(result.results[0].scores["quantile"][0]) + assert np.isnan(result.results[1].scores["log"][0]) + assert np.isfinite(result.results[1].log_prob[0]) + log = plain.score_differences("ref").set_index("candidate") + assert_allclose(log.loc["shifted", "mean"], -(2 * 2 + 4) / 3) + with pytest.raises(ValueError, match="not requested"): + plain.score_differences("ref", "crps") + with pytest.raises(ValueError, match="Unknown reference"): + result.score_differences("other", "interval") + + +def test_paired_differences_compare_cdfs_across_reference_measures(): + candidates = { + "continuous": _Candidate(), + "other_continuous": _Candidate(2.0), + "count": _Candidate(kind="discrete"), + "atom": _Candidate(kind="mixed0"), + } + result = compare_distributions(candidates, *_inputs(), scores=("crps", "interval")) + assert result.ranking == () + log = result.score_differences("continuous", "log").set_index("candidate") + assert np.isfinite(log.loc["other_continuous", "mean"]) + assert log.loc[["count", "atom"], "reason"].str.contains("measure").all() + for rule in result.requested_scores: + table = result.score_differences( + "continuous", + rule, + method="group", + groups=["a", "a", "b"], + random_state=42, + n_resamples=100, + ).set_index("candidate") + assert table["reason"].isna().all() + for row in result.results: + expected = row.scores[rule] - result.results[0].scores[rule] + assert_allclose(table.loc[row.name, "mean"], np.mean(expected)) + + +def test_missing_measure_metadata_does_not_hide_interval_scores(): + result = compare_distributions( + {"ref": _Candidate(), "atom": _Candidate(kind="mixed_unknown")}, + *_inputs(), + scores="interval", + ) + assert result.ranking == ("ref",) + table = result.score_differences("ref", "interval") + assert np.isfinite(table["mean"]).all() + + @pytest.mark.parametrize( "override", [ diff --git a/tests/public_api/test_paired_score_difference.py b/tests/public_api/test_paired_score_difference.py new file mode 100644 index 00000000..e984c587 --- /dev/null +++ b/tests/public_api/test_paired_score_difference.py @@ -0,0 +1,155 @@ +"""Numerical checks of paired means, sampling units and interval coverage.""" + +import numpy as np +import pytest +from scipy.signal import lfilter +from scipy.stats import norm + +from nampy.diagnostics.paired import paired_score_difference + + +def test_weighted_interval_and_positive_weight_policy(): + candidate = np.array([1.0, 3.0, np.inf, 7.0, np.nan]) + reference = np.array([0.5, 5.0, np.inf, 3.0, 1.0]) + weights = np.array([2, 1, 0, 3, 0]) + result = paired_score_difference(candidate, reference, weights=weights, level=0.90) + d = np.array([0.5, -2.0, 4.0]) + w = np.array([2, 1, 3]) / 6 + mean = np.average(d, weights=w) + se = np.sqrt(np.sum(w**2 * (d - mean) ** 2) / (1.0 - np.sum(w**2))) + assert result.mean == pytest.approx(mean) + assert result.standard_error == pytest.approx(se) + assert result.lower == pytest.approx(mean - norm.ppf(0.95) * se) + assert result.upper == pytest.approx(mean + norm.ppf(0.95) * se) + assert result.n_rows == 3 + for invalid in (np.inf, -np.inf, np.nan): + with pytest.raises(ValueError, match="finite"): + paired_score_difference([invalid, 1.0], [invalid, 2.0]) + + +def test_paired_inference_retains_small_differences_among_large_values(): + result = paired_score_difference([1e16, -1e16, 1], [0, 0, 0]) + assert result.mean == pytest.approx(1 / 3) + result = paired_score_difference( + [1e16, 0.1, 0.2], + [0, 0, 0], + method="group", + groups=[1, 2, 3], + random_state=2, + n_resamples=2000, + ) + assert result.lower == pytest.approx(0.1) + + +@pytest.mark.parametrize( + "options", + [ + {}, + {"method": "block", "block_length": 3}, + {"method": "group", "groups": [2, 2, 1, 1, 3]}, + ], +) +def test_orientation_identical_candidates_and_seed(options): + a = np.array([2.0, 5.0, 6.0, -1.0, 10.0]) + b = np.array([0.0, 1.0, 0.0, 1.0, 1.0]) + params = dict(n_resamples=251, random_state=805, **options) + ab = paired_score_difference(a, b, **params) + ba = paired_score_difference(b, a, **params) + same = paired_score_difference(a, a, **params) + assert (same.mean, same.standard_error, same.lower, same.upper) == (0, 0, 0, 0) + assert ab == paired_score_difference(a, b, **params) + np.testing.assert_allclose( + [ab.mean, ab.standard_error, ab.lower, ab.upper], + [-ba.mean, ba.standard_error, -ba.upper, -ba.lower], + ) + if not options: + assert ab.standard_error == pytest.approx((a - b).std(ddof=1) / np.sqrt(len(a))) + + +@pytest.mark.parametrize("method", ["group", "block"]) +def test_bootstrap_matches_resampling_whole_weighted_units(method): + d = np.array([1.0, 0.0, 1000.0, -3.0, 5.0, 12.0, 2.0]) + weights = np.array([1, 3, 0, 4, 1, 1, 2]) + labels = np.array(["a", "b", None, "a", "b", "a", "c"]) + kwargs = {"groups": labels} if method == "group" else {"block_length": 2} + count = 59 + result = paired_score_difference( + d, + np.zeros_like(d), + weights=weights, + method=method, + random_state=73, + n_resamples=count, + level=0.8, + **kwargs, + ) + valid = np.flatnonzero(weights) + if method == "group": + units = [np.flatnonzero(labels == group) for group in ("a", "b", "c")] + else: + units = [valid[i : i + 2] for i in range(5)] + rng = np.random.default_rng(73) + means = [] + for _ in range(count): + indices = np.concatenate([units[j] for j in rng.integers(len(units), size=3)]) + means.append(np.average(d[indices], weights=weights[indices])) + assert result.standard_error == pytest.approx(np.std(means, ddof=1)) + np.testing.assert_allclose( + [result.lower, result.upper], np.quantile(means, [0.1, 0.9]) + ) + + +@pytest.mark.parametrize( + ("kwargs", "message"), + [ + ({"weights": [1, 0, 0]}, "two"), + ({"weights": [1, -1, 1]}, "weights"), + ({"level": 1}, "level"), + ({"method": "moving"}, "method"), + ({"block_length": 2}, "block_length"), + ({"method": "block", "block_length": 3}, "block_length"), + ({"method": "group", "groups": ["a", "a", "a"]}, "two groups"), + ({"method": "group", "groups": ["a", "b", np.nan]}, "missing"), + ({"method": "group", "groups": ["a", "b"]}, "shape"), + ({"method": "block", "block_length": 1, "n_resamples": 1}, "n_resamples"), + ], +) +def test_invalid_intervals(kwargs, message): + with pytest.raises(ValueError, match=message): + paired_score_difference([0, 1, 2], [0, 0, 0], **kwargs) + + +def _coverage(repetitions, n, n_resamples, block_length, seed): + """Generate paired differences with known mean zero and unit variance.""" + rng = np.random.default_rng(seed) + bootstrap_rng = np.random.default_rng(seed + 1) + covered = np.zeros(3, dtype=int) + zero = np.zeros(n) + rho = 0.65 + for _ in range(repetitions): + iid = rng.standard_normal(n) + innovations = rng.standard_normal(n) * np.sqrt(1 - rho**2) + innovations[0] = rng.standard_normal() # Stationary initial law. + ar = lfilter([1.0], [1.0, -rho], innovations) + results = [ + paired_score_difference(iid, zero), + paired_score_difference(ar, zero), + paired_score_difference( + ar, + zero, + method="block", + block_length=block_length, + random_state=bootstrap_rng, + n_resamples=n_resamples, + ), + ] + covered += [result.lower <= 0 <= result.upper for result in results] + return covered / repetitions + + +def test_seeded_coverage_under_independence_and_serial_dependence(): + iid, ar_iid, ar_block = _coverage(200, 320, 299, 16, 4162) + assert 0.89 <= iid <= 0.99 + assert ar_iid < 0.80 + assert ar_block > 0.85 + assert abs(ar_block - 0.95) < abs(ar_iid - 0.95) diff --git a/tests/public_api/test_proper_scores.py b/tests/public_api/test_proper_scores.py new file mode 100644 index 00000000..800427b7 --- /dev/null +++ b/tests/public_api/test_proper_scores.py @@ -0,0 +1,408 @@ +"""Independent benchmarks for rowwise proper scoring of scalar distributions.""" + +import math + +import mpmath as mp +import numpy as np +import pytest +from numpy.testing import assert_allclose, assert_array_equal +from properscoring import crps_gaussian +from scipy import integrate, special, stats + +from nampy.diagnostics import proper_scores +from nampy.distributions import ( + AtomMixtureLaw, + BCCGLaw, + BCPELaw, + BCTLaw, + BetaBinomialLaw, + BetaLaw, + DistributionPrediction, + DistributionSpec, + GammaLaw, + LogNormalLaw, + NegativeBinomialLaw, + NormalLaw, + StudentTLaw, + TruncatedLaw, + WeibullLaw, +) + + +def _prediction(law, params, n=1, **context): + return DistributionPrediction( + law, {k: np.full(n, v) for k, v in params.items()}, context + ) + + +def _crps(prediction, observations): + return proper_scores(prediction, observations, scores=("crps",))["crps"] + + +def _crps_integral(cdf, sf, y, cuts): + # Split the mathematical CDF integral at every known discontinuity, at + # the observation, and at support boundaries before applying QUADPACK. + edges = sorted({-np.inf, *cuts, y, np.inf}) + terms = [] + for low, high in zip(edges[:-1], edges[1:], strict=True): + probability = cdf if high <= y else sf + value, error = integrate.quad( + lambda x, fn=probability: fn(x) ** 2, + low, + high, + epsabs=1e-12, + epsrel=3e-12, + limit=180, + ) + assert error < 1e-10 * max(1, value) + terms.append(value) + return math.fsum(terms) + + +@pytest.mark.parametrize( + "law,params,rv,y,cuts", + [ + (NormalLaw(), {"loc": 1.2, "scale": 0.8}, stats.norm(1.2, 0.8), -2.0, [1.2]), + ( + GammaLaw(), + {"shape": 0.65, "rate": 1.2}, + stats.gamma(0.65, scale=1 / 1.2), + 0.4, + [0], + ), + ( + LogNormalLaw(), + {"loc": 1.0, "scale": 1.4}, + stats.lognorm(1.4, scale=np.e), + 14, + [0], + ), + ( + WeibullLaw(), + {"shape": 0.6, "scale": 2}, + stats.weibull_min(0.6, scale=2), + 3, + [0], + ), + (BetaLaw(), {"alpha": 0.4, "beta": 1.9}, stats.beta(0.4, 1.9), 0.25, [0, 1]), + # Finite first moment, infinite variance; the outcome is far into the tail. + ( + StudentTLaw(), + {"loc": 0.8, "scale": 1.3, "df": 1.15}, + stats.t(1.15, loc=0.8, scale=1.3), + -28, + [0.8], + ), + ( + TruncatedLaw(NormalLaw(), 8, 9), + {"loc": 0, "scale": 1}, + stats.truncnorm(8, 9), + 8.1, + [8, 9], + ), + ], + ids=[ + "normal", + "gamma", + "lognormal", + "weibull", + "beta", + "heavy-student", + "far-truncated-normal", + ], +) +def test_crps_against_independent_cdf_integral(law, params, rv, y, cuts): + reference = _crps_integral(rv.cdf, rv.sf, y, cuts) + assert_allclose( + _crps(_prediction(law, params), [y]), reference, atol=5e-8, rtol=3e-7 + ) + + +@pytest.mark.parametrize( + "law,latent,extra", + [ + (BCCGLaw(), stats.norm(), {}), + (BCTLaw(), stats.t(3.5), {"tau": 3.5}), + ( + BCPELaw(), + stats.gennorm(1.5, scale=np.sqrt(special.gamma(2 / 3) / special.gamma(2))), + {"tau": 1.5}, + ), + ], + ids=["bccg", "bct", "bcpe"], +) +def test_box_cox_crps_from_conditioned_latent_distribution(law, latent, extra): + mu, sigma, nu = 2.5, 0.7, 1.5 + lower = -1 / (sigma * nu) + normalizer = latent.sf(lower) + + def sf(x): + if x <= 0: + return 1.0 + z = ((x / mu) ** nu - 1) / (nu * sigma) + return latent.sf(z) / normalizer + + reference = _crps_integral(lambda x: 1 - sf(x), sf, 2.1, [0, mu]) + prediction = _prediction(law, dict(mu=mu, sigma=sigma, nu=nu, **extra)) + assert_allclose(_crps(prediction, [2.1]), reference, atol=5e-8, rtol=3e-7) + + +def test_atom_mixture_crps_integrates_both_sides_of_each_jump(): + rv = stats.norm(-0.4, 1.2) + a, b = -1.7, 2.3 + pa, pb, pc = 0.2, 0.45, 0.35 + y = [a, 0.0, 3.7] + prediction = _prediction( + AtomMixtureLaw(NormalLaw(), (a, b), ("pa", "pb")), + {"loc": -0.4, "scale": 1.2, "pa": pa, "pb": pb}, + len(y), + ) + + def cdf(x): + return pc * rv.cdf(x) + pa * (x >= a) + pb * (x >= b) + + def sf(x): + return pc * rv.sf(x) + pa * (x < a) + pb * (x < b) + + expected = [_crps_integral(cdf, sf, value, [a, b]) for value in y] + assert_allclose(_crps(prediction, y), expected, atol=5e-8, rtol=3e-7) + + +@pytest.mark.parametrize( + "law,params,rv,context,upper", + [ + ( + BetaBinomialLaw(), + {"mu": 0.3, "kappa": 5}, + stats.betabinom(13, 1.5, 3.5), + {"trials": [13] * 4}, + 13, + ), + ( + NegativeBinomialLaw(), + {"mean": 4, "dispersion": 0.5}, + stats.nbinom(2, 1 / 3), + {}, + 180, + ), + ], + ids=["beta-binomial", "negative-binomial"], +) +def test_discrete_crps_from_expectations_on_integer_support( + law, params, rv, context, upper +): + # The NB remainder of the first absolute moment is below 1e-26 here. + k = np.arange(upper + 1) + p = rv.pmf(k) + y = np.array([-1.25, 0, 2.7, 21.0]) + gini = p @ np.abs(k[:, None] - k) @ p + expected = np.abs(y[:, None] - k) @ p - 0.5 * gini + prediction = _prediction(law, params, len(y), **context) + assert_allclose(_crps(prediction, y), expected, atol=5e-8, rtol=3e-7) + + +def test_gaussian_reference_across_scales_and_extreme_tails(): + z = np.array([-45.0, -2.0, 0.0, 0.7, 39.0]) + mu = np.array([-2.0, 1.0, 2.0, 3.0, 4.0]) + sd = np.array([3e-5, 0.1, 1.0, 2.0, 1e4]) + y = mu + z * sd + pred = DistributionPrediction(NormalLaw(), {"loc": mu, "scale": sd}) + assert_allclose(_crps(pred, y), crps_gaussian(y, mu, sd), atol=1e-14, rtol=2e-14) + + +def test_exponential_extreme_observation_preserves_order_one_correction(): + # Integrating the squared exponential CDF on [0,y] and squared survival + # beyond y yields y - 3/2 + 2 exp(-y) for a unit-rate exponential. + y = 1e7 + value = _crps(_prediction(GammaLaw(), {"shape": 1, "rate": 1}), [y]) + assert_allclose(value, y - 1.5, rtol=0, atol=2e-6) + + +def test_lognormal_long_upper_tail_against_high_precision_log_scale_integration(): + # At y=0 the integral is just S(x)^2. Under t=log(x), its integrand + # is exp(t)*Phi(-t/sigma)^2. For sigma=3.5 both tails omitted beyond + # +/-110 contribute less than exp(-110) by the Gaussian tail bound. + sigma = 3.5 + with mp.workdps(40): + expected = mp.quad( + lambda t: mp.exp(t) * mp.ncdf(-t / sigma) ** 2, + [-110, -16, 0, 8, 24, 50, 110], + ) + pred = _prediction(LogNormalLaw(), {"loc": 0, "scale": sigma}) + assert_allclose(_crps(pred, [0]), float(expected), atol=5e-8, rtol=3e-7) + + +def test_scores_at_interval_endpoints_tails_and_missing_rows_are_read_only(): + # The uniform law gives q_tau=tau, hence equalities have exact references. + params = np.array([1.0, 1.0, 1.0, 1.0, np.nan]) + prediction = DistributionPrediction(BetaLaw(), {"alpha": params, "beta": params}) + y = np.array([-0.2, 0.1, 0.9, 1.4, 0.5]) + scores = proper_scores(prediction, y, tau=0.25, alpha=0.2) + assert_allclose(scores["interval"], [3.8, 0.8, 0.8, 5.8, np.nan]) + assert_allclose(scores["quantile"], [0.3375, 0.1125, 0.1625, 0.2875, np.nan]) + assert_allclose(scores["log"], [np.inf, 0.0, 0.0, np.inf, np.nan]) + for values in scores.values(): + assert values.shape == y.shape + assert np.isnan(values[-1]) + assert not values.flags.writeable + + +def test_no_first_moment_policy_is_rowwise_and_only_affects_crps(): + prediction = DistributionPrediction( + StudentTLaw(), {"df": [0.6, 1.0, 1.3], "loc": [0.0] * 3, "scale": [1.0] * 3} + ) + scores = proper_scores(prediction, np.zeros(3)) + assert_array_equal(np.isposinf(scores["crps"]), [True, True, False]) + for key in ("log", "quantile", "interval"): + assert np.isfinite(scores[key]).all() + + +def test_moment_restriction_applies_to_the_predictive_law_after_composition(): + # A zero-weight Cauchy component contributes nothing to either energy + # expectation. Conditioning a Cauchy on a bounded interval also restores + # its finite first moment. + params = {"df": 1.0, "loc": 0.0, "scale": 1.0} + point_mass = _prediction( + AtomMixtureLaw(StudentTLaw(), (3.5,), ("p",)), {**params, "p": 1} + ) + assert_allclose(_crps(point_mass, [0.25]), 3.25, atol=1e-7) + trimmed = _prediction(TruncatedLaw(StudentTLaw(), -1, 1), params) + # P(X <= x | -1 < X < 1) = 1/2 + (2/pi) atan(x) on [-1,1]. + expected = ( + 2 * integrate.quad(lambda x: (0.5 - 2 * np.arctan(x) / np.pi) ** 2, 0, 1)[0] + ) + assert_allclose(_crps(trimmed, [0.0]), expected, atol=5e-8, rtol=3e-7) + + +@pytest.mark.parametrize("level", [0, 1, -0.1, np.nan]) +@pytest.mark.parametrize( + "score,parameter", [("interval", "alpha"), ("quantile", "tau")] +) +def test_score_levels_must_be_in_the_open_unit_interval(score, parameter, level): + pred = _prediction(NormalLaw(), {"loc": 0, "scale": 1}) + with pytest.raises(ValueError): + proper_scores(pred, [1.0], scores=(score,), **{parameter: level}) + + +def test_response_shape_must_match_prediction_rows(): + pred = _prediction(NormalLaw(), {"loc": 0, "scale": 1}, n=2) + for invalid in ([0.0], [[1.0], [2.0]]): + with pytest.raises(ValueError): + proper_scores(pred, invalid) + + +def test_crps_equals_integrated_returned_pinball_score(): + prediction = _prediction(BetaLaw(), {"alpha": 2, "beta": 3}) + y = [0.35] + + def integrand(tau): + return ( + 2 + * proper_scores(prediction, y, scores=("quantile",), tau=tau)["quantile"][0] + ) + + reference, error = integrate.quad( + integrand, 0, 1, points=[stats.beta.cdf(y[0], 2, 3)], epsabs=1e-10, epsrel=1e-10 + ) + assert error < 1e-8 + assert_allclose(_crps(prediction, y), reference, atol=5e-8, rtol=3e-7) + + +def test_crps_matches_monte_carlo_energy_identity_with_sampling_error(): + prediction = _prediction( + AtomMixtureLaw(NormalLaw(), (-1.25,), ("p",)), {"loc": 1, "scale": 2, "p": 0.4} + ) + rng = np.random.default_rng(3820) + draws = np.where( + rng.random((2, 60_000)) < 0.4, -1.25, rng.normal(1, 2, (2, 60_000)) + ) + x, independent = draws + terms = np.abs(x - 0.4) - 0.5 * np.abs(x - independent) + se = terms.std(ddof=1) / np.sqrt(len(terms)) + assert abs(_crps(prediction, [0.4])[0] - terms.mean()) < 4 * se + + +def test_positive_affine_transformation_of_scores(): + y = np.array([-4.0, 0.3, 3.5]) + shift, scale = 9.5, 3.25 + before = _prediction(StudentTLaw(), {"df": 4, "loc": 0.5, "scale": 2}, len(y)) + after = _prediction( + StudentTLaw(), {"df": 4, "loc": shift + scale * 0.5, "scale": 2 * scale}, len(y) + ) + base = proper_scores(before, y, tau=0.75) + moved = proper_scores(after, shift + scale * y, tau=0.75) + assert_allclose(moved["log"], base["log"] + np.log(scale)) + for name in ("crps", "quantile", "interval"): + assert_allclose(moved[name], scale * base[name], atol=5e-8, rtol=3e-7) + + +def test_simulated_true_forecast_outscores_shifted_forecast_for_each_score(): + rng = np.random.default_rng(49051) + y = rng.normal(0.5, 1.2, size=750) + true = _prediction(NormalLaw(), {"loc": 0.5, "scale": 1.2}, len(y)) + shifted = _prediction(NormalLaw(), {"loc": 2.0, "scale": 1.2}, len(y)) + scores = proper_scores(true, y, tau=0.7) + shifted_scores = proper_scores(shifted, y, tau=0.7) + for key in ("log", "crps", "quantile", "interval"): + assert scores[key].mean() < shifted_scores[key].mean() + + +def test_missing_required_capability_identified_without_calling_undeclared_operations(): + class MeanOnly: + spec = DistributionSpec( + "mean_only", ("m",), frozenset({"mean"}), "v1", "continuous" + ) + + def validate_parameters(self, parameters, *, context): + pass + + def evaluate(self, operation, parameters, **kwargs): + assert operation == "mean" + return parameters["m"] + + prediction = _prediction(MeanOnly(), {"m": 0}) + for score, required in [ + ("log", "log_prob"), + ("crps", "cdf|quantile"), + ("interval", "quantile"), + ("quantile", "quantile"), + ]: + for observations in ([0.0], [np.nan]): + with pytest.raises((ValueError, NotImplementedError), match=required): + proper_scores(prediction, observations, scores=(score,)) + + +def test_pinball_loss_when_only_the_unweighted_difference_overflows(): + locations = np.array([1.1e308, -1.1e308]) + prediction = DistributionPrediction( + NormalLaw(), {"loc": locations, "scale": np.ones(2)} + ) + for tau, expected in [(0.5, [1.1e308, 1.1e308]), (0.25, [1.65e308, 5.5e307])]: + actual = proper_scores(prediction, -locations, scores="quantile", tau=tau) + assert_allclose(actual["quantile"], expected, rtol=3e-16) + + +def test_normal_crps_with_opposite_sign_extremes_and_representable_score(): + # CRPS is homogeneous under positive rescaling. Compute on a unit scale + # with an independent Gaussian reference before restoring response units. + loc = np.array([1.1, -1.1]) + expected = crps_gaussian(-loc, loc, 1.0) * 1e308 + prediction = DistributionPrediction( + NormalLaw(), {"loc": loc * 1e308, "scale": np.full(2, 1e308)} + ) + assert_allclose(_crps(prediction, -loc * 1e308), expected, rtol=1e-15) + + +def test_missing_outcome_skips_unresolvable_quantile_and_preserves_row_order(): + law = TruncatedLaw(StudentTLaw(), 0, np.inf) + prediction = DistributionPrediction( + law, {"loc": [0, -1e8, 1], "scale": np.ones(3), "df": np.full(3, 3)} + ) + observed = DistributionPrediction( + law, {"loc": [0, 1], "scale": np.ones(2), "df": np.full(2, 3)} + ) + names = ("quantile", "interval", "log") + actual = proper_scores(prediction, [2, np.nan, 2], scores=names) + reference = proper_scores(observed, [2, 2], scores=names) + for name in names: + assert_allclose(actual[name], [reference[name][0], np.nan, reference[name][1]]) From a82fcea9fda8d88f3b5bd8a0b0a8a3eed5a197a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20S=C3=A4fken?= Date: Fri, 27 Nov 2026 17:52:26 +0100 Subject: [PATCH 2/2] Preserve signed losses and accelerate Gamma and atom-mixture CRPS --- docs/_data/public_reference_inventory.json | 174 +++++++++++++- docs/user_guide/distributional_comparison.rst | 25 +- examples/example_paired_scores.py | 17 +- nampy/diagnostics/paired.py | 17 +- nampy/diagnostics/scores.py | 218 ++++++++++++++---- nampy/models/comparison.py | 43 +++- tests/public_api/test_closed_form_crps.py | 93 ++++++++ .../test_distribution_comparison.py | 34 +++ .../test_paired_score_difference.py | 10 + tests/public_api/test_proper_scores.py | 73 +++++- 10 files changed, 634 insertions(+), 70 deletions(-) create mode 100644 tests/public_api/test_closed_form_crps.py diff --git a/docs/_data/public_reference_inventory.json b/docs/_data/public_reference_inventory.json index ae7f3464..4867075c 100644 --- a/docs/_data/public_reference_inventory.json +++ b/docs/_data/public_reference_inventory.json @@ -4384,7 +4384,7 @@ "kind": "extension", "symbol": "DistributionComparison", "public_import": "nampy.models.DistributionComparison", - "signature": "(results: 'tuple[DistributionComparisonRow, ...]', response_units: 'str | None' = None) -> None", + "signature": "(results: 'tuple[DistributionComparisonRow, ...]', response_units: 'str | None' = None, validation_weight: 'np.ndarray | None' = None, requested_scores: 'tuple[str, ...]' = (), tau: 'float' = 0.5, alpha: 'float' = 0.1) -> None", "parameters": [ { "name": "results", @@ -4393,6 +4393,22 @@ { "name": "response_units", "default": "None" + }, + { + "name": "validation_weight", + "default": "None" + }, + { + "name": "requested_scores", + "default": "()" + }, + { + "name": "tau", + "default": "0.5" + }, + { + "name": "alpha", + "default": "0.1" } ], "page": "user_guide/distributional_comparison", @@ -4408,7 +4424,7 @@ "kind": "extension", "symbol": "DistributionComparisonRow", "public_import": "nampy.models.DistributionComparisonRow", - "signature": "(name: 'str', fit_status: 'DistributionFitStatus', status: 'str', eligible: 'bool', rank: 'int | None', mean_log_prob: 'float | None', n_validation: 'int', n_scored: 'int', n_zero_probability: 'int', validation_weight_sum: 'float', effective_n: 'float', fit_seconds: 'float', evaluation_seconds: 'float', warnings: 'tuple[str, ...]' = (), failure_stage: 'str | None' = None, failure_reason: 'str | None' = None, measure: 'tuple[str, tuple[float, ...]] | None' = None, calibration: 'CentileCalibration | None' = None, calibration_error: 'str | None' = None, log_prob: 'np.ndarray | None' = None, estimator: 'Any' = None) -> None", + "signature": "(name: 'str', fit_status: 'DistributionFitStatus', status: 'str', eligible: 'bool', rank: 'int | None', mean_log_prob: 'float | None', n_validation: 'int', n_scored: 'int', n_zero_probability: 'int', validation_weight_sum: 'float', effective_n: 'float', fit_seconds: 'float', evaluation_seconds: 'float', warnings: 'tuple[str, ...]' = (), failure_stage: 'str | None' = None, failure_reason: 'str | None' = None, measure: 'tuple[str, tuple[float, ...]] | None' = None, calibration: 'CentileCalibration | None' = None, calibration_error: 'str | None' = None, log_prob: 'np.ndarray | None' = None, estimator: 'Any' = None, scores: 'Mapping[str, np.ndarray]' = , score_errors: 'Mapping[str, str]' = ) -> None", "parameters": [ { "name": "name", @@ -4493,6 +4509,14 @@ { "name": "estimator", "default": "None" + }, + { + "name": "scores", + "default": "" + }, + { + "name": "score_errors", + "default": "" } ], "page": "user_guide/distributional_comparison", @@ -4708,7 +4732,7 @@ "kind": "extension", "symbol": "compare_distributions", "public_import": "nampy.models.compare_distributions", - "signature": "(candidates: 'Mapping[str, Any]', X_train, y_train, X_valid, y_valid, *, sample_weight=None, validation_weight=None, calibration_probs=(0.05, 0.5, 0.95), response_units: 'str | None' = None) -> 'DistributionComparison'", + "signature": "(candidates: 'Mapping[str, Any]', X_train, y_train, X_valid, y_valid, *, sample_weight=None, validation_weight=None, calibration_probs=(0.05, 0.5, 0.95), response_units: 'str | None' = None, scores=None, tau=0.5, alpha=0.1) -> 'DistributionComparison'", "parameters": [ { "name": "candidates", @@ -4745,6 +4769,18 @@ { "name": "response_units", "default": "None" + }, + { + "name": "scores", + "default": "None" + }, + { + "name": "tau", + "default": "0.5" + }, + { + "name": "alpha", + "default": "0.1" } ], "page": "user_guide/distributional_comparison", @@ -7936,6 +7972,50 @@ "tests/docs/test_feature_reference.py" ] }, + { + "kind": "shared", + "symbol": "PairedScoreDifference", + "public_import": "nampy.diagnostics.PairedScoreDifference", + "signature": "(mean: 'float', standard_error: 'float', lower: 'float', upper: 'float', level: 'float', method: 'str', n_rows: 'int') -> None", + "parameters": [ + { + "name": "mean", + "default": "required" + }, + { + "name": "standard_error", + "default": "required" + }, + { + "name": "lower", + "default": "required" + }, + { + "name": "upper", + "default": "required" + }, + { + "name": "level", + "default": "required" + }, + { + "name": "method", + "default": "required" + }, + { + "name": "n_rows", + "default": "required" + } + ], + "page": "api/generated/nampy.diagnostics.PairedScoreDifference", + "example": "api/generated/nampy.diagnostics.PairedScoreDifference", + "input_contract": "api/generated/nampy.diagnostics.PairedScoreDifference", + "return_schema": "_examples/reference/output_schemas.json#api/generated/nampy.diagnostics.PairedScoreDifference", + "restrictions": "api/generated/nampy.diagnostics.PairedScoreDifference", + "tests": [ + "tests/docs/test_feature_reference.py" + ] + }, { "kind": "shared", "symbol": "ParsedFormulaComponent", @@ -8432,6 +8512,58 @@ "tests/docs/test_feature_reference.py" ] }, + { + "kind": "shared", + "symbol": "paired_score_difference", + "public_import": "nampy.diagnostics.paired_score_difference", + "signature": "(candidate, reference, *, weights=None, level=0.95, method='iid', block_length=None, groups=None, n_resamples=2000, random_state=None) -> 'PairedScoreDifference'", + "parameters": [ + { + "name": "candidate", + "default": "required" + }, + { + "name": "reference", + "default": "required" + }, + { + "name": "weights", + "default": "None" + }, + { + "name": "level", + "default": "0.95" + }, + { + "name": "method", + "default": "'iid'" + }, + { + "name": "block_length", + "default": "None" + }, + { + "name": "groups", + "default": "None" + }, + { + "name": "n_resamples", + "default": "2000" + }, + { + "name": "random_state", + "default": "None" + } + ], + "page": "api/generated/nampy.diagnostics.paired_score_difference", + "example": "api/generated/nampy.diagnostics.paired_score_difference", + "input_contract": "api/generated/nampy.diagnostics.paired_score_difference", + "return_schema": "_examples/reference/output_schemas.json#api/generated/nampy.diagnostics.paired_score_difference", + "restrictions": "api/generated/nampy.diagnostics.paired_score_difference", + "tests": [ + "tests/docs/test_feature_reference.py" + ] + }, { "kind": "shared", "symbol": "parse_gam_formula", @@ -8804,6 +8936,42 @@ "tests/docs/test_feature_reference.py" ] }, + { + "kind": "shared", + "symbol": "proper_scores", + "public_import": "nampy.diagnostics.proper_scores", + "signature": "(distribution, y, *, scores=('log', 'crps', 'quantile', 'interval'), tau=0.5, alpha=0.1)", + "parameters": [ + { + "name": "distribution", + "default": "required" + }, + { + "name": "y", + "default": "required" + }, + { + "name": "scores", + "default": "('log', 'crps', 'quantile', 'interval')" + }, + { + "name": "tau", + "default": "0.5" + }, + { + "name": "alpha", + "default": "0.1" + } + ], + "page": "api/generated/nampy.diagnostics.proper_scores", + "example": "api/generated/nampy.diagnostics.proper_scores", + "input_contract": "api/generated/nampy.diagnostics.proper_scores", + "return_schema": "_examples/reference/output_schemas.json#api/generated/nampy.diagnostics.proper_scores", + "restrictions": "api/generated/nampy.diagnostics.proper_scores", + "tests": [ + "tests/docs/test_feature_reference.py" + ] + }, { "kind": "shared", "symbol": "quantile_residuals", diff --git a/docs/user_guide/distributional_comparison.rst b/docs/user_guide/distributional_comparison.rst index d5325261..d5c5db7d 100644 --- a/docs/user_guide/distributional_comparison.rst +++ b/docs/user_guide/distributional_comparison.rst @@ -169,13 +169,21 @@ use response units and allow comparisons between a count law, a continuous law and a law with atoms on the same outcome scale. Access the read-only arrays through ``row.scores``, or call ``nampy.diagnostics.proper_scores`` directly on a ``DistributionPrediction``. In the comparison's optional arrays, zero-weight rows -are marked NaN. Optional scoring failures appear in ``row.score_errors``. - -CRPS uses the finite-first-absolute-moment domain. For example, a Student-t -forecast with at most one degree of freedom receives infinite CRPS because its -energy representation is undefined, even when the CDF integral alone would -converge. The Normal score uses the analytic expression. Numerical scores must -meet the documented tolerance or report a scoring error. +are marked NaN. The log loss is positive infinity at a zero probability +and negative infinity at a density pole. A NaN from evaluation on an +observed row with valid parameters raises an error naming the score and +the number of affected rows. Optional scoring failures in a comparison +appear in ``row.score_errors``. + +CRPS integrates the squared difference between the forecast CDF and the +observed step function. Student-t tails give infinite CRPS at or below half a +degree of freedom. Between half and one degree of freedom the integral is +finite, but the numerical method lacks a tail bound and reports the affected +row count. At one degree of freedom (Cauchy) the CDF integral has a closed +form. Normal, Gamma and their fixed-atom mixtures also use analytic scores. +The fallback checks the accuracy of numerical scores. Supplied count laws +have a budget of 100,000 CDF steps per row. Exceeding it makes the requested +CRPS vector unavailable. By default the table uses a normal interval with the weighted paired standard error. For serial observations, use ``method="block"`` with a ``block_length`` @@ -186,7 +194,8 @@ blocks, then renormalizes the selected weights. The interval uses bootstrap percentiles. Its reliability depends on the number of independent groups or blocks and the chosen block length. Zero-weight rows are removed before inference. A missing or infinite loss on a positive-weight row makes a pair -unavailable. An unusable reference raises an error because every pair needs it. +unavailable. The reason identifies the affected side and row count. An +unusable reference raises an error because every pair needs it. Run ``python examples/example_paired_scores.py`` for a seeded GAMLSS and neural LSS comparison that prints the paired CRPS differences. diff --git a/examples/example_paired_scores.py b/examples/example_paired_scores.py index 32cde4e9..427faf92 100644 --- a/examples/example_paired_scores.py +++ b/examples/example_paired_scores.py @@ -3,6 +3,9 @@ A positive neural-minus-GAMLSS difference favors GAMLSS. The 95% interval uses the same independent observations for both fits. Its uncertainty is conditional on these two trained models. + +GAMLSS fits a constant scale. The neural model can also learn a scale trend +and reserves a fifth of the training rows for early stopping on log loss. """ from tempfile import TemporaryDirectory @@ -39,7 +42,11 @@ def main(): ), training=GradientTrainingConfig( random_state=7, - max_epochs=3, + max_epochs=400, + lr=0.025, + patience=30, + val_size=0.2, + monitor="val_loss", checkpoint_path=checkpoints, trainer_kwargs={ "accelerator": "cpu", @@ -61,6 +68,14 @@ def main(): table = comparison.score_differences(reference="GAMLSS", score="crps") if table.reason.notna().any(): raise RuntimeError(table[["candidate", "reason"]].to_string(index=False)) + fitted = comparison.models["neural_LSS"] + if fitted.n_epochs_ == fitted.training.max_epochs: + print(f"Neural LSS reached its budget of {fitted.n_epochs_} epochs.") + else: + print( + f"Neural LSS stopped after {fitted.n_epochs_} epochs when inner " + f"validation loss had not improved for {fitted.training.patience} epochs." + ) print( table[ [ diff --git a/nampy/diagnostics/paired.py b/nampy/diagnostics/paired.py index a857ca21..22452346 100644 --- a/nampy/diagnostics/paired.py +++ b/nampy/diagnostics/paired.py @@ -89,6 +89,18 @@ def _bootstrap_means(differences, weights, method, block_length, labels, count, return means +def _require_finite_losses(**sides): + problems = [] + for side, losses in sides.items(): + count = np.count_nonzero(~np.isfinite(losses)) + if count: + problems.append( + f"{side} loss is not finite on {count} positive-weight row(s)" + ) + if problems: + raise ValueError("; ".join(problems) + ".") + + def paired_score_difference( candidate, reference, @@ -172,12 +184,9 @@ def paired_score_difference( active = weights > 0 weights = weights[active] n = len(weights) + _require_finite_losses(candidate=candidate[active], reference=reference[active]) if n < 2: raise ValueError("At least two positive-weight pairs are required.") - if not ( - np.isfinite(candidate[active]).all() and np.isfinite(reference[active]).all() - ): - raise ValueError("Paired scores must be finite on every positive-weight row.") with np.errstate(over="raise", invalid="raise", divide="raise"): differences = candidate[active] - reference[active] weights = weights / weights.max() diff --git a/nampy/diagnostics/scores.py b/nampy/diagnostics/scores.py index f997b8ed..67ca0466 100644 --- a/nampy/diagnostics/scores.py +++ b/nampy/diagnostics/scores.py @@ -4,15 +4,13 @@ import numpy as np from scipy.integrate import cubature -from scipy.special import beta, ndtr +from scipy.special import beta, gammainc, ndtr, poch from ..distributions import ( AtomMixtureLaw, - BCCGLaw, - BCPELaw, - BCTLaw, BetaBinomialLaw, DistributionPrediction, + GammaLaw, NegativeBinomialLaw, NormalLaw, StudentTLaw, @@ -40,7 +38,7 @@ def _score_options(scores, tau, alpha): def _first_absolute_bound(row, y, lower, upper): - """Bound E|X-y| for the omitted tails, or return None for divergent E|X|.""" + """Bound E|X-y| for the omitted tails when a finite bound is available.""" if np.isfinite(lower) and np.isfinite(upper): return max(abs(lower - y), abs(upper - y)) law = row.law @@ -57,7 +55,7 @@ def _first_absolute_bound(row, y, lower, upper): base = _base_prediction(row) lo, hi = base.quantile([0, 1])[0] component = _first_absolute_bound(base, y, lo, hi) - return None if component is None else bound + continuous * component + return bound + continuous * component if isinstance(law, TruncatedLaw) and "mean" not in row.spec.operations: base = _base_prediction(row) lo, hi = base.quantile([0, 1])[0] @@ -69,8 +67,6 @@ def _first_absolute_bound(row, y, lower, upper): np.array([[law.lower]]), np.array([[law.upper]]), ).item() - if bound is None: - return None with np.errstate(over="ignore", divide="ignore"): bound /= np.exp(log_mass) if not np.isfinite(bound): @@ -78,23 +74,7 @@ def _first_absolute_bound(row, y, lower, upper): return bound mean = row.mean().item() if not np.isfinite(mean): - # These families explicitly report an undefined moment. Other laws - # may simply overflow (e.g. lognormal with a large log-scale). - if isinstance(law, StudentTLaw) and row.parameters["df"][0] <= 1: - return None - if isinstance(law, (BCCGLaw, BCTLaw, BCPELaw)): - nu = row.parameters["nu"][0] - if -1 <= nu < 0: - return None - if isinstance(law, BCTLaw) and ( - nu == 0 or nu > 0 and 1 / nu >= row.parameters["tau"][0] - ): - return None - if isinstance(law, BCPELaw) and nu == 0: - tau = row.parameters["tau"][0] - if tau < 1 or tau == 1 and row.parameters["sigma"][0] >= np.sqrt(2): - return None - raise ArithmeticError("CRPS requires a representable first moment.") + raise ArithmeticError("no finite first-moment bound for the omitted tails") if np.isfinite(lower): return mean - lower + abs(y - lower) if np.isfinite(upper): @@ -184,10 +164,12 @@ def _discrete_pinball_integral(row, y, qlo): def _quantile_crps(row, y): + # Student-t tails decay as x**(-df). Their squared integral diverges + # precisely when 2*df <= 1, independently of the observation. + if type(row.law) is StudentTLaw and row.parameters["df"][0] <= 0.5: + return np.inf lower, qlo, qhi, upper = row.quantile([0, _TAIL, 1 - _TAIL, 1])[0] bound = _first_absolute_bound(row, y, lower, upper) - if bound is None: - return np.inf if lower == upper: return abs(lower - y) if not np.isfinite([qlo, qhi, bound]).all(): @@ -256,6 +238,122 @@ def _pinball(y, q, probability, complement): ) +def _cauchy_crps(loc, scale, y): + """Integrate the squared Cauchy CDF on the response scale.""" + # The standard score at zero is 2 log(2)/pi. Its derivative at z is + # 2 F(z) - 1 = 2 atan(z)/pi, so the increment is proportional to + # z atan(z) - log(hypot(1,z)). Rescale before forming a large ratio. + from scipy.special import xlogy + + with np.errstate(over="ignore", under="ignore"): + distance = np.abs(y - loc) + wide = np.isinf(distance) + distance = np.where(wide, np.abs(0.5 * y - 0.5 * loc), distance) + sd = np.where(wide, 0.5 * scale, scale) + unit = np.maximum(distance, sd) + x, s = distance / unit, sd / unit + value = ( + (2 / np.pi) + * ( + x * np.arctan2(x, s) + + s * (np.log(2.0) - np.log(np.hypot(s, x))) + + xlogy(s, s) + ) + * unit + ) + return np.where(wide, value * 2, value) + + +def _score_potential(law, parameters, t): + """Potential with derivative 2F(t)-1 and its numerical error scale.""" + if type(law) is StudentTLaw: + # Cauchy E|X-t| is infinite, but its CRPS is a finite potential with + # derivative 2F(t)-1. Only its differences enter mixture cross terms. + value = _cauchy_crps(parameters["loc"], parameters["scale"], t) + return value, value + if type(law) is GammaLaw: + shape, rate = parameters["shape"], parameters["rate"] + mean = shape / rate + if np.isscalar(t) and t <= 0: + return mean - t, mean - t + x = rate * np.maximum(t, 0) + # E[X 1(X <= t)] = mean * F_{shape+1,rate}(t). + deviation = t * (2 * gammainc(shape, x) - 1) - mean * ( + 2 * gammainc(shape + 1, x) - 1 + ) + return deviation, abs(t) + mean + sd = parameters["scale"] + delta = t - parameters["loc"] + z = delta / sd + deviation = delta * (2 * ndtr(z) - 1) + sd * np.sqrt(2 / np.pi) * np.exp( + -(z**2) / 2 + ) + return deviation, abs(delta) + sd + + +def _closed_crps(law, parameters, y): + """Evaluate scalar closed forms and pairwise cross terms for fixed atoms.""" + mixed = type(law) is AtomMixtureLaw + base = law.base if mixed else law + deviation, y_scale = _score_potential(base, parameters, y) + if type(base) is GammaLaw: + # Half E|X-X'| = 1 / (rate * B(1/2, shape)). + shape = parameters["shape"] + ratio = poch(shape, 0.5) + # Subtracting two large log-gammas degrades the ratio near 1e4. + # In this range Stirling's expansion has omitted O(shape**-4) terms. + large = shape > 1000 + inv = 1 / shape[large] + ratio[large] = np.sqrt(shape[large]) * ( + 1 + inv * (-1 / 8 + inv * (1 / 128 + inv * (5 / 1024))) + ) + half_pair = ratio / np.sqrt(np.pi) / parameters["rate"] + elif type(base) is NormalLaw: + half_pair = parameters["scale"] / np.sqrt(np.pi) + else: + half_pair = 0.0 # The Cauchy potential is already the base CRPS. + values = deviation - half_pair + scale = y_scale + half_pair + if mixed: + masses, continuous = law._weights(parameters) + # Expand the squared CDF residual of the mixture into component pairs. + # A base/atom cross integral is the integral of F from atom to y + # (atom < y) or of 1-F from y to atom. As the potential derivative + # is 2F-1, twice that integral is D(y)-D(atom)+|y-atom|. + # When y equals an atom the cross term vanishes exactly. This keeps + # the continuous^2 contribution even for an almost pure point mass. + values = np.where(continuous > 0, continuous * (continuous * values), 0) + scale = np.where(continuous > 0, continuous * (continuous * scale), 0) + for j, atom in enumerate(law.atoms): + p = masses[:, j] + distance = abs(y - atom) + values += np.where(p > 0, p * (p * distance), 0) + atom_deviation, atom_scale = _score_potential(base, parameters, atom) + cross = (deviation - atom_deviation) + distance + active = (continuous > 0) & (p > 0) & (atom != y) + values += np.where(active, continuous * (p * cross), 0) + # The error scale includes both operands of the cross-term subtraction. + scale += np.where( + active, continuous * (p * (y_scale + atom_scale + distance)), 0 + ) + for k in range(j): + # The point-point cross term is twice the overlap of the + # segments from y to each atom on the same side of y. + other = law.atoms[k] + overlap = np.maximum(np.maximum(other - y, y - atom), 0) + values += 2 * p * (masses[:, k] * overlap) + # Re-evaluate cancellation-prone rows through the independent quadrature. + # The allowance is absolute before comparing it with the size of the score. + bad = ( + ~np.isfinite(values) + | ~np.isfinite(scale) + | (32 * np.finfo(float).eps * scale > 1e-10 * values) + ) + if type(base) is StudentTLaw: + bad |= parameters["df"] != 1 + return values, np.flatnonzero(bad) + + def _crps(distribution, y): if type(distribution.law) is NormalLaw: loc = distribution.parameters["loc"] @@ -270,6 +368,11 @@ def _crps(distribution, y): spread = np.sqrt(2 / np.pi) * np.exp(-0.5 * z**2) - 1 / np.sqrt(np.pi) values = delta * tilt + sd * spread values[wide] = sd[wide] * (z[wide] * tilt[wide] + spread[wide]) + if not np.isfinite(values).all(): + count = np.count_nonzero(~np.isfinite(values)) + raise ArithmeticError( + f"Normal CRPS exceeds float precision on {count} row(s)." + ) return values required = {"quantile", "cdf"} if distribution.spec.response_kind == "mixed": @@ -288,14 +391,33 @@ def _crps(distribution, y): raise NotImplementedError( f"{distribution.spec.name} CRPS requires {sorted(missing)}." ) - values = np.empty(len(y)) - for i in range(len(y)): + law = distribution.law + base = law.base if type(law) is AtomMixtureLaw else law + if type(base) in (NormalLaw, GammaLaw) or ( + type(base) is StudentTLaw and np.any(distribution.parameters["df"] == 1) + ): + with np.errstate(over="ignore", invalid="ignore", divide="ignore"): + values, pending = _closed_crps(law, distribution.parameters, y) + else: + values, pending = np.empty(len(y)), range(len(y)) + errors = {} + for i in pending: row = DistributionPrediction( distribution.law, {k: v[i : i + 1] for k, v in distribution.parameters.items()}, context={k: v[i : i + 1] for k, v in distribution.context.items()}, ) - values[i] = _count_crps(row, y[i]) if counts else _quantile_crps(row, y[i]) + try: + values[i] = _count_crps(row, y[i]) if counts else _quantile_crps(row, y[i]) + except ArithmeticError as error: + reason = str(error) + errors[reason] = errors.get(reason, 0) + 1 + if errors: + count = sum(errors.values()) + details = "; ".join(f"{reason} ({n})" for reason, n in errors.items()) + raise ArithmeticError( + f"crps unavailable on {count} observed row(s): {details}." + ) return values @@ -318,8 +440,16 @@ def proper_scores(distribution, y, *, scores=_SCORES, tau=0.5, alpha=0.1): Returns ------- dict of str to ndarray - Read-only score vectors. Smaller values favor the forecast. A nonfinite - score on an observed row gives positive infinity. + Read-only score vectors. Smaller values favor the forecast. Infinite + losses retain their signs, including minus infinity at a density pole. + + Raises + ------ + ValueError + If a score evaluates to NaN on observed rows with valid predictions. + The error identifies the score and the number of such rows. + ArithmeticError + If a numerical CRPS cannot be resolved with a valid tail bound. Notes ----- @@ -327,12 +457,15 @@ def proper_scores(distribution, y, *, scores=_SCORES, tau=0.5, alpha=0.1): by 1-tau and underprediction by tau. Interval score adds 2/alpha times the distance outside the central interval to its width. - CRPS uses the finite-first-absolute-moment domain of the energy formula. - A law reporting an undefined first moment (e.g., Student-t with df <= 1) - receives positive infinity. Normal CRPS uses its exact Gaussian expression. - Supplied count laws integrate CDF steps (up to 100,000). Other discrete - laws enumerate up to 10,000 quantile plateaus. For continuous and mixed - laws, CRPS integrates twice the pinball loss in probability space. + The defining integral for CRPS uses the squared difference between the + predictive CDF and the observation's step function. For Student-t laws it + diverges for df <= 1/2 (positive infinity). For 1/2 < df < 1 it is finite + but unavailable here because the numerical method needs a tail bound. + Normal, Gamma, Cauchy and fixed-atom mixtures of these bases have analytic + scores. Supplied count laws integrate at most 100,000 CDF steps. Exceeding + that budget on any row makes the requested CRPS vector unavailable. Other + discrete laws enumerate up to 10,000 quantile plateaus. The numerical + fallback integrates twice the pinball loss in probability space. Estimated quadrature error, a first-moment bound on omitted tails and a quantile rounding allowance must together be within 1e-8 relative to the score, otherwise an ArithmeticError is raised. Declared atoms provide @@ -345,7 +478,9 @@ def proper_scores(distribution, y, *, scores=_SCORES, tau=0.5, alpha=0.1): Matheson and Winkler (1976), Scoring Rules for Continuous Probability Distributions. Gneiting and Raftery (2007), Strictly Proper Scoring Rules, Prediction, and Estimation. Jordan, Krüger and Lerch (2019), Evaluating - Probabilistic Forecasts with scoringRules. + Probabilistic Forecasts with scoringRules. Scheuerer and Möller (2015), + Probabilistic wind speed forecasting on a grid based on ensemble model + output statistics. """ names = _score_options(scores, tau, alpha) y = _vector(y, distribution.n_rows, "y") @@ -375,7 +510,10 @@ def proper_scores(distribution, y, *, scores=_SCORES, tau=0.5, alpha=0.1): distance = np.maximum(lo - y, 0) + np.maximum(y - hi, 0) value = (hi - lo) + 2 * distance / alpha aligned = np.full(valid.shape, np.nan) - aligned[valid] = np.where(np.isfinite(value), value, np.inf) + undefined = np.count_nonzero(np.isnan(value)) + if undefined: + raise ValueError(f"{name} score is NaN on {undefined} observed row(s).") + aligned[valid] = value aligned.setflags(write=False) result[name] = aligned return result diff --git a/nampy/models/comparison.py b/nampy/models/comparison.py index b0fa3713..83e63aae 100644 --- a/nampy/models/comparison.py +++ b/nampy/models/comparison.py @@ -18,7 +18,7 @@ centile_calibration, centile_probabilities, ) -from ..diagnostics.paired import paired_score_difference +from ..diagnostics.paired import _require_finite_losses, paired_score_difference from ..diagnostics.scores import _score_options, proper_scores from ..distributions.prediction import DistributionPrediction @@ -165,16 +165,22 @@ def score_differences( if baseline is None: raise ValueError(f"Unknown reference candidate: {reference!r}.") - def losses(row): - if score == "log" and row.status in {"ok", "incompatible_measure"}: + def losses(row, side): + if score == "log" and row.log_prob is not None: return -row.log_prob if score in row.score_errors: - raise ValueError(row.score_errors[score]) + raise ValueError(f"{side} {row.name!r}: {row.score_errors[score]}") if score in row.scores: return row.scores[score] - raise ValueError(row.failure_reason or row.status) + raise ValueError(f"{side} {row.name!r}: {row.failure_reason or row.status}") - reference_loss = losses(baseline) + reference_loss = losses(baseline, "reference") + active = ( + slice(None) + if self.validation_weight is None + else self.validation_weight > 0 + ) + _require_finite_losses(reference=reference_loss[active]) options = { "weights": self.validation_weight, "level": level, @@ -201,7 +207,9 @@ def losses(row): result = ( self_difference if row is baseline - else paired_score_difference(losses(row), reference_loss, **options) + else paired_score_difference( + losses(row, "candidate"), reference_loss, **options + ) ) record.update(asdict(result), reason=None) except ValueError as error: @@ -471,6 +479,24 @@ def compare_distributions( distribution.log_prob(valid_y), dtype=float, copy=True ) selected = log_prob[active] + if "log" in requested: + # Preserve the sign at density poles even when the + # original likelihood ranking marks the fit ineligible. + predicted = ~np.isnan( + distribution.parameters[ + distribution.spec.parameter_names[0] + ] + ) + undefined = np.count_nonzero( + active & predicted & np.isnan(log_prob) + ) + if undefined: + score_errors["log"] = ( + f"log score is NaN on {undefined} observed row(s)." + ) + else: + row_scores["log"] = np.where(active, -log_prob, np.nan) + row_scores["log"].setflags(write=False) n_scored = int(np.sum(~np.isnan(selected) & ~np.isposinf(selected))) n_zero = int(np.isneginf(selected).sum()) if n_scored != n_active: @@ -479,9 +505,6 @@ def compare_distributions( ) score = -np.inf if n_zero else float(np.sum(normalized * selected)) status = "ok" - if "log" in requested: - row_scores["log"] = np.where(active, -log_prob, np.nan) - row_scores["log"].setflags(write=False) if probabilities is not None: if {"cdf", "quantile"} <= distribution.spec.operations: try: diff --git a/tests/public_api/test_closed_form_crps.py b/tests/public_api/test_closed_form_crps.py new file mode 100644 index 00000000..d987bd78 --- /dev/null +++ b/tests/public_api/test_closed_form_crps.py @@ -0,0 +1,93 @@ +"""Gamma and atom-mixture energy formulas against separate CRPS integrals.""" + +import mpmath as mp +import numpy as np +import pytest +from numpy.testing import assert_allclose +from scipy.integrate import quad +from scipy.special import gammainc, gammaincc + +from nampy.diagnostics import proper_scores +from nampy.diagnostics.scores import _quantile_crps +from nampy.distributions import ( + AtomMixtureLaw, + DistributionPrediction, + GammaLaw, + NormalLaw, +) + + +@pytest.mark.parametrize("kind", ["gamma", "gamma_atoms", "normal_atoms"]) +def test_vectorized_crps_agrees_with_quantile_quadrature(kind): + rng = np.random.default_rng(45) + n = 18 + y = rng.uniform(-1, 4, n) + y[:4] = [0, -0.4, 1.5, 0] + if kind == "normal_atoms": + law = NormalLaw() + parameters = {"loc": rng.normal(size=n), "scale": np.exp(rng.uniform(-2, 2, n))} + else: + law = GammaLaw() + shape = np.exp(rng.uniform(-2.5, 4, n)) + shape[:5] = [0.01, 0.5, 1000, 0.01, 8832.9] + rate = shape / np.exp(rng.uniform(-1.2, 1.2, n)) + y[4] = shape[4] / rate[4] + parameters = {"shape": shape, "rate": rate} + if kind.endswith("atoms"): + law = AtomMixtureLaw(law, (0.0, 1.5), ("p0", "p1"), continuous_mass_name="pc") + masses = rng.dirichlet([1.5, 1, 2], size=n) + masses[3] = [1, 0, 0] + parameters.update(zip(("p0", "p1", "pc"), masses.T, strict=True)) + values = proper_scores(DistributionPrediction(law, parameters), y, scores="crps")[ + "crps" + ] + reference = [] + for i, observation in enumerate(y): + row = DistributionPrediction( + law, {k: v[i : i + 1] for k, v in parameters.items()} + ) + reference.append(_quantile_crps(row, observation)) + assert_allclose(values, reference, rtol=1e-10, atol=0) + + +def test_zero_adjusted_gamma_against_direct_cdf_integral(): + # Integrate the square of F below y and the square of the survival above y + # independently, splitting at the atom. No quantiles or energy formula. + law = AtomMixtureLaw(GammaLaw(), (0.0,), ("p0",)) + y = np.array([0.0, -1.0, 1.3, 5.1]) + a = np.array([0.5, 1.5, 2.0, 15.0]) + b = np.array([0.5, 0.1, 1.7, 2.2]) + p = np.array([0.4, 0.7, 0.1, 0.2]) + prediction = DistributionPrediction(law, {"shape": a, "rate": b, "p0": p}) + + def from_cdf(yi, ai, bi, pi): + cut = max(0.0, yi) + left = quad(lambda t: (pi + (1 - pi) * gammainc(ai, bi * t)) ** 2, 0, cut)[0] + right = quad(lambda t: ((1 - pi) * gammaincc(ai, bi * t)) ** 2, cut, np.inf)[0] + return max(-yi, 0) + left + right + + reference = [from_cdf(*row) for row in zip(y, a, b, p, strict=True)] + assert_allclose( + proper_scores(prediction, y, scores="crps")["crps"], reference, rtol=1e-10 + ) + + +def test_gamma_cancellation_at_zero_uses_accurate_fallback(): + # At y=0 both terms of the energy identity approach the mean as shape -> 0. + shape = 1e-5 + d = DistributionPrediction(GammaLaw(), {"shape": [shape], "rate": [1.0]}) + with mp.workdps(50): + reference = float(mp.mpf(shape) - 1 / mp.beta(0.5, shape)) + assert_allclose(proper_scores(d, [0], scores="crps")["crps"], reference, rtol=1e-10) + + +def test_gamma_atom_retains_tiny_explicit_continuous_mass(): + # F differs from the point mass only through its survival above zero. + law = AtomMixtureLaw(GammaLaw(), (0.0,), ("p0",), continuous_mass_name="pc") + pc = 1e-18 + d = DistributionPrediction( + law, {"shape": [1.0], "rate": [3.0], "p0": [1.0], "pc": [pc]} + ) + assert_allclose( + proper_scores(d, [0], scores="crps")["crps"], [pc**2 / 6], rtol=1e-12, atol=0 + ) diff --git a/tests/public_api/test_distribution_comparison.py b/tests/public_api/test_distribution_comparison.py index ae533340..33f5f527 100644 --- a/tests/public_api/test_distribution_comparison.py +++ b/tests/public_api/test_distribution_comparison.py @@ -17,6 +17,7 @@ GammaLaw, NegativeBinomialLaw, NormalLaw, + StudentTLaw, ) from nampy.models import DistributionCandidate, compare_distributions @@ -87,6 +88,11 @@ def predict_distribution(self, X, **kwargs): if self.behavior == "raise_predict": raise RuntimeError("prediction failed deliberately") n = len(X) - int(self.behavior == "omit") + if self.kind == "heavy_t": + return DistributionPrediction( + StudentTLaw(), + {"df": np.full(n, 0.9), "loc": np.zeros(n), "scale": np.ones(n)}, + ) if self.kind == "gamma": return DistributionPrediction( GammaLaw(), {"shape": np.full(n, 2.0), "rate": np.ones(n)} @@ -290,6 +296,34 @@ def test_positive_infinite_log_density_is_ineligible(): assert "NaN/+inf" in result.results[1].failure_reason +def test_pair_and_candidate_errors_identify_unavailable_rows(): + result = compare_distributions( + { + "good": _Candidate(), + "singular": _Candidate(kind="infinite"), + "heavy": _Candidate(kind="heavy_t"), + }, + *_inputs(), + scores=("log", "crps"), + validation_weight=[0, 2, 1], + ) + singular = result.results[1] + assert np.isneginf(singular.scores["log"][1:]).all() + log = result.score_differences("good", "log").set_index("candidate") + assert ( + "candidate loss is not finite on 2 positive-weight" + in log.loc["singular", "reason"] + ) + with pytest.raises( + ValueError, match="reference loss is not finite on 2 positive-weight" + ): + result.score_differences("singular", "log") + assert "crps unavailable on 2 observed" in result.results[2].score_errors["crps"] + crps = result.score_differences("good", "crps").set_index("candidate") + assert "candidate 'heavy'" in crps.loc["heavy", "reason"] + assert "crps unavailable on 2 observed" in crps.loc["heavy", "reason"] + + def test_diagnostic_failure_does_not_change_likelihood_eligibility_or_hide_warnings(): result = compare_distributions( {"diagnostic": _Candidate(kind="bad_calibration")}, *_inputs() diff --git a/tests/public_api/test_paired_score_difference.py b/tests/public_api/test_paired_score_difference.py index e984c587..98f60487 100644 --- a/tests/public_api/test_paired_score_difference.py +++ b/tests/public_api/test_paired_score_difference.py @@ -41,6 +41,16 @@ def test_paired_inference_retains_small_differences_among_large_values(): assert result.lower == pytest.approx(0.1) +def test_unavailable_pair_reports_the_count_for_each_side_on_positive_weight_rows(): + with pytest.raises( + ValueError, + match=r"candidate loss.*2 positive-weight.*reference loss.*1 positive-weight", + ): + paired_score_difference( + [np.nan, -np.inf, 3, np.inf], [0, np.inf, 2, np.nan], weights=[1, 1, 1, 0] + ) + + @pytest.mark.parametrize( "options", [ diff --git a/tests/public_api/test_proper_scores.py b/tests/public_api/test_proper_scores.py index 800427b7..4923448a 100644 --- a/tests/public_api/test_proper_scores.py +++ b/tests/public_api/test_proper_scores.py @@ -247,14 +247,79 @@ def test_scores_at_interval_endpoints_tails_and_missing_rows_are_read_only(): assert not values.flags.writeable -def test_no_first_moment_policy_is_rowwise_and_only_affects_crps(): +@pytest.mark.parametrize( + "law,params", + [ + (GammaLaw(), {"shape": 0.5, "rate": 1}), + (BetaLaw(), {"alpha": 0.5, "beta": 0.5}), + (WeibullLaw(), {"shape": 0.5, "scale": 1}), + ], +) +def test_log_loss_keeps_opposite_signs_at_a_density_pole_and_outside_support( + law, params +): + predicted = _prediction(law, params, n=2) + assert_array_equal( + proper_scores(predicted, [0, -1], scores="log")["log"], [-np.inf, np.inf] + ) + + +def test_undefined_score_counts_only_observed_rows_with_predictions(): + class UndefinedLog(NormalLaw): + def evaluate(self, operation, parameters, **kwargs): + return np.where(parameters["loc"] == 0, np.nan, 0.0) + + predicted = DistributionPrediction( + UndefinedLog(), {"loc": [0, np.nan, 1, 0, 0], "scale": [1, np.nan, 1, 1, 1]} + ) + with pytest.raises(ValueError, match="log score is NaN on 2 observed"): + proper_scores(predicted, [0, 0, 0, 0, np.nan], scores="log") + + +def test_student_tail_convergence_and_unavailable_bounds_are_distinguished(): prediction = DistributionPrediction( - StudentTLaw(), {"df": [0.6, 1.0, 1.3], "loc": [0.0] * 3, "scale": [1.0] * 3} + StudentTLaw(), {"df": [0.6, 0.9, 1.3], "loc": [0.0] * 3, "scale": [1.0] * 3} + ) + with pytest.raises(ArithmeticError, match="crps unavailable on 2 observed.*tail"): + _crps(prediction, np.zeros(3)) + scores = proper_scores( + prediction, np.zeros(3), scores=("log", "quantile", "interval") ) - scores = proper_scores(prediction, np.zeros(3)) - assert_array_equal(np.isposinf(scores["crps"]), [True, True, False]) for key in ("log", "quantile", "interval"): assert np.isfinite(scores[key]).all() + divergent = DistributionPrediction( + StudentTLaw(), {"df": [0.25, 0.5], "loc": [0, 0], "scale": [1, 1]} + ) + assert np.isposinf(_crps(divergent, [0, 2])).all() + + +def test_cauchy_integral_is_finite_without_a_first_moment(): + y = np.array([0.0, 2.0, -2.0]) + pred = _prediction(StudentTLaw(), {"df": 1, "loc": 0, "scale": 1}, n=len(y)) + oracle = [_crps_integral(stats.cauchy.cdf, stats.cauchy.sf, t, [0]) for t in y] + assert_allclose( + oracle, [2 * np.log(2) / np.pi, 1.33863673, 1.33863673], atol=5e-9, rtol=0 + ) + assert_allclose(_crps(pred, y), oracle, rtol=2e-13) + + +def test_atom_cauchy_mixture_against_squared_cdf_integrals(): + rv = stats.cauchy(loc=2, scale=3) + y = [0.0, -5.0, 7.0] + pred = _prediction( + AtomMixtureLaw(StudentTLaw(), (0.0,), ("p",)), + {"df": 1, "loc": 2, "scale": 3, "p": 0.43}, + n=len(y), + ) + + def cdf(x): + return 0.57 * rv.cdf(x) + 0.43 * (x >= 0) + + def sf(x): + return 0.57 * rv.sf(x) + 0.43 * (x < 0) + + oracle = [_crps_integral(cdf, sf, t, [0]) for t in y] + assert_allclose(_crps(pred, y), oracle, rtol=2e-13) def test_moment_restriction_applies_to_the_predictive_law_after_composition():