API: metrics and tests¶
metrics
¶
Calibration metrics and statistical tests (flat re-exports).
Implementation lives in the submodules (scores, binned, smooth,
regression, kernel, grade) and in private helpers
(_evaluate, _summary, _binstats, _grades, _common).
The sample-weight convention shared by every metric is documented in
:mod:probcal.metrics._common. Selection guidance — what may be optimized
and what is report-only — is the table in docs/concepts/metrics.md.
GroupedMetricReport
dataclass
¶
GroupedMetricReport(pooled: MetricReport, groups: tuple[str, ...], reports: tuple[MetricReport, ...], counts: ndarray)
Bases: _ResultBase
Per-group metric reports plus a pooled report, from metrics.evaluate(by=...).
| ATTRIBUTE | DESCRIPTION |
|---|---|
pooled |
Report computed on the full, ungrouped data (the
TYPE:
|
groups |
Sorted, stringified group labels.
TYPE:
|
reports |
Per-group reports, aligned with
TYPE:
|
counts |
Observation count per group, aligned with
TYPE:
|
to_frame
¶
to_frame() -> object
Rows as a list of dicts, or a pandas DataFrame when pandas is importable.
Each row is {"group", "metric", "value", "ci_low", "ci_high"};
the pooled report is included under the group label "pooled",
which is therefore reserved — a group of your own named "pooled"
is indistinguishable from it in this frame.
Source code in src/probcal/_results.py
256 257 258 259 260 261 262 263 264 265 266 267 268 269 | |
ReliabilitySummary
dataclass
¶
ReliabilitySummary(n: int, events: int, intercept: float, slope: float, ici: float, e90: float, spiegelhalter_p: float)
Stats-box aggregate for the annotated reliability diagram.
| ATTRIBUTE | DESCRIPTION |
|---|---|
n |
Observation count.
TYPE:
|
events |
Event count (
TYPE:
|
intercept |
Calibration-in-the-large intercept (log-odds).
TYPE:
|
slope |
Cox calibration slope.
TYPE:
|
ici |
Integrated calibration index.
TYPE:
|
e90 |
90th percentile of the LOESS distances.
TYPE:
|
spiegelhalter_p |
Spiegelhalter test p-value.
TYPE:
|
HosmerLemeshowResult
dataclass
¶
HosmerLemeshowResult(statistic: float, df: int, p_value: float)
Hosmer–Lemeshow chi-square test (report-only; never a selection criterion).
| ATTRIBUTE | DESCRIPTION |
|---|---|
statistic |
Chi-square test statistic.
TYPE:
|
df |
Degrees of freedom: non-empty groups minus
TYPE:
|
p_value |
Upper-tail p-value of the statistic;
TYPE:
|
BinomialGradeResult
dataclass
¶
BinomialGradeResult(grades: tuple, n: ndarray, k: ndarray, pd: ndarray, p_exact: ndarray, p_normal: ndarray, light: tuple, ci_low: ndarray, ci_high: ndarray)
Bases: _ResultBase
Exact and approximate one-sided binomial backtest per rating grade.
| ATTRIBUTE | DESCRIPTION |
|---|---|
grades |
Grade labels: the
TYPE:
|
n |
Observation count per grade.
TYPE:
|
k |
Default count per grade.
TYPE:
|
pd |
Assigned PD per grade (mean of
TYPE:
|
p_exact |
Exact binomial tail p-value per grade (also available as
:attr:
TYPE:
|
p_normal |
Normal-approximation p-value per grade.
TYPE:
|
light |
Traffic light per grade (
TYPE:
|
ci_low, ci_high |
90% Clopper-Pearson display interval for the observed rate.
TYPE:
|
p_value
property
¶
p_value: ndarray
Alias of :attr:p_exact (the exact test decides the traffic light).
HlEResult
dataclass
¶
HlEResult(e_value: float, p_value: float, grades: tuple[str, ...], e_grade: ndarray, construction: str)
Bases: _ResultBase
Mixture-LR grade e-test result (:func:hl_e_test).
| ATTRIBUTE | DESCRIPTION |
|---|---|
e_value |
The test e-value,
TYPE:
|
p_value |
TYPE:
|
grades |
Grade labels: best to worst for a
TYPE:
|
e_grade |
Per-grade e-value, aligned with
TYPE:
|
construction |
Always
TYPE:
|
Examples:
>>> import numpy as np
>>> from probcal.metrics import hl_e_test
>>> rng = np.random.default_rng(0)
>>> p = np.full(200, 0.1)
>>> y = (rng.random(200) < 0.1).astype(float)
>>> grades = np.array(["A"] * 100 + ["B"] * 100)
>>> res = hl_e_test(y, p, grades)
>>> res.construction
'mixture-lr'
>>> bool(np.isclose(res.e_value, np.prod(res.e_grade), rtol=1e-9))
True
>>> res.p_value == min(1.0, 1.0 / res.e_value)
True
interpret
¶
interpret() -> Interpretation
Read one e-value sentence per grade and the test-level conclusion.
| RETURNS | DESCRIPTION |
|---|---|
Interpretation
|
|
Examples:
>>> import numpy as np
>>> from probcal.metrics import hl_e_test
>>> rng = np.random.default_rng(0)
>>> p = np.full(200, 0.1)
>>> y = (rng.random(200) < 0.1).astype(float)
>>> grades = np.array(["A"] * 100 + ["B"] * 100)
>>> interp = hl_e_test(y, p, grades).interpret()
>>> interp.method
'HlETest'
>>> "grade A: e =" in interp.messages[0]
True
Source code in src/probcal/metrics/_safe.py
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
JeffreysGradeResult
dataclass
¶
JeffreysGradeResult(grades: tuple, n: ndarray, k: ndarray, pd: ndarray, p_value: ndarray, light: tuple, ci_low: ndarray, ci_high: ndarray)
Bases: _ResultBase
Jeffreys-posterior backtest per rating grade (ECB IRB practice).
| ATTRIBUTE | DESCRIPTION |
|---|---|
grades |
Grade labels: the
TYPE:
|
n |
Observation count per grade.
TYPE:
|
k |
Default count per grade.
TYPE:
|
pd |
Assigned PD per grade (mean of
TYPE:
|
p_value |
Posterior
TYPE:
|
light |
Traffic light per grade (
TYPE:
|
ci_low, ci_high |
Central 90% Jeffreys posterior display interval.
TYPE:
|
PlutoTascheResult
dataclass
¶
PlutoTascheResult(grades: tuple[str, ...], n: ndarray, d: ndarray, n_pooled: ndarray, d_pooled: ndarray, pd_upper: ndarray, confidence: float, monotonized: bool)
Bases: _ResultBase
Pluto-Tasche one-period most-prudent PD per rating grade.
| ATTRIBUTE | DESCRIPTION |
|---|---|
grades |
Grade labels, best to worst, in the order given to
:func:
TYPE:
|
n |
Own obligor count per grade (weighted sum if fitted from arrays with
TYPE:
|
d |
Own default count per grade (weighted sum likewise).
TYPE:
|
n_pooled |
Obligor count pooled with all worse grades:
TYPE:
|
d_pooled |
Default count pooled the same way.
TYPE:
|
pd_upper |
Most-prudent PD per grade: the one-sided Clopper-Pearson upper bound
of the pooled default rate at
TYPE:
|
confidence |
Confidence level used for every grade's bound.
TYPE:
|
monotonized |
TYPE:
|
interpret
¶
interpret() -> Interpretation
Read one audit sentence per grade: own counts, pooling, and the bound.
| RETURNS | DESCRIPTION |
|---|---|
Interpretation
|
|
Examples:
>>> import numpy as np
>>> from probcal.metrics import pluto_tasche
>>> res = pluto_tasche(
... np.array([100.0, 400.0, 300.0]),
... np.array([0.0, 0.0, 0.0]),
... confidence=0.9,
... grades=("A", "B", "C"),
... )
>>> msg = res.interpret().messages[0]
>>> "grade A: 0 defaults among 100 obligors" in msg
True
>>> "most-prudent PD at 90% confidence = 0.29%" in msg
True
Source code in src/probcal/metrics/_conservative.py
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | |
SkceTestResult
dataclass
¶
SkceTestResult(statistic: float, estimator: str, method: str, p_value: float, p_value_bound: float, bandwidth: float, n_boot: int | None)
One-sided SKCE calibration test (H0: calibrated; large positive rejects).
| ATTRIBUTE | DESCRIPTION |
|---|---|
statistic |
SKCE point estimate (
TYPE:
|
estimator |
Estimator used for
TYPE:
|
method |
Test method used (
TYPE:
|
p_value |
Test p-value.
TYPE:
|
p_value_bound |
Distribution-free worst-case p-value bound (valid without asymptotics).
TYPE:
|
bandwidth |
Kernel bandwidth used (resolved from
TYPE:
|
n_boot |
Bootstrap replicate count for the bootstrap method;
TYPE:
|
CalibrationTestResult
dataclass
¶
CalibrationTestResult(statistic: float, p_value: float, alpha: float, beta: float, df: float = 2.0)
Likelihood-ratio test of (intercept, slope) = (0, 1) — the Cox-framed weak calibration test.
| ATTRIBUTE | DESCRIPTION |
|---|---|
statistic |
Likelihood-ratio test statistic, referred to
TYPE:
|
p_value |
Upper-tail p-value of the statistic.
TYPE:
|
alpha |
Fitted intercept (also available as :attr:
TYPE:
|
beta |
Fitted slope (also available as :attr:
TYPE:
|
df |
Degrees of freedom of the reference chi-square:
TYPE:
|
GuardrailReport
dataclass
¶
GuardrailReport(slope: float, intercept: float, spiegelhalter_p: float, slope_ok: bool, intercept_ok: bool, spiegelhalter_ok: bool, all_ok: bool)
Three-flag calibration health summary used across the package.
Thresholds are conventions, not theorems: slope within [0.9, 1.1], intercept within +/-0.1 log-odds, Spiegelhalter p above 0.05.
| ATTRIBUTE | DESCRIPTION |
|---|---|
slope |
Fitted Cox calibration slope.
TYPE:
|
intercept |
Fitted calibration-in-the-large intercept (log-odds).
TYPE:
|
spiegelhalter_p |
Spiegelhalter test p-value.
TYPE:
|
slope_ok |
Whether
TYPE:
|
intercept_ok |
Whether
TYPE:
|
spiegelhalter_ok |
Whether
TYPE:
|
all_ok |
Conjunction of the three flags above.
TYPE:
|
LogLossDecomposition
dataclass
¶
LogLossDecomposition(calibration: float, refinement: float)
Calibration/refinement split of the log loss via a plug-in recalibration curve (LOESS).
| ATTRIBUTE | DESCRIPTION |
|---|---|
calibration |
Mean KL divergence between the plug-in and predicted Bernoullis.
TYPE:
|
refinement |
Mean entropy of the plug-in Bernoulli.
TYPE:
|
MurphyCurve
dataclass
¶
MurphyCurve(thresholds: ndarray, score: ndarray, n: int)
Bases: _ResultBase
Murphy diagram: mean elementary score of the binary mean functional across thresholds.
| ATTRIBUTE | DESCRIPTION |
|---|---|
thresholds |
Threshold grid :math:
TYPE:
|
score |
Weighted mean elementary score :math:
TYPE:
|
n |
Number of observations.
TYPE:
|
MurphyDecomposition
dataclass
¶
MurphyDecomposition(reliability: float, resolution: float, uncertainty: float)
Binned Murphy (1973) partition of the Brier score.
reliability - resolution + uncertainty equals the Brier score exactly
when predictions are constant within bins; otherwise the identity holds
up to the within-bin variance of p (documented binning bias).
| ATTRIBUTE | DESCRIPTION |
|---|---|
reliability |
Mean squared gap between within-bin predicted and observed rates.
TYPE:
|
resolution |
Mean squared gap between within-bin observed rate and the overall base rate.
TYPE:
|
uncertainty |
Base-rate variance
TYPE:
|
EcceResult
dataclass
¶
EcceResult(stat_max: float, stat_mean: float)
Empirical cumulative calibration error: Kolmogorov-style max and mean of the cumulative deviation over sorted predictions.
| ATTRIBUTE | DESCRIPTION |
|---|---|
stat_max |
Maximum absolute cumulative deviation.
TYPE:
|
stat_mean |
Weighted mean absolute cumulative deviation (each tied-score block weighted by its total sample weight).
TYPE:
|
SpiegelhalterResult
dataclass
¶
SpiegelhalterResult(z: float, p_value: float)
Spiegelhalter's z test of forecast unbiasedness (two-sided).
| ATTRIBUTE | DESCRIPTION |
|---|---|
z |
Standardized test statistic (
TYPE:
|
p_value |
Two-sided p-value under the standard normal approximation (
TYPE:
|
evaluate
¶
evaluate(y: object, p: object, *, sample_weight: object = None, n_boot: int = 1000, random_state: int = 42, metrics: Sequence[str] | None = None, stratify: bool = True, by: None = None) -> MetricReport
evaluate(y: object, p: object, *, sample_weight: object = None, n_boot: int = 1000, random_state: int = 42, metrics: Sequence[str] | None = None, stratify: bool = True, by: object) -> GroupedMetricReport
evaluate(y: object, p: object, *, sample_weight: object = None, n_boot: int = 1000, random_state: int = 42, metrics: Sequence[str] | None = None, stratify: bool = True, by: object = None) -> MetricReport | GroupedMetricReport
Full metric report with seeded bootstrap percentile confidence intervals.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Outcomes and predicted probabilities.
TYPE:
|
p
|
Outcomes and predicted probabilities.
TYPE:
|
sample_weight
|
Positive observation weights (resampled together with the
observations); see the weight convention in
:mod:
TYPE:
|
n_boot
|
Case-resampling bootstrap replicates (percentile CIs at 2.5/97.5).
TYPE:
|
random_state
|
RNG seed; results are bit-reproducible given the seed.
TYPE:
|
metrics
|
Subset of catalog names to compute;
TYPE:
|
stratify
|
If
TYPE:
|
by
|
Optional group labels, one per observation (same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MetricReport or GroupedMetricReport
|
Point estimates and CI bounds for the requested catalog
( |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
RuntimeError
|
If |
Notes
Every metric is recomputed n_boot times; for n > 1e6 reduce
n_boot or pass a metrics= subset (the ICI family's LOESS fit is
the largest single cost). With by given, the cost is paid once per
group plus once for the pooled report. Each replicate is sorted by
prediction once, and the LOESS fit and the ECCE walk reuse that order;
the point estimates always come off the unsorted path. The measured cost
table lives in docs/concepts/metrics.md.
Examples:
>>> import numpy as np
>>> from probcal.metrics import evaluate
>>> rng = np.random.default_rng(0)
>>> p = rng.uniform(0.05, 0.5, 300)
>>> y = (rng.random(300) < p).astype(float)
>>> segment = np.where(p < 0.2, "low", "high")
>>> grouped = evaluate(y, p, n_boot=50, metrics=("brier",), by=segment)
>>> grouped.groups
('high', 'low')
>>> len(grouped.reports) == len(grouped.groups)
True
Source code in src/probcal/metrics/_evaluate.py
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | |
reliability_summary
¶
reliability_summary(y: object, p: object, *, sample_weight: object = None, grid_size: int | None = 512) -> ReliabilitySummary
Assemble the annotated-reliability stats box from existing metrics.
No new math: intercept and slope from the recalibration regression, ICI
and E90 from the LOESS distance family, and Spiegelhalter's p-value.
Lives here because, like evaluate, it aggregates across submodules;
probcal.plots only formats the result. grid_size=None fits the
LOESS exactly at every prediction.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
grid_size
|
LOESS evaluation grid size for the ICI/E90 terms;
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ReliabilitySummary
|
Stats-box fields for the annotated reliability diagram. |
Source code in src/probcal/metrics/_summary.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | |
ece
¶
ece(y: object, p: object, *, n_bins: int = 15, strategy: str = 'mass', norm: str = 'l1', sample_weight: object = None) -> float
Expected calibration error; norm="max" gives the MCE.
Binning-sensitive and upward-biased in finite samples — report, never select on it (see the metrics chapter's table).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
n_bins
|
Requested number of bins (positive integer).
TYPE:
|
strategy
|
TYPE:
|
norm
|
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Weighted binned calibration error under the chosen norm. |
Source code in src/probcal/metrics/binned.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | |
ece_debiased
¶
ece_debiased(y: object, p: object, *, n_bins: int = 15, strategy: str = 'mass', sample_weight: object = None) -> float
Bias-corrected ECE, floored at zero.
Per-bin squared gaps minus the within-bin variance of the event rate
(correction in the spirit of Bröcker 2009 / Ferro & Fricker 2012):
sqrt(max(gap_b**2 - rate_b * (1 - rate_b) / (n_b - 1), 0)) for bins
with n_b > 1. n_b is the bin's effective count
sum_b(w)**2 / sum_b(w**2) -- the size of an unweighted bin whose
event rate has the same variance -- so it follows the weights inside the
bin, and is the raw count for unit (or within-bin constant) weights.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
n_bins
|
Requested number of bins.
TYPE:
|
strategy
|
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Bias-corrected calibration error. |
Source code in src/probcal/metrics/binned.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
ece_sweep
¶
ece_sweep(y: object, p: object, *, norm: str = 'l1', sample_weight: object = None, max_bins: int = 100, rule: str = 'first_violation') -> float
Monotonic-sweep calibration error (Roelofs et al., 2022).
Equal-mass bins; the bin count is the largest b such that b and
every smaller bin count give non-decreasing bin event rates — the
paper's b* = max{b : for all b' <= b, ybar_1 <= ... <= ybar_b'}
(its Algorithm 1: sweep b = 2, 3, ... and stop at the first
non-monotone binning). The paper sweeps up to b = n; the sweep here
stops at max_bins (default 100) as a cost cap.
rule="largest" instead takes the largest monotone b anywhere in
2..max_bins, skipping over non-monotone counts.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
norm
|
Norm of the final binned error at the selected bin count.
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
max_bins
|
Upper end of the sweep (capped at
TYPE:
|
rule
|
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Calibration error at the selected bin count. |
Source code in src/probcal/metrics/binned.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | |
hosmer_lemeshow
¶
hosmer_lemeshow(y: object, p: object, *, n_bins: int = 10, sample_weight: object = None, ddof: int = 0) -> HosmerLemeshowResult
Hosmer–Lemeshow goodness-of-fit test on n_bins equal-mass risk groups.
The statistic depends on an essentially arbitrary grouping and its power scales with n — see the metrics chapter for why this is report-only.
Per group g, O_g = sum(w y) and E_g = sum(w p) are compared
against V_g = S_g * pt_g * (1 - pt_g), where S_g = sum(w**2) and
pt_g = sum(w**2 p) / S_g. V_g is the weighted form of the
classical n_g pbar_g (1 - pbar_g): it equals the exact null variance
sum(w**2 p (1 - p)) of O_g - E_g plus the same within-group
spread term sum(w**2 (p - pt_g)**2) the unweighted statistic carries.
The statistic is invariant to rescaling the weights, and unit weights
give the unweighted test bit for bit.
The reference distribution is chi-square on groups - ddof degrees of
freedom. With p fixed in advance (a model or calibrator fitted on
other data, the usual validation setting) the per-group standardized
residuals are asymptotically independent, so the statistic is
chi2(groups): ddof=0, the default (Hosmer, Lemeshow and
Sturdivant, 2013, on external validation). The classical groups - 2
is for a logistic model fitted on the same data; pass ddof=2 for it.
On out-of-sample p it is anti-conservative (about 12% rejections at
a nominal 5% with 10 groups).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
n_bins
|
Requested number of equal-mass risk groups. Tied scores can collapse
groups; when no more than
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
ddof
|
Degrees of freedom subtracted from the number of non-empty groups:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
HosmerLemeshowResult
|
Chi-square statistic, degrees of freedom, and p-value. |
Source code in src/probcal/metrics/binned.py
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | |
binomial_grade_test
¶
binomial_grade_test(y: object, p: object, grades: object, *, sample_weight: object = None, order: object = None) -> BinomialGradeResult
Exact binomial tail test per grade: P(X >= k | n, PD).
Small p-values flag grades with more defaults than the assigned PD
supports. The exact tail uses the incomplete-beta identity
P(X >= k) = I_PD(k, n - k + 1); the normal approximation is reported
alongside. Traffic lights: green > 0.05, amber > 0.01, red <= 0.01.
ci_low/ci_high are 90% Clopper-Pearson display intervals for the
observed rate; the traffic light itself remains the one-sided exact test,
unchanged.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities (assigned PDs) in
TYPE:
|
grades
|
Rating grade label per observation, or a :class:
TYPE:
|
sample_weight
|
Not used: grade tests use raw integer counts. A
TYPE:
|
order
|
Explicit grade order for the result (a permutation of the grade
labels present);
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BinomialGradeResult
|
Per-grade counts, p-values, traffic lights, and display intervals. |
Source code in src/probcal/metrics/grade.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | |
hl_e_test
¶
hl_e_test(y: object, p: object, grades: object, *, mixture_grid: tuple[float, ...] = (0.1, 0.25, 0.5, 1.0), sample_weight: object = None) -> HlEResult
Fixed-sample mixture-LR grade e-test (safe Hosmer-Lemeshow analogue).
For grade g, with z_i = logit(p_i):
log E_g = logsumexp_{delta in +/-mixture_grid}(sum_{i in g} log
LR_i(sigma(z_i + delta) : p_i)) - log(2 * len(mixture_grid))
i.e. the log-mean Bernoulli log-likelihood-ratio (probcal._math
.bern_log_lr) of the grade's observations, averaged over the
symmetrized offset grid -- the same mixture construction
CalibrationMonitor's offset e-process uses, applied once per grade
with no predictable (plug-in) component, since a fixed sample has no
strictly-earlier data to learn one from. The test statistic is the
product across grades, log E = sum_g log E_g, e_value = exp(log
E): grades partition the sample into disjoint observations, each
grade's mixture average is an e-value for that grade's null (an average
of e-values, each with conditional expectation 1 under H0), and the
product of e-values over independent (here: disjoint-observation)
factors is itself an e-value. p_value = min(1, 1 / e_value) follows
from Markov's inequality and is a valid (generally conservative)
p-value.
Sample weights, when given, enter as exponents min(1, w / mean(w))
(mean over the grade) on the Bernoulli factors, as in
CalibrationMonitor: every factor stays an e-value for any weights,
the test is invariant to rescaling the weights, and unit weights give
the unweighted test.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Assigned probabilities (the null) in
TYPE:
|
grades
|
Rating grade label per observation, or a :class:
TYPE:
|
mixture_grid
|
Positive logit-scale offsets; symmetrized to
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
HlEResult
|
Per-grade and combined e-values, the derived p-value, and the construction tag. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Examples:
>>> import numpy as np
>>> from probcal.metrics import hl_e_test
>>> rng = np.random.default_rng(1)
>>> p = np.full(400, 0.05)
>>> y = (rng.random(400) < 0.05).astype(float)
>>> grades = np.array(["A"] * 200 + ["B"] * 200)
>>> res = hl_e_test(y, p, grades)
>>> res.grades
('A', 'B')
>>> res.e_value > 0.0
True
Source code in src/probcal/metrics/_safe.py
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
jeffreys_grade_test
¶
jeffreys_grade_test(y: object, p: object, grades: object, *, sample_weight: object = None, order: object = None) -> JeffreysGradeResult
Jeffreys test per grade: posterior P(theta <= PD | k, n) under Beta(k+1/2, n-k+1/2).
One-sided and conservative by design: a small value flags a grade whose
PD is likely understated. Do not read it two-sided (a recurring
validation error — see the metrics chapter). ci_low/ci_high are
the central 90% Jeffreys posterior display intervals; the traffic light
itself remains the one-sided posterior test, unchanged.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities (assigned PDs) in
TYPE:
|
grades
|
Rating grade label per observation, or a :class:
TYPE:
|
sample_weight
|
Not used: grade tests use raw integer counts. A
TYPE:
|
order
|
Explicit grade order for the result (a permutation of the grade
labels present);
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
JeffreysGradeResult
|
Per-grade counts, p-values, traffic lights, and display intervals. |
Source code in src/probcal/metrics/grade.py
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 | |
jeffreys_upper_bands
¶
jeffreys_upper_bands(y: object, p: object, grades: object, *, confidence: float = 0.9, order: object = None) -> dict[str, tuple[float, float]]
Jeffreys per-grade upper bounds as a contiguous masterscale band table.
For grade i (best to worst, in order): hi_i is the same
one-sided Jeffreys posterior upper bound jeffreys_grade_test reports
as its own-grade display interval, beta_ppf(confidence, k_i + 0.5,
n_i - k_i + 0.5) under a Beta(k_i + 0.5, n_i - k_i + 0.5) posterior
on grade i's own default rate; lo_i is the previous grade's
hi (0.0 for the best grade), so the bands are contiguous by
construction: (lo_0, hi_0), (hi_0, hi_1), (hi_1, hi_2), .... Unlike
:func:pluto_tasche, each grade's bound uses only its own counts (no
pooling across grades), so a zero-default grade still gets a strictly
positive hi from the Jeffreys prior alone.
The raw hi sequence need not come out increasing (a noisy grade can
have a posterior upper bound no larger than a better grade's), which
would make the bands overlap or invert. The prudent hull of
:func:pluto_tasche -- the running maximum best to worst, which never
lowers any grade's bound -- fixes the order but would leave such a grade
a zero-width band (hi, hi) that no calibrated PD can fall into.
Instead, a grade whose own bound does not exceed the running maximum is
merged into the band before it: the merged band is keyed by the joined
labels ("A+B", best to worst), keeps the running-maximum hi (so
no grade's bound is ever lowered), and a UserWarning names the
merged grades. The data cannot order those grades at this confidence;
merging them (or collecting more data) is the decision the warning asks
for. Every returned band therefore has lo < hi, and the bands are
contiguous and strictly increasing. A size-weighted PAVA fit is not
used because it can lower a grade's upper bound.
The resulting {grade: (lo, hi)} table is exactly the shape
:func:probcal.thresholds.calibrated_bands_to_raw and
:class:probcal.Masterscale consume to translate a masterscale defined
on calibrated PD into raw-score intervals.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
grades
|
Rating grade label per observation, or a :class:
TYPE:
|
confidence
|
Confidence level in
TYPE:
|
order
|
Explicit best-to-worst grade order; must match the unique labels in
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, tuple[float, float]]
|
Mapping of grade label -- or |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Examples:
>>> import numpy as np
>>> from probcal.metrics import jeffreys_upper_bands
>>> grades = np.array(["A"] * 100 + ["B"] * 100)
>>> y = np.array([0.0] * 100 + [1.0] * 5 + [0.0] * 95)
>>> p = np.array([0.01] * 100 + [0.05] * 100)
>>> bands = jeffreys_upper_bands(y, p, grades, confidence=0.9)
>>> bands["A"][0]
0.0
>>> bands["A"][1] < bands["B"][1]
True
Source code in src/probcal/metrics/_conservative.py
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | |
pluto_tasche
¶
pluto_tasche(grade_n: object, grade_d: object, *, confidence: float = 0.9, grades: object = None) -> PlutoTascheResult
Pluto & Tasche (2005) one-period most-prudent PD, from per-grade counts.
For grade i (best to worst, in the order given), pool its own
obligors and defaults with every worse grade's: n*_i = sum(n[i:]),
d*_i = sum(d[i:]). The most-prudent PD is the one-sided
Clopper-Pearson upper bound of the pooled rate,
p solving I_p(d*_i + 1, n*_i - d*_i) = confidence
(beta_ppf(confidence, d*_i + 1, n*_i - d*_i)), i.e. the largest PD
under which observing at most d*_i defaults in n*_i obligors
still has probability >= 1 - confidence. Pooling with worse grades is the
rating-monotonicity assumption doing its work: a grade's own data alone
is often uninformative (frequently zero defaults), but the assumption
that its true PD cannot exceed a worse grade's lets that grade's
defaults bound this one.
| PARAMETER | DESCRIPTION |
|---|---|
grade_n
|
Obligor count per grade, best to worst. Non-integer (weighted) counts are accepted and pass directly into the Beta shape parameters below.
TYPE:
|
grade_d
|
Default count per grade, same order;
TYPE:
|
confidence
|
Confidence level in
TYPE:
|
grades
|
Grade labels, best to worst;
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PlutoTascheResult
|
Per-grade counts, pooled counts, and most-prudent PDs. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Examples:
>>> import numpy as np
>>> from probcal.metrics import pluto_tasche
>>> res = pluto_tasche(
... np.array([100.0, 400.0, 300.0]),
... np.array([0.0, 0.0, 0.0]),
... confidence=0.9,
... grades=("A", "B", "C"),
... )
>>> res.grades
('A', 'B', 'C')
>>> np.round(res.pd_upper, 4)
array([0.0029, 0.0033, 0.0076])
Source code in src/probcal/metrics/_conservative.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | |
pluto_tasche_from_arrays
¶
pluto_tasche_from_arrays(grades: object, y: object, *, order: object = None, p: object = None, confidence: float = 0.9, sample_weight: object = None) -> PlutoTascheResult
Pluto-Tasche most-prudent PD from observation-level grades and outcomes.
Convenience wrapper around :func:pluto_tasche: aggregates y by
grades into per-grade obligor/default counts (weighted sums when
sample_weight is given) in the explicit order, then applies the
same pooling and bound.
| PARAMETER | DESCRIPTION |
|---|---|
grades
|
Rating grade label per observation, or a :class:
TYPE:
|
y
|
Binary outcomes in
TYPE:
|
order
|
Explicit best-to-worst grade order; must match the unique labels in
TYPE:
|
p
|
Predicted probabilities, required when
TYPE:
|
confidence
|
Confidence level in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PlutoTascheResult
|
Per-grade counts, pooled counts, and most-prudent PDs. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Examples:
>>> import numpy as np
>>> from probcal.metrics import pluto_tasche_from_arrays
>>> grades = np.array(["A"] * 100 + ["B"] * 400 + ["C"] * 300)
>>> y = np.zeros(800)
>>> res = pluto_tasche_from_arrays(grades, y, order=("A", "B", "C"))
>>> res.n
array([100., 400., 300.])
Source code in src/probcal/metrics/_conservative.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | |
skce
¶
skce(y: object, p: object, *, estimator: str = 'uq', kernel: str = 'laplace', bandwidth: float | None = None, scale: str = 'probability', random_state: int = 42) -> float
Squared kernel calibration error (Widmann et al., 2019, Table 1).
"uq" (default) is the unbiased quadratic estimator (may be negative);
"ul" the unbiased linear O(n) estimator over seeded disjoint pairs
(random_state controls the pairing); "biased" the nonnegative
V-statistic. bandwidth=None uses the deterministic median heuristic;
scale="logit" transforms the kernel input only (the low-PD option).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
estimator
|
Estimator variant; see above.
TYPE:
|
kernel
|
Kernel family applied to the (scaled) score distance.
TYPE:
|
bandwidth
|
Kernel bandwidth;
TYPE:
|
scale
|
Scale on which the kernel input
TYPE:
|
random_state
|
Seed for the
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
SKCE point estimate. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/probcal/metrics/kernel.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | |
skce_test
¶
skce_test(y: object, p: object, *, method: str = 'bootstrap', n_boot: int = 999, kernel: str = 'laplace', bandwidth: float | None = None, scale: str = 'probability', random_state: int = 42) -> SkceTestResult
Calibration test on the SKCE (Widmann et al., 2019, Sec. 6 / App. G).
"bootstrap" (default): quadratic statistic with Arcones–Giné centered
resampling; O(n_boot * n^2) — the more powerful choice. "asymptotic":
linear statistic, normal approximation (Corollary G.3); O(n), preferred
for n >~ 20 000, but a single random pairing can miss slope-type
miscalibration that the bootstrap test rejects (the paper's documented
power gap). p_value_bound is the distribution-free worst case.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
method
|
Test method; see above.
TYPE:
|
n_boot
|
Bootstrap replicate count (
TYPE:
|
kernel
|
Kernel family applied to the (scaled) score distance.
TYPE:
|
bandwidth
|
Kernel bandwidth;
TYPE:
|
scale
|
Scale on which the kernel input
TYPE:
|
random_state
|
Seed for the resampling (
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SkceTestResult
|
Test statistic, method, p-value, and worst-case bound. |
Source code in src/probcal/metrics/kernel.py
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | |
calibration_guardrails
¶
calibration_guardrails(y: object, p: object, *, sample_weight: object = None) -> GuardrailReport
Evaluate the three guardrail flags.
Printed in selection reports and offset audit reports.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
GuardrailReport
|
Slope, intercept, and Spiegelhalter-p values with pass/fail flags. |
Source code in src/probcal/metrics/regression.py
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | |
calibration_intercept
¶
calibration_intercept(y: object, p: object, *, sample_weight: object = None) -> float
Calibration-in-the-large in log-odds.
Logistic intercept with the slope fixed at 1 (offset regression on logit(p)).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Fitted intercept in log-odds units. |
Source code in src/probcal/metrics/regression.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | |
calibration_slope
¶
calibration_slope(y: object, p: object, *, sample_weight: object = None) -> float
Cox calibration slope.
< 1 means overfitting/overconfident spread, > 1 underfitting.
When every prediction has the same logit(p) (a constant p, or a
single PD level) the slope is not identified and nan is returned
with a UserWarning.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Fitted slope on the logit scale ( |
Source code in src/probcal/metrics/regression.py
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | |
calibration_test
¶
calibration_test(y: object, p: object, *, sample_weight: object = None) -> CalibrationTestResult
Likelihood-ratio test of joint calibration (alpha, beta) = (0, 1).
With weights, the fit and the likelihood ratio use sample_weight as
given, and the weighted LR statistic -- distributed under calibration as
a weighted sum of chi2_1 variables, not as chi2_2 -- is referred
to a second-order Rao-Scott corrected chi-square
(:func:probcal.metrics._common.rao_scott; the design effects use the
exact null variance sum(w**2 p (1 - p) x x') of the weighted score).
The test is invariant to rescaling the weights, and unit (or constant)
weights give the plain 2-df likelihood-ratio test.
When every prediction has the same logit(p) the slope is not
identified: only calibration-in-the-large is tested (slope fixed at 1,
df = 1), beta is nan, and a UserWarning is emitted.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
CalibrationTestResult
|
Test statistic, p-value, and fitted intercept/slope. |
Source code in src/probcal/metrics/regression.py
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 | |
brier_score
¶
brier_score(y: object, p: object, *, sample_weight: object = None) -> float
Weighted mean squared error of the probability forecast (strictly proper).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Weighted mean squared error. |
Source code in src/probcal/metrics/scores.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | |
brier_skill_score
¶
brier_skill_score(y: object, p: object, *, sample_weight: object = None) -> float
Brier skill score vs the climatology forecast p = mean(y).
Positive values beat the base rate; 0 equals it.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Skill score relative to the weighted base rate. |
Source code in src/probcal/metrics/scores.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | |
log_loss
¶
log_loss(y: object, p: object, *, sample_weight: object = None) -> float
Weighted mean negative log-likelihood.
Strictly proper; the default selection criterion.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Weighted mean negative log-likelihood. |
Source code in src/probcal/metrics/scores.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | |
logloss_calibration_refinement
¶
logloss_calibration_refinement(y: object, p: object, *, frac: float = 0.75, sample_weight: object = None) -> LogLossDecomposition
Split the log loss into a calibration (KL) and refinement (entropy) part.
The conditional event rate c(p) is estimated by a LOESS smoother of
the outcome on the prediction; calibration is the mean
KL(Bernoulli(c) || Bernoulli(p)) and refinement the mean entropy of
Bernoulli(c). Only as good as the plug-in estimate of c.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
frac
|
LOESS smoothing fraction passed through to the recalibration curve.
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
LogLossDecomposition
|
Calibration and refinement terms. |
Source code in src/probcal/metrics/scores.py
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 | |
murphy_curve
¶
murphy_curve(y: object, p: object, *, thresholds: object = 513, sample_weight: object = None) -> MurphyCurve
Murphy diagram data: mean elementary score of the mean functional across a threshold grid.
Uses the Ehm, Gneiting, Jordan & Krüger (2016) elementary score for the mean functional of a binary outcome,
S_theta(p, y) = theta * 1{p > theta, y = 0} + (1 - theta) * 1{p <= theta, y = 1},
whose weighted mean at each theta is this curve's score.
2 * integral(S_theta, theta in [0, 1]) equals the Brier score.
S_theta is linear in theta between consecutive breakpoints
u = sorted(unique(p) | {0, 1}) and jumps only at them, so the
midpoint rule over u reproduces the Brier score to machine
precision, while sampling at the breakpoints themselves converges only
as n grows. Isotonic (PAV) recalibration never increases the score
at any threshold (Ehm et al., 2016), so comparing the two curves
diagnoses the value of recalibration. Cost O(n log n + T log n) for
T thresholds.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Outcomes and predicted probabilities.
TYPE:
|
p
|
Outcomes and predicted probabilities.
TYPE:
|
thresholds
|
Either the number of equally spaced points in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MurphyCurve
|
Threshold grid, weighted mean elementary score, and observation count. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Examples:
>>> import numpy as np
>>> from probcal.metrics import murphy_curve
>>> rng = np.random.default_rng(0)
>>> p = rng.uniform(0.05, 0.5, 300)
>>> y = (rng.random(300) < p).astype(float)
>>> curve = murphy_curve(y, p, thresholds=101)
>>> curve.score.shape
(101,)
Source code in src/probcal/metrics/scores.py
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 | |
murphy_decomposition
¶
murphy_decomposition(y: object, p: object, *, n_bins: int = 10, strategy: str = 'mass', bias_corrected: bool = False, sample_weight: object = None) -> MurphyDecomposition
Binned reliability/resolution/uncertainty split of the Brier score.
bias_corrected=True subtracts the within-bin variance of the event
rate from the squared-gap terms (within-bin variance corrections in the
manner of Ferro & Fricker, 2012); the naive plug-in otherwise. The
decomposition inherits the binning choice — see the metrics chapter.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
n_bins
|
Requested number of bins.
TYPE:
|
strategy
|
TYPE:
|
bias_corrected
|
If
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MurphyDecomposition
|
Reliability, resolution, and uncertainty terms. |
Source code in src/probcal/metrics/scores.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | |
e50
¶
e50(y: object, p: object, *, frac: float = 0.75, sample_weight: object = None, grid_size: int | None = 512) -> float
Median of the |LOESS(y|p) - p| distances.
grid_size=None fits the LOESS exactly at every prediction. The LOESS distances are
always unweighted; sample_weight, when given and
not uniform, weights only the quantile step (see
:func:~probcal._math.weighted_quantile).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
frac
|
LOESS smoothing fraction.
TYPE:
|
sample_weight
|
Optional positive weights; used only for the quantile step.
TYPE:
|
grid_size
|
LOESS evaluation grid size;
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Median of the LOESS distances. |
Source code in src/probcal/metrics/smooth.py
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 | |
e90
¶
e90(y: object, p: object, *, frac: float = 0.75, sample_weight: object = None, grid_size: int | None = 512) -> float
90th percentile of the |LOESS(y|p) - p| distances.
grid_size=None fits the LOESS exactly at every prediction. The LOESS distances are
always unweighted; sample_weight, when given and
not uniform, weights only the quantile step (see
:func:~probcal._math.weighted_quantile).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
frac
|
LOESS smoothing fraction.
TYPE:
|
sample_weight
|
Optional positive weights; used only for the quantile step.
TYPE:
|
grid_size
|
LOESS evaluation grid size;
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
90th percentile of the LOESS distances. |
Source code in src/probcal/metrics/smooth.py
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 | |
ecce
¶
ecce(y: object, p: object, *, sample_weight: object = None) -> EcceResult
Cumulative-deviation calibration error (Arrieta-Ibarra et al., 2022).
Sort by prediction and walk the cumulative sum of weighted residuals,
normalized by the total weight; under calibration the walk hovers near
zero, and drift localizes miscalibration without any smoothing
parameter. The walk is read only at the end of each block of tied
predictions, so the result does not depend on the input order of tied
rows; stat_mean weights each block by its total sample weight.
Without ties and with unit weights the walk is read after every row.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EcceResult
|
Max and mean absolute cumulative deviation. |
Source code in src/probcal/metrics/smooth.py
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | |
emax
¶
emax(y: object, p: object, *, frac: float = 0.75, sample_weight: object = None, grid_size: int | None = 512) -> float
Maximum of the |LOESS(y|p) - p| distances.
grid_size=None fits the LOESS exactly at every prediction.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
frac
|
LOESS smoothing fraction.
TYPE:
|
sample_weight
|
Optional positive weights, validated like everywhere else. The weighted maximum over strictly positive weights is the plain maximum, so the value does not depend on them.
TYPE:
|
grid_size
|
LOESS evaluation grid size;
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Maximum of the LOESS distances. |
Source code in src/probcal/metrics/smooth.py
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 | |
ici
¶
ici(y: object, p: object, *, frac: float = 0.75, sample_weight: object = None, grid_size: int | None = 512) -> float
Integrated calibration index: weighted mean |LOESS(y|p) - p| (Austin & Steyerberg, 2019).
The LOESS stage itself is unweighted.
grid_size=None fits the LOESS exactly at every prediction.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
frac
|
LOESS smoothing fraction.
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
grid_size
|
LOESS evaluation grid size;
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Weighted mean absolute LOESS-to-prediction distance. |
Source code in src/probcal/metrics/smooth.py
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 | |
smooth_ece
¶
smooth_ece(y: object, p: object, *, sample_weight: object = None, bins: int | None = 8192) -> float
Kernel-smoothed ECE with a self-consistent bandwidth (Błasiok–Nakkiran).
Residuals are smoothed with a Gaussian kernel on the logit scale (the
paper's reflected kernel is a boundary device for [0, 1]; on the
unbounded logit scale no reflection is needed), and the
reported value is the fixed point smECE(sigma) = sigma found by
bisection.
bins aggregates the weighted residual measure onto an equal-width
logit lattice and solves the fixed point there by direct convolution
(cost independent of n and sigma). If the solved sigma spans fewer
than 8 cells, the solve is repeated once on a lattice refined to 8 cells
per sigma; if that would exceed 2**20 cells or is still
under-resolved -- or with bins=None or a degenerate logit range --
the exact computation (a 257-point grid evaluator, O(n) per bisection
step) runs instead. The lattice value differs from the exact one by
~1e-4 on typical portfolios; on wide clipped-logit data the exact path's
fixed grid under-resolves small-sigma kernels and the lattice value is
the better one.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
bins
|
Number of lattice bins for the fast path (default 8192);
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
smECE: the fixed point |
Source code in src/probcal/metrics/smooth.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | |
spiegelhalter_z
¶
spiegelhalter_z(y: object, p: object, *, sample_weight: object = None) -> SpiegelhalterResult
Spiegelhalter (1986) z statistic built on the Brier score.
The numerator has expectation zero under calibration; the statistic is asymptotically standard normal. No binning, no smoothing; aggregates the whole range, so compensating regional errors can cancel.
With weights the numerator is sum(w (y - p) (1 - 2p)) and the null
variance its exact variance under calibration, sum(w**2 (1 - 2p)^2 p
(1 - p)) (package convention, :mod:probcal.metrics._common): z
is invariant to rescaling the weights and unit weights give the
unweighted statistic. A Kish-rescaled effective sample size is not used
because it misstates the variance when the weights vary with p (1 - p).
The null variance is zero when every prediction is exactly 0.5 (or
clipped to 0/1); the statistic is then undefined and z and
p_value are nan.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SpiegelhalterResult
|
Z statistic and two-sided p-value. |
Source code in src/probcal/metrics/smooth.py
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 | |
scores
¶
Proper scoring rules: log loss, Brier score, and their decompositions.
Theory, formulas, and pathologies: docs/concepts/metrics.md.
MurphyDecomposition
dataclass
¶
MurphyDecomposition(reliability: float, resolution: float, uncertainty: float)
Binned Murphy (1973) partition of the Brier score.
reliability - resolution + uncertainty equals the Brier score exactly
when predictions are constant within bins; otherwise the identity holds
up to the within-bin variance of p (documented binning bias).
| ATTRIBUTE | DESCRIPTION |
|---|---|
reliability |
Mean squared gap between within-bin predicted and observed rates.
TYPE:
|
resolution |
Mean squared gap between within-bin observed rate and the overall base rate.
TYPE:
|
uncertainty |
Base-rate variance
TYPE:
|
MurphyCurve
dataclass
¶
MurphyCurve(thresholds: ndarray, score: ndarray, n: int)
Bases: _ResultBase
Murphy diagram: mean elementary score of the binary mean functional across thresholds.
| ATTRIBUTE | DESCRIPTION |
|---|---|
thresholds |
Threshold grid :math:
TYPE:
|
score |
Weighted mean elementary score :math:
TYPE:
|
n |
Number of observations.
TYPE:
|
LogLossDecomposition
dataclass
¶
LogLossDecomposition(calibration: float, refinement: float)
Calibration/refinement split of the log loss via a plug-in recalibration curve (LOESS).
| ATTRIBUTE | DESCRIPTION |
|---|---|
calibration |
Mean KL divergence between the plug-in and predicted Bernoullis.
TYPE:
|
refinement |
Mean entropy of the plug-in Bernoulli.
TYPE:
|
log_loss
¶
log_loss(y: object, p: object, *, sample_weight: object = None) -> float
Weighted mean negative log-likelihood.
Strictly proper; the default selection criterion.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Weighted mean negative log-likelihood. |
Source code in src/probcal/metrics/scores.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | |
brier_score
¶
brier_score(y: object, p: object, *, sample_weight: object = None) -> float
Weighted mean squared error of the probability forecast (strictly proper).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Weighted mean squared error. |
Source code in src/probcal/metrics/scores.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | |
brier_skill_score
¶
brier_skill_score(y: object, p: object, *, sample_weight: object = None) -> float
Brier skill score vs the climatology forecast p = mean(y).
Positive values beat the base rate; 0 equals it.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Skill score relative to the weighted base rate. |
Source code in src/probcal/metrics/scores.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | |
murphy_decomposition
¶
murphy_decomposition(y: object, p: object, *, n_bins: int = 10, strategy: str = 'mass', bias_corrected: bool = False, sample_weight: object = None) -> MurphyDecomposition
Binned reliability/resolution/uncertainty split of the Brier score.
bias_corrected=True subtracts the within-bin variance of the event
rate from the squared-gap terms (within-bin variance corrections in the
manner of Ferro & Fricker, 2012); the naive plug-in otherwise. The
decomposition inherits the binning choice — see the metrics chapter.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
n_bins
|
Requested number of bins.
TYPE:
|
strategy
|
TYPE:
|
bias_corrected
|
If
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MurphyDecomposition
|
Reliability, resolution, and uncertainty terms. |
Source code in src/probcal/metrics/scores.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | |
murphy_curve
¶
murphy_curve(y: object, p: object, *, thresholds: object = 513, sample_weight: object = None) -> MurphyCurve
Murphy diagram data: mean elementary score of the mean functional across a threshold grid.
Uses the Ehm, Gneiting, Jordan & Krüger (2016) elementary score for the mean functional of a binary outcome,
S_theta(p, y) = theta * 1{p > theta, y = 0} + (1 - theta) * 1{p <= theta, y = 1},
whose weighted mean at each theta is this curve's score.
2 * integral(S_theta, theta in [0, 1]) equals the Brier score.
S_theta is linear in theta between consecutive breakpoints
u = sorted(unique(p) | {0, 1}) and jumps only at them, so the
midpoint rule over u reproduces the Brier score to machine
precision, while sampling at the breakpoints themselves converges only
as n grows. Isotonic (PAV) recalibration never increases the score
at any threshold (Ehm et al., 2016), so comparing the two curves
diagnoses the value of recalibration. Cost O(n log n + T log n) for
T thresholds.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Outcomes and predicted probabilities.
TYPE:
|
p
|
Outcomes and predicted probabilities.
TYPE:
|
thresholds
|
Either the number of equally spaced points in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MurphyCurve
|
Threshold grid, weighted mean elementary score, and observation count. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Examples:
>>> import numpy as np
>>> from probcal.metrics import murphy_curve
>>> rng = np.random.default_rng(0)
>>> p = rng.uniform(0.05, 0.5, 300)
>>> y = (rng.random(300) < p).astype(float)
>>> curve = murphy_curve(y, p, thresholds=101)
>>> curve.score.shape
(101,)
Source code in src/probcal/metrics/scores.py
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 | |
logloss_calibration_refinement
¶
logloss_calibration_refinement(y: object, p: object, *, frac: float = 0.75, sample_weight: object = None) -> LogLossDecomposition
Split the log loss into a calibration (KL) and refinement (entropy) part.
The conditional event rate c(p) is estimated by a LOESS smoother of
the outcome on the prediction; calibration is the mean
KL(Bernoulli(c) || Bernoulli(p)) and refinement the mean entropy of
Bernoulli(c). Only as good as the plug-in estimate of c.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
frac
|
LOESS smoothing fraction passed through to the recalibration curve.
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
LogLossDecomposition
|
Calibration and refinement terms. |
Source code in src/probcal/metrics/scores.py
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 | |
binned
¶
Binned calibration-error estimators: ECE family, MCE, Hosmer–Lemeshow.
Pathologies (binning sensitivity, finite-sample bias, HL power issues) are
documented in docs/concepts/metrics.md. None of these are selection
criteria; the Hosmer–Lemeshow test is report-only. Sample weights follow the
package convention in :mod:probcal.metrics._common (relative weights;
per-bin variances from the weights themselves wherever a sample size
enters).
HosmerLemeshowResult
dataclass
¶
HosmerLemeshowResult(statistic: float, df: int, p_value: float)
Hosmer–Lemeshow chi-square test (report-only; never a selection criterion).
| ATTRIBUTE | DESCRIPTION |
|---|---|
statistic |
Chi-square test statistic.
TYPE:
|
df |
Degrees of freedom: non-empty groups minus
TYPE:
|
p_value |
Upper-tail p-value of the statistic;
TYPE:
|
ece
¶
ece(y: object, p: object, *, n_bins: int = 15, strategy: str = 'mass', norm: str = 'l1', sample_weight: object = None) -> float
Expected calibration error; norm="max" gives the MCE.
Binning-sensitive and upward-biased in finite samples — report, never select on it (see the metrics chapter's table).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
n_bins
|
Requested number of bins (positive integer).
TYPE:
|
strategy
|
TYPE:
|
norm
|
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Weighted binned calibration error under the chosen norm. |
Source code in src/probcal/metrics/binned.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | |
ece_debiased
¶
ece_debiased(y: object, p: object, *, n_bins: int = 15, strategy: str = 'mass', sample_weight: object = None) -> float
Bias-corrected ECE, floored at zero.
Per-bin squared gaps minus the within-bin variance of the event rate
(correction in the spirit of Bröcker 2009 / Ferro & Fricker 2012):
sqrt(max(gap_b**2 - rate_b * (1 - rate_b) / (n_b - 1), 0)) for bins
with n_b > 1. n_b is the bin's effective count
sum_b(w)**2 / sum_b(w**2) -- the size of an unweighted bin whose
event rate has the same variance -- so it follows the weights inside the
bin, and is the raw count for unit (or within-bin constant) weights.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
n_bins
|
Requested number of bins.
TYPE:
|
strategy
|
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Bias-corrected calibration error. |
Source code in src/probcal/metrics/binned.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
ece_sweep
¶
ece_sweep(y: object, p: object, *, norm: str = 'l1', sample_weight: object = None, max_bins: int = 100, rule: str = 'first_violation') -> float
Monotonic-sweep calibration error (Roelofs et al., 2022).
Equal-mass bins; the bin count is the largest b such that b and
every smaller bin count give non-decreasing bin event rates — the
paper's b* = max{b : for all b' <= b, ybar_1 <= ... <= ybar_b'}
(its Algorithm 1: sweep b = 2, 3, ... and stop at the first
non-monotone binning). The paper sweeps up to b = n; the sweep here
stops at max_bins (default 100) as a cost cap.
rule="largest" instead takes the largest monotone b anywhere in
2..max_bins, skipping over non-monotone counts.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
norm
|
Norm of the final binned error at the selected bin count.
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
max_bins
|
Upper end of the sweep (capped at
TYPE:
|
rule
|
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Calibration error at the selected bin count. |
Source code in src/probcal/metrics/binned.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | |
hosmer_lemeshow
¶
hosmer_lemeshow(y: object, p: object, *, n_bins: int = 10, sample_weight: object = None, ddof: int = 0) -> HosmerLemeshowResult
Hosmer–Lemeshow goodness-of-fit test on n_bins equal-mass risk groups.
The statistic depends on an essentially arbitrary grouping and its power scales with n — see the metrics chapter for why this is report-only.
Per group g, O_g = sum(w y) and E_g = sum(w p) are compared
against V_g = S_g * pt_g * (1 - pt_g), where S_g = sum(w**2) and
pt_g = sum(w**2 p) / S_g. V_g is the weighted form of the
classical n_g pbar_g (1 - pbar_g): it equals the exact null variance
sum(w**2 p (1 - p)) of O_g - E_g plus the same within-group
spread term sum(w**2 (p - pt_g)**2) the unweighted statistic carries.
The statistic is invariant to rescaling the weights, and unit weights
give the unweighted test bit for bit.
The reference distribution is chi-square on groups - ddof degrees of
freedom. With p fixed in advance (a model or calibrator fitted on
other data, the usual validation setting) the per-group standardized
residuals are asymptotically independent, so the statistic is
chi2(groups): ddof=0, the default (Hosmer, Lemeshow and
Sturdivant, 2013, on external validation). The classical groups - 2
is for a logistic model fitted on the same data; pass ddof=2 for it.
On out-of-sample p it is anti-conservative (about 12% rejections at
a nominal 5% with 10 groups).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
n_bins
|
Requested number of equal-mass risk groups. Tied scores can collapse
groups; when no more than
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
ddof
|
Degrees of freedom subtracted from the number of non-empty groups:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
HosmerLemeshowResult
|
Chi-square statistic, degrees of freedom, and p-value. |
Source code in src/probcal/metrics/binned.py
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | |
smooth
¶
Binning-free calibration metrics: smoothECE, ECCE, ICI family, Spiegelhalter z.
Theory: docs/concepts/metrics.md. Sample weights follow the package
convention in :mod:probcal.metrics._common.
Lattice
module-attribute
¶
Lattice = tuple[float, float, int]
(width, t_lo, bins) of the equal-width logit lattice a smECE was solved on.
EcceResult
dataclass
¶
EcceResult(stat_max: float, stat_mean: float)
Empirical cumulative calibration error: Kolmogorov-style max and mean of the cumulative deviation over sorted predictions.
| ATTRIBUTE | DESCRIPTION |
|---|---|
stat_max |
Maximum absolute cumulative deviation.
TYPE:
|
stat_mean |
Weighted mean absolute cumulative deviation (each tied-score block weighted by its total sample weight).
TYPE:
|
SpiegelhalterResult
dataclass
¶
SpiegelhalterResult(z: float, p_value: float)
Spiegelhalter's z test of forecast unbiasedness (two-sided).
| ATTRIBUTE | DESCRIPTION |
|---|---|
z |
Standardized test statistic (
TYPE:
|
p_value |
Two-sided p-value under the standard normal approximation (
TYPE:
|
smooth_ece
¶
smooth_ece(y: object, p: object, *, sample_weight: object = None, bins: int | None = 8192) -> float
Kernel-smoothed ECE with a self-consistent bandwidth (Błasiok–Nakkiran).
Residuals are smoothed with a Gaussian kernel on the logit scale (the
paper's reflected kernel is a boundary device for [0, 1]; on the
unbounded logit scale no reflection is needed), and the
reported value is the fixed point smECE(sigma) = sigma found by
bisection.
bins aggregates the weighted residual measure onto an equal-width
logit lattice and solves the fixed point there by direct convolution
(cost independent of n and sigma). If the solved sigma spans fewer
than 8 cells, the solve is repeated once on a lattice refined to 8 cells
per sigma; if that would exceed 2**20 cells or is still
under-resolved -- or with bins=None or a degenerate logit range --
the exact computation (a 257-point grid evaluator, O(n) per bisection
step) runs instead. The lattice value differs from the exact one by
~1e-4 on typical portfolios; on wide clipped-logit data the exact path's
fixed grid under-resolves small-sigma kernels and the lattice value is
the better one.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
bins
|
Number of lattice bins for the fast path (default 8192);
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
smECE: the fixed point |
Source code in src/probcal/metrics/smooth.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | |
ecce
¶
ecce(y: object, p: object, *, sample_weight: object = None) -> EcceResult
Cumulative-deviation calibration error (Arrieta-Ibarra et al., 2022).
Sort by prediction and walk the cumulative sum of weighted residuals,
normalized by the total weight; under calibration the walk hovers near
zero, and drift localizes miscalibration without any smoothing
parameter. The walk is read only at the end of each block of tied
predictions, so the result does not depend on the input order of tied
rows; stat_mean weights each block by its total sample weight.
Without ties and with unit weights the walk is read after every row.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EcceResult
|
Max and mean absolute cumulative deviation. |
Source code in src/probcal/metrics/smooth.py
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | |
ici
¶
ici(y: object, p: object, *, frac: float = 0.75, sample_weight: object = None, grid_size: int | None = 512) -> float
Integrated calibration index: weighted mean |LOESS(y|p) - p| (Austin & Steyerberg, 2019).
The LOESS stage itself is unweighted.
grid_size=None fits the LOESS exactly at every prediction.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
frac
|
LOESS smoothing fraction.
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
grid_size
|
LOESS evaluation grid size;
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Weighted mean absolute LOESS-to-prediction distance. |
Source code in src/probcal/metrics/smooth.py
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 | |
e50
¶
e50(y: object, p: object, *, frac: float = 0.75, sample_weight: object = None, grid_size: int | None = 512) -> float
Median of the |LOESS(y|p) - p| distances.
grid_size=None fits the LOESS exactly at every prediction. The LOESS distances are
always unweighted; sample_weight, when given and
not uniform, weights only the quantile step (see
:func:~probcal._math.weighted_quantile).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
frac
|
LOESS smoothing fraction.
TYPE:
|
sample_weight
|
Optional positive weights; used only for the quantile step.
TYPE:
|
grid_size
|
LOESS evaluation grid size;
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Median of the LOESS distances. |
Source code in src/probcal/metrics/smooth.py
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 | |
e90
¶
e90(y: object, p: object, *, frac: float = 0.75, sample_weight: object = None, grid_size: int | None = 512) -> float
90th percentile of the |LOESS(y|p) - p| distances.
grid_size=None fits the LOESS exactly at every prediction. The LOESS distances are
always unweighted; sample_weight, when given and
not uniform, weights only the quantile step (see
:func:~probcal._math.weighted_quantile).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
frac
|
LOESS smoothing fraction.
TYPE:
|
sample_weight
|
Optional positive weights; used only for the quantile step.
TYPE:
|
grid_size
|
LOESS evaluation grid size;
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
90th percentile of the LOESS distances. |
Source code in src/probcal/metrics/smooth.py
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 | |
emax
¶
emax(y: object, p: object, *, frac: float = 0.75, sample_weight: object = None, grid_size: int | None = 512) -> float
Maximum of the |LOESS(y|p) - p| distances.
grid_size=None fits the LOESS exactly at every prediction.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
frac
|
LOESS smoothing fraction.
TYPE:
|
sample_weight
|
Optional positive weights, validated like everywhere else. The weighted maximum over strictly positive weights is the plain maximum, so the value does not depend on them.
TYPE:
|
grid_size
|
LOESS evaluation grid size;
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Maximum of the LOESS distances. |
Source code in src/probcal/metrics/smooth.py
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 | |
spiegelhalter_z
¶
spiegelhalter_z(y: object, p: object, *, sample_weight: object = None) -> SpiegelhalterResult
Spiegelhalter (1986) z statistic built on the Brier score.
The numerator has expectation zero under calibration; the statistic is asymptotically standard normal. No binning, no smoothing; aggregates the whole range, so compensating regional errors can cancel.
With weights the numerator is sum(w (y - p) (1 - 2p)) and the null
variance its exact variance under calibration, sum(w**2 (1 - 2p)^2 p
(1 - p)) (package convention, :mod:probcal.metrics._common): z
is invariant to rescaling the weights and unit weights give the
unweighted statistic. A Kish-rescaled effective sample size is not used
because it misstates the variance when the weights vary with p (1 - p).
The null variance is zero when every prediction is exactly 0.5 (or
clipped to 0/1); the statistic is then undefined and z and
p_value are nan.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SpiegelhalterResult
|
Z statistic and two-sided p-value. |
Source code in src/probcal/metrics/smooth.py
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 | |
regression
¶
Recalibration-regression framework: calibration intercept, slope, and joint test.
The Cox (1958) framework; lineage through Miller, Hui & Tierney (1991).
Theory: docs/concepts/metrics.md. Sample weights follow the package
convention in :mod:probcal.metrics._common.
CalibrationTestResult
dataclass
¶
CalibrationTestResult(statistic: float, p_value: float, alpha: float, beta: float, df: float = 2.0)
Likelihood-ratio test of (intercept, slope) = (0, 1) — the Cox-framed weak calibration test.
| ATTRIBUTE | DESCRIPTION |
|---|---|
statistic |
Likelihood-ratio test statistic, referred to
TYPE:
|
p_value |
Upper-tail p-value of the statistic.
TYPE:
|
alpha |
Fitted intercept (also available as :attr:
TYPE:
|
beta |
Fitted slope (also available as :attr:
TYPE:
|
df |
Degrees of freedom of the reference chi-square:
TYPE:
|
GuardrailReport
dataclass
¶
GuardrailReport(slope: float, intercept: float, spiegelhalter_p: float, slope_ok: bool, intercept_ok: bool, spiegelhalter_ok: bool, all_ok: bool)
Three-flag calibration health summary used across the package.
Thresholds are conventions, not theorems: slope within [0.9, 1.1], intercept within +/-0.1 log-odds, Spiegelhalter p above 0.05.
| ATTRIBUTE | DESCRIPTION |
|---|---|
slope |
Fitted Cox calibration slope.
TYPE:
|
intercept |
Fitted calibration-in-the-large intercept (log-odds).
TYPE:
|
spiegelhalter_p |
Spiegelhalter test p-value.
TYPE:
|
slope_ok |
Whether
TYPE:
|
intercept_ok |
Whether
TYPE:
|
spiegelhalter_ok |
Whether
TYPE:
|
all_ok |
Conjunction of the three flags above.
TYPE:
|
calibration_intercept
¶
calibration_intercept(y: object, p: object, *, sample_weight: object = None) -> float
Calibration-in-the-large in log-odds.
Logistic intercept with the slope fixed at 1 (offset regression on logit(p)).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Fitted intercept in log-odds units. |
Source code in src/probcal/metrics/regression.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | |
calibration_slope
¶
calibration_slope(y: object, p: object, *, sample_weight: object = None) -> float
Cox calibration slope.
< 1 means overfitting/overconfident spread, > 1 underfitting.
When every prediction has the same logit(p) (a constant p, or a
single PD level) the slope is not identified and nan is returned
with a UserWarning.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Fitted slope on the logit scale ( |
Source code in src/probcal/metrics/regression.py
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | |
calibration_test
¶
calibration_test(y: object, p: object, *, sample_weight: object = None) -> CalibrationTestResult
Likelihood-ratio test of joint calibration (alpha, beta) = (0, 1).
With weights, the fit and the likelihood ratio use sample_weight as
given, and the weighted LR statistic -- distributed under calibration as
a weighted sum of chi2_1 variables, not as chi2_2 -- is referred
to a second-order Rao-Scott corrected chi-square
(:func:probcal.metrics._common.rao_scott; the design effects use the
exact null variance sum(w**2 p (1 - p) x x') of the weighted score).
The test is invariant to rescaling the weights, and unit (or constant)
weights give the plain 2-df likelihood-ratio test.
When every prediction has the same logit(p) the slope is not
identified: only calibration-in-the-large is tested (slope fixed at 1,
df = 1), beta is nan, and a UserWarning is emitted.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
CalibrationTestResult
|
Test statistic, p-value, and fitted intercept/slope. |
Source code in src/probcal/metrics/regression.py
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 | |
calibration_guardrails
¶
calibration_guardrails(y: object, p: object, *, sample_weight: object = None) -> GuardrailReport
Evaluate the three guardrail flags.
Printed in selection reports and offset audit reports.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
sample_weight
|
Optional positive weights, same length as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
GuardrailReport
|
Slope, intercept, and Spiegelhalter-p values with pass/fail flags. |
Source code in src/probcal/metrics/regression.py
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | |
grade
¶
Per-grade binomial and Jeffreys backtests (credit-risk rating grades).
Supervisory context (BCBS WP14; ECB 2019 instructions): each rating grade's
realized default count is tested against its assigned PD. Theory:
docs/concepts/metrics.md.
BinomialGradeResult
dataclass
¶
BinomialGradeResult(grades: tuple, n: ndarray, k: ndarray, pd: ndarray, p_exact: ndarray, p_normal: ndarray, light: tuple, ci_low: ndarray, ci_high: ndarray)
Bases: _ResultBase
Exact and approximate one-sided binomial backtest per rating grade.
| ATTRIBUTE | DESCRIPTION |
|---|---|
grades |
Grade labels: the
TYPE:
|
n |
Observation count per grade.
TYPE:
|
k |
Default count per grade.
TYPE:
|
pd |
Assigned PD per grade (mean of
TYPE:
|
p_exact |
Exact binomial tail p-value per grade (also available as
:attr:
TYPE:
|
p_normal |
Normal-approximation p-value per grade.
TYPE:
|
light |
Traffic light per grade (
TYPE:
|
ci_low, ci_high |
90% Clopper-Pearson display interval for the observed rate.
TYPE:
|
p_value
property
¶
p_value: ndarray
Alias of :attr:p_exact (the exact test decides the traffic light).
JeffreysGradeResult
dataclass
¶
JeffreysGradeResult(grades: tuple, n: ndarray, k: ndarray, pd: ndarray, p_value: ndarray, light: tuple, ci_low: ndarray, ci_high: ndarray)
Bases: _ResultBase
Jeffreys-posterior backtest per rating grade (ECB IRB practice).
| ATTRIBUTE | DESCRIPTION |
|---|---|
grades |
Grade labels: the
TYPE:
|
n |
Observation count per grade.
TYPE:
|
k |
Default count per grade.
TYPE:
|
pd |
Assigned PD per grade (mean of
TYPE:
|
p_value |
Posterior
TYPE:
|
light |
Traffic light per grade (
TYPE:
|
ci_low, ci_high |
Central 90% Jeffreys posterior display interval.
TYPE:
|
binomial_grade_test
¶
binomial_grade_test(y: object, p: object, grades: object, *, sample_weight: object = None, order: object = None) -> BinomialGradeResult
Exact binomial tail test per grade: P(X >= k | n, PD).
Small p-values flag grades with more defaults than the assigned PD
supports. The exact tail uses the incomplete-beta identity
P(X >= k) = I_PD(k, n - k + 1); the normal approximation is reported
alongside. Traffic lights: green > 0.05, amber > 0.01, red <= 0.01.
ci_low/ci_high are 90% Clopper-Pearson display intervals for the
observed rate; the traffic light itself remains the one-sided exact test,
unchanged.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities (assigned PDs) in
TYPE:
|
grades
|
Rating grade label per observation, or a :class:
TYPE:
|
sample_weight
|
Not used: grade tests use raw integer counts. A
TYPE:
|
order
|
Explicit grade order for the result (a permutation of the grade
labels present);
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BinomialGradeResult
|
Per-grade counts, p-values, traffic lights, and display intervals. |
Source code in src/probcal/metrics/grade.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | |
jeffreys_grade_test
¶
jeffreys_grade_test(y: object, p: object, grades: object, *, sample_weight: object = None, order: object = None) -> JeffreysGradeResult
Jeffreys test per grade: posterior P(theta <= PD | k, n) under Beta(k+1/2, n-k+1/2).
One-sided and conservative by design: a small value flags a grade whose
PD is likely understated. Do not read it two-sided (a recurring
validation error — see the metrics chapter). ci_low/ci_high are
the central 90% Jeffreys posterior display intervals; the traffic light
itself remains the one-sided posterior test, unchanged.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities (assigned PDs) in
TYPE:
|
grades
|
Rating grade label per observation, or a :class:
TYPE:
|
sample_weight
|
Not used: grade tests use raw integer counts. A
TYPE:
|
order
|
Explicit grade order for the result (a permutation of the grade
labels present);
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
JeffreysGradeResult
|
Per-grade counts, p-values, traffic lights, and display intervals. |
Source code in src/probcal/metrics/grade.py
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 | |
kernel
¶
Kernel calibration error (SKCE) and its calibration tests.
Theory: docs/concepts/metrics.md. Widmann, Lindsten & Zachariah (2019),
"Calibration tests in multi-class classification: A unifying framework",
NeurIPS 32 (arXiv:1910.11385).
Binary specialization: with the identity-matrix kernel construction and a
prediction represented as the 2-vector (1 - p, p), the paper's kernel term
reduces to h_ij = 2 * k(s_i, s_j) * (y_i - p_i) * (y_j - p_j) — the factor
2 keeps values comparable with the paper's framework. Residuals always stay on
the probability scale; only the kernel input s may be logit-transformed.
No sample_weight: the cited U-statistic theory (unbiasedness, the
degenerate limit, the distribution-free bounds) is stated for unweighted
i.i.d. samples. Refusing the argument is honest; improvising weighted
inference is not.
Complexity: "uq", "biased", and the bootstrap test are O(n^2) memory
and O(n_boot * n^2) time; prefer method="asymptotic" for n >~ 20 000.
SkceTestResult
dataclass
¶
SkceTestResult(statistic: float, estimator: str, method: str, p_value: float, p_value_bound: float, bandwidth: float, n_boot: int | None)
One-sided SKCE calibration test (H0: calibrated; large positive rejects).
| ATTRIBUTE | DESCRIPTION |
|---|---|
statistic |
SKCE point estimate (
TYPE:
|
estimator |
Estimator used for
TYPE:
|
method |
Test method used (
TYPE:
|
p_value |
Test p-value.
TYPE:
|
p_value_bound |
Distribution-free worst-case p-value bound (valid without asymptotics).
TYPE:
|
bandwidth |
Kernel bandwidth used (resolved from
TYPE:
|
n_boot |
Bootstrap replicate count for the bootstrap method;
TYPE:
|
skce
¶
skce(y: object, p: object, *, estimator: str = 'uq', kernel: str = 'laplace', bandwidth: float | None = None, scale: str = 'probability', random_state: int = 42) -> float
Squared kernel calibration error (Widmann et al., 2019, Table 1).
"uq" (default) is the unbiased quadratic estimator (may be negative);
"ul" the unbiased linear O(n) estimator over seeded disjoint pairs
(random_state controls the pairing); "biased" the nonnegative
V-statistic. bandwidth=None uses the deterministic median heuristic;
scale="logit" transforms the kernel input only (the low-PD option).
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
estimator
|
Estimator variant; see above.
TYPE:
|
kernel
|
Kernel family applied to the (scaled) score distance.
TYPE:
|
bandwidth
|
Kernel bandwidth;
TYPE:
|
scale
|
Scale on which the kernel input
TYPE:
|
random_state
|
Seed for the
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
SKCE point estimate. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/probcal/metrics/kernel.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | |
skce_test
¶
skce_test(y: object, p: object, *, method: str = 'bootstrap', n_boot: int = 999, kernel: str = 'laplace', bandwidth: float | None = None, scale: str = 'probability', random_state: int = 42) -> SkceTestResult
Calibration test on the SKCE (Widmann et al., 2019, Sec. 6 / App. G).
"bootstrap" (default): quadratic statistic with Arcones–Giné centered
resampling; O(n_boot * n^2) — the more powerful choice. "asymptotic":
linear statistic, normal approximation (Corollary G.3); O(n), preferred
for n >~ 20 000, but a single random pairing can miss slope-type
miscalibration that the bootstrap test rejects (the paper's documented
power gap). p_value_bound is the distribution-free worst case.
| PARAMETER | DESCRIPTION |
|---|---|
y
|
Binary outcomes in
TYPE:
|
p
|
Predicted probabilities in
TYPE:
|
method
|
Test method; see above.
TYPE:
|
n_boot
|
Bootstrap replicate count (
TYPE:
|
kernel
|
Kernel family applied to the (scaled) score distance.
TYPE:
|
bandwidth
|
Kernel bandwidth;
TYPE:
|
scale
|
Scale on which the kernel input
TYPE:
|
random_state
|
Seed for the resampling (
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SkceTestResult
|
Test statistic, method, p-value, and worst-case bound. |
Source code in src/probcal/metrics/kernel.py
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | |