API reference¶
Everything below is importable from the top-level kernel_calibration package
(e.g. from kernel_calibration import KLCE_test). Plotting helpers live in the
kernel_calibration.plots submodule.
The test and statistic¶
kernel_calibration.kite.KLCE_test ¶
KLCE_test(X, Y, p, prob_kernel_width, iterations, key, x_kernel_width=None, add_one_correction=True)
Perform the KLCE hypothesis test comparing model predictions to true labels.
This function computes the test statistic and p-value by comparing the observed KLCE2 estimator against a null distribution generated by permutations. The null hypothesis is that the model is locally calibrated (KLCE^2 = 0); a small p-value is evidence against it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
array_like
|
Feature matrix of shape (n_samples, n_features). NumPy arrays are accepted. |
required |
Y
|
array_like
|
True label vector of shape (n_samples,). |
required |
p
|
array_like
|
Predicted probability vector of shape (n_samples,). |
required |
prob_kernel_width
|
float
|
Bandwidth for the probability kernel. |
required |
iterations
|
int
|
Number of permutations for null distribution. |
required |
key
|
Array or int
|
PRNG key for random operations. An integer is accepted and converted with
|
required |
x_kernel_width
|
float
|
Bandwidth for the feature kernel. If omitted, |
None
|
add_one_correction
|
bool
|
If True (default), use the Monte-Carlo permutation p-value
|
True
|
Returns:
| Type | Description |
|---|---|
KLCETestResult
|
A result object that unpacks as |
Source code in kernel_calibration/kite.py
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 302 303 304 305 306 307 308 309 310 311 312 313 314 | |
kernel_calibration.kite.KLCETestResult
dataclass
¶
KLCETestResult(statistic, pvalue, null_distribution=None)
Result of :func:KLCE_test.
Unpacks as (statistic, pvalue) for backward compatibility
(stat, p = KLCE_test(...)), and also exposes attribute access
(.statistic, .pvalue, .null_distribution) in the style of SciPy's
hypothesis-test result objects.
kernel_calibration.kite.KLCE2_estimator ¶
KLCE2_estimator(K, err)
Compute the KLCE2 estimator from kernel matrix K and error vector err.
This function sums the off-diagonal elements of the elementwise product between K and the outer product of err with itself, normalized by n*(n-1).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
K
|
ndarray
|
Kernel matrix of shape (n_samples, n_samples). |
required |
err
|
ndarray
|
Error vector of shape (n_samples,). |
required |
Returns:
| Type | Description |
|---|---|
float
|
KLCE2 estimator value. |
Source code in kernel_calibration/kite.py
100 101 102 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 | |
kernel_calibration.kite.create_kernel ¶
create_kernel(X, p, prob_kernel_width, x_kernel_width)
Create combined kernel matrix for KLCE.
This function computes the elementwise product of two RBF kernels: one over predicted probabilities p and one over feature matrix X.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Feature matrix of shape (n_samples, n_features). |
required |
p
|
ndarray
|
Predicted probabilities array of shape (n_samples,). |
required |
prob_kernel_width
|
float
|
Bandwidth parameter for the probability kernel. |
required |
x_kernel_width
|
float
|
Bandwidth parameter for the feature kernel. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Combined kernel matrix of shape (n_samples, n_samples). |
Source code in kernel_calibration/kite.py
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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | |
kernel_calibration.kite.rbf_kernel ¶
rbf_kernel(X, Y, gamma)
Compute the RBF (Gaussian) kernel matrix between X and Y.
This function computes the Gaussian (radial basis function) kernel elementwise between two datasets X and Y using kernel coefficient gamma.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
First data array of shape (n_samples, n_features) or (n_samples,) for single feature. |
required |
Y
|
ndarray
|
Second data array of shape (m_samples, n_features) or (m_samples,). Must have the same number of features as X, but may have a different number of samples — rectangular kernels are supported (used e.g. by the LCB diagnostic to evaluate at query points). |
required |
gamma
|
float
|
Kernel coefficient, typically defined as 1 / (sigma^2). |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Kernel matrix of shape (n_samples, m_samples). |
Source code in kernel_calibration/kite.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | |
The diagnostic¶
kernel_calibration.lcb.local_calibration_bias ¶
local_calibration_bias(X, y, f, prob_kernel_width, x_kernel_width=None, *, X_query=None, f_query=None, leave_one_out=False)
Estimate the local calibration bias at each query point.
For a query point (x', a') the estimator is the Nadaraya–Watson-style
kernel-weighted average of residuals (Eq. 7 of the paper)::
LCB(x', a') = sum_i (y_i - f_i) k(f_i, a') l(x_i, x')
LCB(x', a') = sum_i (y_i - f_i) k(f_i, a') l(x_i, x')
sum_i k(f_i, a') l(x_i, x')
with k an RBF kernel on predicted probabilities and l an RBF kernel on
features. Setting the feature kernel aside (a single feature value) this reduces
to the usual reliability-curve bias; with the feature kernel it localises the
bias in feature space, revealing e.g. subgroups where the model is miscalibrated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
array_like
|
Reference feature matrix of shape (n_samples, n_features). NumPy arrays are accepted. |
required |
y
|
array_like
|
Reference labels of shape (n_samples,). |
required |
f
|
array_like
|
Reference predicted probabilities of shape (n_samples,). |
required |
prob_kernel_width
|
float
|
Bandwidth for the probability kernel |
required |
x_kernel_width
|
float
|
Bandwidth for the feature kernel |
None
|
X_query
|
array_like
|
Feature points at which to evaluate the bias, shape (m_samples, n_features).
Defaults to |
None
|
f_query
|
array_like
|
Predicted probabilities at the query points, shape (m_samples,). Required
if |
None
|
leave_one_out
|
bool
|
Only used when evaluating at the reference points themselves (no explicit
|
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Estimated local calibration bias at each query point, shape (m_samples,). |
Examples:
>>> bias = local_calibration_bias(X, y, f, prob_kernel_width=0.1)
>>> # bias[i] > 0 -> model under-confident near sample i
>>> # bias[i] < 0 -> model over-confident near sample i
Source code in kernel_calibration/lcb.py
28 29 30 31 32 33 34 35 36 37 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 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 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | |
Recalibration¶
kernel_calibration.kite.recalibrated_model ¶
recalibrated_model(sigma_k=0.1, sigma_l=1.0, alpha=0.5, beta=0.5, num_steps=1000, learning_rate=0.001, hidden_layer_sizes=(64, 64), seed=121, verbose=False)
Recalibration model combining distillation loss and KLCE penalty.
This class implements a simple MLP-based recalibration of base probabilities trained to minimize a combination of KL divergence and kernel-based calibration error.
Initialize hyperparameters for the recalibration model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sigma_k
|
float
|
Kernel width for probability kernel. Default is 0.1. |
0.1
|
sigma_l
|
float
|
Kernel width for feature kernel. Default is 1.0. |
1.0
|
alpha
|
float
|
Weight for the distillation loss term. Default is 0.5. |
0.5
|
beta
|
float
|
Weight for the KLCE penalty term. Default is 0.5. |
0.5
|
num_steps
|
int
|
Number of training steps. Default is 1000. |
1000
|
learning_rate
|
float
|
Optimizer learning rate. Default is 0.001. |
0.001
|
hidden_layer_sizes
|
Tuple[int, ...]
|
Sizes of hidden MLP layers. Default is (64, 64). |
(64, 64)
|
seed
|
int
|
Random seed for initialization. Default is 121. |
121
|
verbose
|
bool
|
If True, print the training loss every 100 steps. Default is False. |
False
|
Source code in kernel_calibration/kite.py
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 434 435 436 437 438 439 | |
accuracy_score ¶
accuracy_score(y_pred, y)
Compute the classification accuracy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_pred
|
Sequence[int]
|
Predicted labels of shape (n_samples,). |
required |
y
|
Sequence[int]
|
True labels of shape (n_samples,). |
required |
Returns:
| Type | Description |
|---|---|
float
|
Proportion of correctly classified samples. |
Source code in kernel_calibration/kite.py
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 | |
fit ¶
fit(y_proba, x_cal, y)
Train the recalibration model on calibration data.
This method optimizes model parameters to minimize the total loss over specified number of steps using the Adam optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_proba
|
ndarray
|
Base probability predictions of shape (n_samples,). |
required |
x_cal
|
ndarray
|
Calibration feature matrix of shape (n_samples, n_features). |
required |
y
|
ndarray
|
True labels of shape (n_samples,). |
required |
Returns:
| Type | Description |
|---|---|
recalibrated_model
|
The fitted estimator ( |
Source code in kernel_calibration/kite.py
510 511 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 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 | |
get_labels ¶
get_labels(y_proba, threshold=0.5)
Convert probability predictions to binary labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_proba
|
ndarray
|
Probability vector of shape (n_samples,). |
required |
threshold
|
float
|
Classification threshold. Default is 0.5. |
0.5
|
Returns:
| Type | Description |
|---|---|
List[int]
|
Binary labels (0 or 1) for each sample. |
Source code in kernel_calibration/kite.py
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 | |
get_params ¶
get_params(deep=True)
Return the model hyperparameters (scikit-learn estimator API).
Source code in kernel_calibration/kite.py
441 442 443 444 445 446 447 448 449 450 451 452 453 | |
predict_proba ¶
predict_proba(y_proba, x_cal)
Generate recalibrated probability predictions.
This method applies the trained recalibration model to new data, returning corrected probability estimates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_proba
|
ndarray
|
Base probability predictions of shape (n_samples,). |
required |
x_cal
|
ndarray
|
Calibration features of shape (n_samples, n_features). |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Recalibrated probability vector of shape (n_samples,). |
Source code in kernel_calibration/kite.py
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 | |
set_params ¶
set_params(**params)
Set model hyperparameters (scikit-learn estimator API). Returns self.
Source code in kernel_calibration/kite.py
455 456 457 458 459 460 461 462 463 464 465 | |
total_loss ¶
total_loss(params, base_probs, x, y)
Compute the total loss combining distillation and KLCE penalty.
This function calculates the KL divergence between base_probs and recalibrated predictions, then adds the kernel-based calibration error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
Dict[str, ndarray]
|
Recalibration model parameters. |
required |
base_probs
|
ndarray
|
Original predicted probabilities of shape (n_samples,). |
required |
x
|
ndarray
|
Calibration features of shape (n_samples, n_features). |
required |
y
|
ndarray
|
True labels of shape (n_samples,). |
required |
Returns:
| Type | Description |
|---|---|
float
|
Weighted sum of distillation loss and KLCE penalty. |
Source code in kernel_calibration/kite.py
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 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 | |
Bandwidth selection¶
kernel_calibration.bandwidth.select_bandwidths ¶
select_bandwidths(X, f, max_samples=2000, seed=0)
Median-heuristic bandwidths for the probability and feature kernels.
Convenience wrapper that returns sensible defaults for both kernels used by
:func:~kernel_calibration.kite.KLCE_test and
:func:~kernel_calibration.lcb.local_calibration_bias.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
array_like
|
Feature matrix of shape (n_samples, n_features) or (n_samples,). |
required |
f
|
array_like
|
Predicted probabilities of shape (n_samples,). |
required |
max_samples
|
int
|
Passed through to :func: |
2000
|
seed
|
int
|
Passed through to :func: |
2000
|
Returns:
| Type | Description |
|---|---|
Tuple[float, float]
|
|
Examples:
>>> pw, xw = select_bandwidths(X, f)
>>> stat, pval = KLCE_test(X, y, f, prob_kernel_width=pw, iterations=200,
... key=0, x_kernel_width=xw)
Source code in kernel_calibration/bandwidth.py
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 | |
kernel_calibration.bandwidth.median_heuristic ¶
median_heuristic(values, max_samples=2000, seed=0)
Median-heuristic bandwidth: the median pairwise Euclidean distance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
array_like
|
Data of shape (n_samples, n_features) or (n_samples,) for a single feature (e.g. predicted probabilities). |
required |
max_samples
|
int
|
If |
2000
|
seed
|
int
|
Seed for the subsampling RNG (only used when subsampling). Default is 0. |
0
|
Returns:
| Type | Description |
|---|---|
float
|
The median non-zero pairwise distance, usable directly as a kernel width.
Falls back to |
Source code in kernel_calibration/bandwidth.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 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 | |
Baseline metrics¶
kernel_calibration.metrics.expected_calibration_error ¶
expected_calibration_error(y, p, n_bins=15)
Expected Calibration Error (ECE) with equal-width bins.
ECE = sum over bins of (bin_weight) * |accuracy - confidence|.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
array_like
|
Binary labels of shape (n_samples,). |
required |
p
|
array_like
|
Predicted probabilities of shape (n_samples,). |
required |
n_bins
|
int
|
Number of equal-width bins in [0, 1]. Default is 15. |
15
|
Returns:
| Type | Description |
|---|---|
float
|
The ECE. Lower is better; 0 means perfectly calibrated on this binning. |
Source code in kernel_calibration/metrics.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | |
kernel_calibration.metrics.maximum_calibration_error ¶
maximum_calibration_error(y, p, n_bins=15)
Maximum Calibration Error (MCE): the worst per-bin calibration gap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
array_like
|
Labels and predicted probabilities of shape (n_samples,). |
required |
p
|
array_like
|
Labels and predicted probabilities of shape (n_samples,). |
required |
n_bins
|
int
|
Number of equal-width bins in [0, 1]. Default is 15. |
15
|
Returns:
| Type | Description |
|---|---|
float
|
|
Source code in kernel_calibration/metrics.py
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | |
kernel_calibration.metrics.brier_score ¶
brier_score(y, p)
Brier score: mean squared error between probabilities and outcomes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
array_like
|
Binary labels of shape (n_samples,). |
required |
p
|
array_like
|
Predicted probabilities of shape (n_samples,). |
required |
Returns:
| Type | Description |
|---|---|
float
|
Mean of |
Source code in kernel_calibration/metrics.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | |
kernel_calibration.metrics.kernel_calibration_error ¶
kernel_calibration_error(y, p, prob_kernel_width)
Squared Kernel Calibration Error (KCE) of Widmann et al. (2019).
This is the global (non-local) counterpart of KLCE: the same U-statistic on
residuals y - p but with only the probability kernel and no feature kernel
(equivalently, the feature kernel set to a constant). It measures whether the
model is calibrated on average, without localising in feature space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
array_like
|
Binary labels of shape (n_samples,). |
required |
p
|
array_like
|
Predicted probabilities of shape (n_samples,). |
required |
prob_kernel_width
|
float
|
Bandwidth for the RBF probability kernel. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The squared KCE estimate (an unbiased U-statistic, diagonal removed). |
Source code in kernel_calibration/metrics.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 | |
Plotting¶
kernel_calibration.plots.reliability_diagram ¶
reliability_diagram(y, p, n_bins=15, ax=None, label=None)
Plot a reliability diagram (accuracy vs. confidence per bin).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
array_like
|
Binary labels of shape (n_samples,). |
required |
p
|
array_like
|
Predicted probabilities of shape (n_samples,). |
required |
n_bins
|
int
|
Number of equal-width bins in [0, 1]. Default is 15. |
15
|
ax
|
Axes
|
Axes to draw on. A new figure/axes is created if omitted. |
None
|
label
|
str
|
Legend label for the model curve. |
None
|
Returns:
| Type | Description |
|---|---|
Axes
|
The axes containing the plot. |
Source code in kernel_calibration/plots.py
29 30 31 32 33 34 35 36 37 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 | |
kernel_calibration.plots.plot_local_calibration_bias ¶
plot_local_calibration_bias(feature, bias, ax=None, xlabel='feature')
Scatter the local calibration bias against a single feature.
Useful for the "where is the model miscalibrated" view: points far from zero mark regions of feature space where predictions are over- or under-confident.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
feature
|
array_like
|
A 1-D feature value per sample, shape (n_samples,). |
required |
bias
|
array_like
|
Local calibration bias per sample (e.g. the output of
:func: |
required |
ax
|
Axes
|
Axes to draw on. A new figure/axes is created if omitted. |
None
|
xlabel
|
str
|
Label for the feature axis. Default is "feature". |
'feature'
|
Returns:
| Type | Description |
|---|---|
Axes
|
The axes containing the plot. |
Source code in kernel_calibration/plots.py
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 104 105 106 107 108 | |
Example data¶
kernel_calibration.datasets.make_calibration_data ¶
make_calibration_data(n=1000, miscalibration=0.25, region_threshold=0.0, slope=1.5, seed=0)
Generate synthetic data with a planted local miscalibration.
A single feature x drives the true probability p_true = sigmoid(slope*x).
Labels are drawn as y ~ Bernoulli(p_true). The returned model probabilities
f equal p_true (locally calibrated) except where x >=
region_threshold, in which case the model is made over-confident by adding
miscalibration. Setting miscalibration=0 yields a perfectly locally
calibrated model — useful for a Type-I error check.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of samples. Default is 1000. |
1000
|
miscalibration
|
float
|
Size of the additive bias applied in the affected region. |
0.25
|
region_threshold
|
float
|
The model is miscalibrated where the feature |
0.0
|
slope
|
float
|
Steepness of the true probability as a function of |
1.5
|
seed
|
int
|
RNG seed. Default is 0. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
X |
ndarray
|
Feature matrix of shape (n, 1). |
y |
ndarray
|
Binary labels of shape (n,). |
f |
ndarray
|
Model predicted probabilities of shape (n,). |
Source code in kernel_calibration/datasets.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 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 | |
kernel_calibration.datasets.fetch_compas ¶
fetch_compas(cache_dir=None, filter_propublica=True)
Download the ProPublica COMPAS recidivism dataset (with local caching).
Requires pandas. On the first call the CSV is downloaded and cached; later
calls read the cached copy. Set the KERNEL_CALIBRATION_DATA environment
variable (or pass cache_dir) to control where it is stored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache_dir
|
str
|
Directory to cache the raw CSV. Defaults to |
None
|
filter_propublica
|
bool
|
Apply ProPublica's standard row filtering (screening-date window, valid recidivism flag, non-ordinary charge degree, non-missing score). Default True. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The (optionally filtered) COMPAS records. |
Source code in kernel_calibration/datasets.py
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 119 120 121 122 123 124 125 126 | |