API reference¶
Generated from the docstrings in the code.
pyconformal: conformal prediction for Python.
QuantileBooster
¶
Gradient-boosted quantile regression with CatBoost, XGBoost or LightGBM.
::
qb = QuantileBooster("catboost", levels=19, iterations=300)
cir = ConformalInterquantileRegressor(qb, alpha=0.1)
cir.fit(X_train, y_train).calibrate(X_cal, y_cal)
cir.predict_interval(X_test)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
library
|
('catboost', 'xgboost', 'lightgbm')
|
|
"catboost"
|
levels
|
int or array - like
|
Quantile levels to train. A number |
19
|
tail_holdout
|
float
|
Share of the training rows kept out of the boosting and used only to set the tails (levels 0 and 1, see below). Boosted models fit their training rows closely, so tails measured on those rows alone are too short, and CIR and CTI can then return infinite intervals. 0 uses the training rows themselves. |
0.1
|
**params
|
Passed to the library's regressor ( |
{}
|
|
The
|
|
required | |
of
|
|
required |
Attributes:
| Name | Type | Description |
|---|---|---|
levels_ |
ndarray
|
Trained levels, increasing. |
models_ |
list
|
The fitted library models (one, or one per level for LightGBM). |
tails_ |
(float, float)
|
Distances from the lowest and highest trained quantiles to levels 0 and 1. |
SplitConformalClassifier
¶
Bases: _Conformal
calibrate(X=None, y=None, *, proba=None, groups=None)
¶
Compute scores on data not used for training.
groups: a category per calibration sample, for one threshold per
category (Mondrian conformal prediction).
group_thresholds(alpha=None)
¶
Score threshold of each calibration category, as a dict.
thresholds(alpha=None)
¶
Score threshold, or one per class when class_conditional.
predict(X=None, *, proba=None)
¶
Most likely class.
predict_set(X=None, alpha=None, *, proba=None, groups=None)
¶
Prediction sets as a boolean array (n_samples, n_classes).
Entry [i, j] is True when classes_[j] is in the set for
sample i. alpha overrides the default level without
recalibrating; a list of levels gives shape
(n_samples, n_classes, n_levels), with the sets nested.
groups: the category of each sample; required if and only if
calibrate was given groups.
CrossConformalRegressor
¶
Bases: _Conformal
Jackknife+ and CV+ prediction intervals.
From a model::
cp = CrossConformalRegressor(model, alpha=0.1, cv=10)
cp.fit(X, y) # trains one model per fold and calibrates
cp.predict_interval(X_test)
From predictions, when the fold models were trained elsewhere::
cp = CrossConformalRegressor(alpha=0.1)
cp.calibrate(y_pred=oof, y=y, folds=fold_of_each_row)
cp.predict_interval(y_pred=fold_predictions) # (n_test, K), column k from model k
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
object or None
|
A regressor with |
None
|
alpha
|
float
|
|
0.1
|
cv
|
int or 'loo'
|
Number of folds. |
10
|
method
|
('plus', 'minmax')
|
|
"plus"
|
shuffle
|
bool
|
Assign rows to folds at random. Turn off only if the rows are already in random order. |
True
|
random_state
|
int or None
|
|
None
|
fit(X, y, **fit_params)
¶
Train one copy of the model without each fold, then calibrate on
the out-of-fold predictions. No separate calibrate call is
needed.
calibrate(X=None, y=None, *, y_pred=None, folds=None)
¶
Calibrate from out-of-fold predictions: y_pred[i] must come
from the model trained without row i, and folds[i] says which
model that is (0 .. K - 1). With an estimator, use fit.
predict(X=None, *, y_pred=None)
¶
Point prediction: the average of the fold models.
predict_interval(X=None, alpha=None, *, y_pred=None)
¶
Prediction intervals, shape (n_samples, 2), or (n_samples, 2, n_levels) for a list of levels.
ConformalDistributionRegressor
¶
Bases: _Conformal
Conformal balls around vector-valued predictions.
From predictions::
A_in, A_out = cosine_coefficients(X_samples), cosine_coefficients(Y_samples)
cd = ConformalDistributionRegressor(alpha=0.1)
cd.calibrate(y_pred=model.predict(A_in[cal]), y=A_out[cal])
centre, radius = cd.predict_ball(y_pred=model.predict(A_in[test]))
or from a model that maps input coefficients to output coefficients (any multi-output regressor)::
cd = ConformalDistributionRegressor(Ridge(), alpha=0.1)
cd.fit(A_in[train], A_out[train]).calibrate(A_in[cal], A_out[cal])
cd.predict_ball(A_in[test])
The score is the Euclidean distance between prediction and outcome. If
calibration and test cases are exchangeable, the ball contains the
outcome vector with probability at least 1 - alpha.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
object or None
|
A regressor whose |
None
|
alpha
|
float
|
|
0.1
|
weights
|
array-like of shape (n_outputs,) or None
|
Positive weight of each output in the score, which becomes
|
None
|
k_neighbors
|
int or None
|
None: one radius for all cases, with the guarantee above. A number
|
None
|
What
|
|
required | |
from
|
|
required | |
the
|
|
required |
calibrate(X=None, y=None, *, y_pred=None, features=None)
¶
Compute scores on cases not used for training. y holds the
observed outcome vectors, one row per case.
radius(X=None, alpha=None, *, features=None)
¶
Radius of the ball: one number, or one per case with
k_neighbors. Infinite when there are too few calibration cases
for alpha. A list of levels gives one radius per level (last
axis); the nearest neighbours are then found once for all levels.
predict(X=None, *, y_pred=None)
¶
The predicted vectors (centres of the balls).
predict_ball(X=None, alpha=None, *, y_pred=None, features=None)
¶
(centres, radii): centres of shape (n_samples, n_outputs) and one radius per case.
contains(y, X=None, alpha=None, *, y_pred=None, features=None)
¶
Whether each outcome vector lies in its ball.
log_volume(X=None, alpha=None, *, features=None)
¶
Natural logarithm of the volume of the set (Theorem 4.3 of the
paper): n/2 log(pi) + n log(radius) - lgamma(n/2 + 1) - 1/2
sum(log(weights)) for n outputs. One number, or one per case
with k_neighbors. Compare sets of the same n only.
predict_cdf_band(grid, X=None, alpha=None, *, y_pred=None, features=None, support=(0.0, 1.0))
¶
A band for the distribution function, for outcomes that are
cosine coefficients (see :func:cosine_coefficients).
Returns (lower, upper), each of shape (n_samples, n_grid). Every
coefficient vector in the ball has its (truncated-series)
distribution function between the two curves at every grid point at
once, and each bound is attained by some vector in the ball. So when
the ball contains the outcome, the band contains the outcome's
truncated-series distribution function everywhere: coverage of the
band is at least that of the ball. Read quantile bounds off the band
by inverting it. The curves are cut to [0, 1]; a truncated series
can stray slightly outside that range, so compare it after the same
cut.
ConformalSeasonalPool
¶
Conformal Seasonal Pool forecaster.
For each horizon, predictive samples are a blend of
- a seasonal pool: past values at the same seasonal phase, drawn with exponential recency weights, and
- a conformal component: a seasonal-naive point forecast plus a signed residual drawn from past seasonal-naive errors.
No training and no learned parameters. This is a forecasting heuristic built from conformal residuals; it does not carry a finite-sample coverage guarantee for dependent data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pool_weight
|
float
|
Share of samples drawn from the seasonal pool. |
0.5
|
exp_lambda
|
float
|
Recency-decay rate of the seasonal pool (0 for uniform weights). |
0.01
|
cal_fraction
|
float
|
Share of the history used as the residual calibration window. |
0.5
|
adaptive
|
bool
|
Drop the seasonal pool when there is no seasonality, and cap its weight at 0.3 when fewer than three full cycles are available. |
True
|
residual_mode
|
('h_step', 'paper')
|
|
"h_step"
|
orientation
|
bool
|
Push interval quantiles outward by the finite-sample correction
( |
False
|
decay_unit
|
('step', 'cycle')
|
Whether recency decay counts time steps or seasonal cycles. |
"step"
|
random_state
|
(int, Generator or None)
|
Seed or generator for the draws. |
None
|
fit(history, seasonal_period=1)
¶
Store the series (1-D, most recent value last) and its season length.
predict(H, alpha=0.05, quantile_levels=None, n_samples=100)
¶
Forecast H steps ahead.
Returns a :class:CSPResult with the central 1 - alpha interval,
the requested quantiles and the predictive samples.
CSPResult
dataclass
¶
Predictive distribution for an H-step forecast.
Attributes:
| Name | Type | Description |
|---|---|---|
lower, upper |
ndarray of shape (H,)
|
Bounds of the central |
quantiles |
dict
|
Maps each requested level to an array of shape (H,). |
samples |
ndarray of shape (H, n_samples)
|
Predictive draws per horizon. |
SPCI
¶
Bases: EnbPI
Sequential predictive conformal inference (SPCI).
Same ensemble and out-of-bag residuals as :class:EnbPI, but signed.
To predict step t, a quantile regression forest is fitted on pairs
(the past_window residuals before a point, the residual at that
point) and asked for the quantiles of the next residual given the latest
window. The interval is [centre + Q(beta), centre + Q(1 - alpha +
beta)], with beta in [0, alpha] chosen to make it narrowest,
so it can be asymmetric.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
as in EnbPI
|
|
None
|
alpha
|
as in EnbPI
|
|
None
|
n_bootstraps
|
as in EnbPI
|
|
None
|
random_state
|
as in EnbPI
|
|
None
|
past_window
|
int or None
|
Residuals used as inputs. Default: a tenth of the training residuals, between 5 and 100. |
None
|
beta_bins
|
int
|
Values of |
5
|
refit_every
|
int
|
Refit the forest after this many new observations. 1 follows the paper; larger values are faster. |
1
|
n_estimators
|
int
|
Trees in the quantile forest. |
20
|
min_samples_leaf
|
int
|
|
5
|
Uses
|
|
required |
predict_interval(X=None, alpha=None, *, y_pred=None)
¶
Interval for the next step. Every row passed is treated as the
next step, with the residuals known now; for a stream use run.
run(X=None, y=None, *, y_pred=None)
¶
Predict a stream one step at a time, adding each new residual before the next step.
EnbPI
¶
Bases: _Conformal
Ensemble batch prediction intervals (EnbPI).
From a model::
enb = EnbPI(model, alpha=0.1, n_bootstraps=30)
enb.fit(X_train, y_train) # trains the ensemble and calibrates
result = enb.run(X_test, y_test) # one step at a time, residuals sliding
result.intervals
or step by step with predict_interval(X_next) and
update(X_next, y_next).
From predictions, when the ensemble was trained elsewhere: calibrate(
y_pred=member_predictions, y=y, in_bag=in_bag) with one column per
ensemble member, then pass member predictions (n, B) as y_pred=.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
object or None
|
A regressor with |
None
|
alpha
|
float
|
|
0.1
|
n_bootstraps
|
int
|
Members to train. Every residual must come from members that did
not see that row, so if some rows are in every bootstrap sample,
|
30
|
batch_size
|
int
|
In |
1
|
random_state
|
int or None
|
|
None
|
The
|
|
required | |
the
|
|
required | |
never
|
|
required |
fit(X, y, **fit_params)
¶
Train the bootstrap ensemble and compute out-of-bag residuals.
No separate calibrate call is needed.
calibrate(X=None, y=None, *, y_pred=None, in_bag=None)
¶
Residuals from member predictions on the training rows:
y_pred[i, b] is member b's prediction for row i and
in_bag[i, b] says whether member b was trained on row i.
Each residual uses only the members that did not see that row. A
row that every member saw has no such prediction and is left out of
the residuals (EnbPI; their number is n_starved_) or is an error
(SPCI, whose residuals must be consecutive in time).
predict(X=None, *, y_pred=None)
¶
Point prediction: the mean of the ensemble.
predict_interval(X=None, alpha=None, *, y_pred=None)
¶
Intervals from the current residuals, shape (n_samples, 2), or (n_samples, 2, n_levels) for a list of levels.
update(X=None, y=None, *, y_pred=None)
¶
Add the residuals of newly observed outcomes and drop as many of the oldest ones.
run(X=None, y=None, *, y_pred=None)
¶
Predict a stream one step at a time, refreshing the residuals
after every batch_size observations. Leaves the object as if
update had been called for the whole stream.
EnsembleResult
dataclass
¶
Result of replaying a stream: intervals (T, 2), predictions
(T,), errors (T,) and the overall coverage.
QuantileForest
¶
Quantile regression forest.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_estimators
|
int
|
|
100
|
min_samples_leaf
|
int
|
|
5
|
max_features
|
float or int
|
Features tried at each split: a fraction of all features, or a count. |
1/3
|
max_depth
|
int or None
|
|
None
|
bootstrap
|
bool
|
Draw each tree's sample with replacement. |
True
|
max_samples
|
(float, int or None)
|
Size of each tree's sample (fraction or count). Default: all rows. |
None
|
max_bins
|
int
|
Levels each feature is binned into (at most 256). |
256
|
max_samples_leaf
|
None or 1
|
None keeps every training outcome of a leaf, which gives the exact quantile regression forest. 1 keeps one outcome per leaf, drawn at random: an approximation that predicts faster and is a little less accurate (the default of the quantile-forest package). |
None
|
random_state
|
int or None
|
Results for a given seed do not depend on the number of threads. |
None
|
Use
|
|
required | |
conditional
|
|
required | |
weighted
|
|
required | |
level
|
|
required |
predict(X, quantiles=None)
¶
Conditional mean (quantiles=None) or conditional quantiles.
predict_oob(quantiles=None)
¶
Out-of-bag predictions for the training rows, in training order.
Each row is predicted only by the trees whose sample did not contain
it, so the result behaves like a prediction on unseen data and can
be used to calibrate without setting data aside. Needs
bootstrap=True or max_samples below the number of rows.
AcMCP
¶
Autocorrelated multi-step conformal prediction (Wang and Hyndman).
An online method: for each horizon the half-widths of the interval are tracked from past misses, with three parts added together.
- Quantile tracking: widen after a miss, narrow after a hit, with a step proportional to the range of the errors seen.
- An integrator that pushes harder the longer coverage stays off target.
- A scorecaster that forecasts the next error. It uses the fact that the errors of an optimal h-step forecast are at most MA(h - 1): the forecast is the average of the mean of an MA(h - 1) model and a regression of the h-step error on the shorter horizons.
Use it like :class:MultiStepSplitConformal::
ac = AcMCP(alpha=0.1, min_calibration=50)
result = ac.run(y_pred=F, y=y)
ac.predict_interval(y_pred=next_H)
Forecasts may be missing (NaN) only in the first rows of each column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha
|
float
|
Each end of the interval is tracked at |
0.1
|
min_calibration
|
int
|
Intervals and scorecasts start once a horizon has this many errors. |
10
|
window
|
int or None
|
Learning rate, MA model and regression use only the most recent
|
None
|
integrate
|
bool
|
|
True
|
scorecast
|
bool
|
|
True
|
lr
|
float
|
|
0.1
|
KI
|
float or None
|
Scale of the integrator. None uses the largest absolute error seen so far at that horizon. (The R package's default is the largest absolute error of the whole history, which includes errors that are not yet known at the time; pass that number to reproduce it.) |
None
|
Csat
|
float or None
|
Integrator saturation. None uses the formula of the conformal PID
paper with the length of the history passed to |
None
|
delta
|
float
|
|
0.01
|
refit_every
|
int
|
Refit the MA model every this many steps. 1 follows the R package. |
1
|
The
|
|
required | |
the
|
|
required | |
tighter
|
|
required |
Reference
Wang and Hyndman (2024), arXiv:2410.13115.
run(X=None, y=None, *, y_pred=None, alpha=None)
¶
Intervals for every target time of a history; the interval for
time t at horizon h uses only what was known at t - h.
predict_interval(X=None, *, y_pred=None)
¶
Intervals for the next H steps after the history, shape (H, 2),
at the level used in run.
MultiStepResult
dataclass
¶
intervals[t, h - 1] is (lower, upper) for target time t from
the h-step forecast; NaN where there was no forecast or too little
calibration data. errors marks the targets that fell outside.
coverage
property
¶
Coverage per horizon, over the targets that had an interval.
MultiStepSplitConformal
¶
Multi-step split conformal prediction (MSCP).
Works on forecasts and outcomes, so it fits any forecaster::
ms = MultiStepSplitConformal(alpha=0.1)
result = ms.run(y_pred=F, y=y) # replay a history
result.intervals # (T, H, 2)
ms.predict_interval(y_pred=next_H) # the H steps after the history
F[t, h - 1] is the forecast for time t made h steps earlier
(NaN where no such forecast exists, as in the first rows).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha
|
float
|
|
0.1
|
symmetric
|
bool
|
False: the lower and upper ends are calibrated separately, each at
|
False
|
window
|
int or None
|
Use only the most recent |
None
|
min_calibration
|
int
|
No interval is issued for a horizon until this many of its errors are known. |
10
|
Under
|
|
required | |
the
|
|
required |
run(X=None, y=None, *, y_pred=None, alpha=None)
¶
Intervals for every target time of a history. The interval for
time t at horizon h uses the h-step errors of targets up to
t - h only: what was known when the forecast was made. Afterwards
the object holds all errors, ready for predict_interval.
calibrate(X=None, y=None, *, y_pred=None)
¶
Store the errors of a history without computing its intervals.
predict_interval(X=None, alpha=None, *, y_pred=None)
¶
Intervals for the next H steps after the history, shape
(H, 2): row h - 1 is the h-step forecast y_pred[h - 1],
calibrated on every h-step error seen so far.
ACIResult
dataclass
¶
Output of replaying a stream.
Attributes:
| Name | Type | Description |
|---|---|---|
thresholds |
ndarray of shape (T,)
|
Score threshold used at each step, fixed before that step's outcome
was seen. |
errors |
ndarray of bool, shape (T,)
|
True where the observed score exceeded the threshold (a miss). |
alphas |
ndarray of shape (T,)
|
Working miscoverage level used at each step. |
intervals |
ndarray of shape (T, 2) or None
|
Lower and upper bounds, when predictions were supplied. An empty set
is the row |
AdaptiveConformalInference
¶
Bases: _Conformal
Adaptive conformal inference (Gibbs and Candes, 2021).
Split conformal prediction with a miscoverage level that reacts to past
errors. At each step the threshold is the conformal quantile of the
current calibration scores at the working level alpha_t; after the
outcome is seen,
alpha_{t+1} = alpha_t + gamma * (alpha - err_t),
where err_t is 1 for a miss and 0 otherwise, and the new score joins
the calibration set.
Guarantee (no assumption on the data, not even exchangeability): over
any T steps the average miss rate differs from alpha by at most
(max(alpha_1, 1 - alpha_1) + gamma) / (gamma * T). This holds because
the working level is not clipped: when alpha_t <= 0 the interval is
infinite, and when alpha_t >= 1 the prediction set is empty.
Works on nonconformity scores (scores=), on predictions and
outcomes (y_pred=, y=; the score is the absolute error), or on a
model (X, y). The model is called once per batch, never inside
the update loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
object or None
|
A model with |
None
|
alpha
|
float
|
Target miscoverage level. |
0.1
|
gamma
|
float
|
Step size. 0 gives plain online split conformal. Larger values adapt faster but make the intervals less stable. |
0.005
|
window
|
int or None
|
Keep only the most recent |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
alpha_t_ |
float
|
Current working level. |
calibrate(X=None, y=None, *, y_pred=None, scores=None)
¶
Start from an initial calibration set. Calling it with no arguments starts from nothing.
Resets the working level to alpha.
threshold()
¶
Score threshold for the next step.
update(X=None, y=None, *, y_pred=None, score=None)
¶
Observe the step just predicted: its score, or its prediction and outcome. Returns True on a miss.
run(X=None, y=None, *, y_pred=None, scores=None, use_numba=None)
¶
Replay a whole stream in one call.
Equivalent to calling threshold() then update(...) for each
step in turn, and leaves the object in the same state, but runs in
O(log n) per step. With predictions, the result also carries the
intervals y_pred -/+ threshold; the interval at step t uses
only outcomes before t.
predict_interval(X=None, *, y_pred=None)
¶
Interval(s) for the next step, shape (n, 2).
Uses the absolute-error score: y_pred -/+ threshold. When the
threshold is negative the prediction set is empty and the row is
(nan, nan).
AgACI
¶
Bases: AdaptiveConformalInference
Aggregated adaptive conformal inference (Zaffran et al., 2022).
Runs ACI with many step sizes and combines the thresholds they propose, with weights learned online by Bernstein online aggregation (BOA) on the pinball loss. Where DtACI combines working levels, AgACI combines the thresholds themselves, which is steadier when some experts ask for infinite intervals. There is no step size to choose.
Works on scores (for intervals, the absolute error), so one threshold is
aggregated at pinball level 1 - alpha; the paper aggregates the lower
and upper bounds separately, which is the same thing for symmetric
intervals. An expert that asks for an infinite threshold is counted at
the largest score seen so far.
Same calls as :class:AdaptiveConformalInference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
object or None
|
|
None
|
alpha
|
float
|
|
0.1
|
gammas
|
sequence of float or None
|
Step sizes of the experts. Default: the paper's 30 values from 0 to 0.09. |
None
|
window
|
int or None
|
|
None
|
References
Zaffran, Feron, Goude, Josse and Dieuleveut (2022). Adaptive conformal predictions for time series. ICML.
Wintenberger (2017). Optimal learning with Bernstein online aggregation. Machine Learning 106.
ConformalPID
¶
Bases: AdaptiveConformalInference
Conformal PID control (Angelopoulos, Candes and Tibshirani, 2023): quantile tracking, with an optional integrator.
The threshold itself is moved, not a working level: up by
lr * (1 - alpha) after a miss and down by lr * alpha after a
cover (the P term, "quantile tracking"). On its own this never asks for
an infinite interval and needs no stored scores. With KI > 0 an
integrator adds a correction that grows with the running coverage error
(the I term) and can become infinite when coverage has drifted far.
The D term of the paper, a forecast of the next score, is not included;
forecast the scores yourself and add the forecast to the threshold.
Long-run coverage converges to 1 - alpha for any sequence with
bounded scores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
object or None
|
|
None
|
alpha
|
float
|
|
0.1
|
lr
|
float
|
Step size. With |
0.1
|
KI
|
float
|
Integrator gain; 0 turns the integrator off. |
0.0
|
Csat
|
float
|
Integrator saturation constant. |
1.0
|
burn_in
|
int
|
|
100
|
proportional_lr
|
bool
|
|
True
|
the
|
|
required |
DtACI
¶
Bases: AdaptiveConformalInference
Dynamically-tuned adaptive conformal inference (Gibbs and Candes, 2022).
ACI needs a step size gamma, and the right value depends on how fast
the data drift. DtACI runs ACI with several step sizes at once and
combines their working levels with weights that follow which step size
has been doing best lately. There is no step size to choose.
Same calls as :class:AdaptiveConformalInference. With a single step
size it gives exactly the same results as ACI.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
object or None
|
|
None
|
alpha
|
float
|
|
0.1
|
gammas
|
sequence of float or None
|
Candidate step sizes. Default: 0.001, 0.002, 0.004, ..., 0.128. |
None
|
interval
|
int
|
Length of the stretch over which the method should adapt; sets how
fast the weights move (the paper's |
500
|
window
|
int or None
|
Keep only the most recent scores. |
None
|
Reference
Gibbs and Candes (2022). Conformal inference for online prediction with arbitrary distribution shifts. arXiv:2208.08401.
NonexchangeableConformal
¶
Bases: AdaptiveConformalInference
Non-exchangeable conformal prediction with recency weights (NexCP; Barber, Candes, Ramdas and Tibshirani, 2023).
Recent scores count more: the score seen d steps ago has weight
rho ** d. The threshold is the weighted 1 - alpha quantile of
the past scores, with the point being predicted counted at +infinity.
Under drift, old data lose their say gradually, without a hard window.
The coverage gap is bounded by how much the data distribution moves,
weighted the same way; with rho=1 this is split conformal
prediction on all past scores.
Same calls as :class:AdaptiveConformalInference (calibrate,
run, threshold, update, predict_interval).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
object or None
|
|
None
|
alpha
|
float
|
|
0.1
|
rho
|
float in (0, 1]
|
Decay per step. |
0.99
|
Reference
Barber, Candes, Ramdas and Tibshirani (2023). Conformal prediction beyond exchangeability. Annals of Statistics 51(2), 816-845.
ConformalPredictiveSystem
¶
Bases: _Conformal
calibrate(X=None, y=None, *, y_pred=None, sigma=None, groups=None)
¶
Calibrate on data not used to train the model.
predict_quantile(X=None, q=0.5, *, y_pred=None, sigma=None, groups=None, side='higher')
¶
Quantiles of the predictive distributions.
side="lower" returns C_(floor(q (n + 1))) and side="higher"
returns C_(ceil(q (n + 1))), with C_(0) = -inf and
C_(n + 1) = +inf. The two differ by at most one calibration score;
use "lower" for lower bounds and "higher" for upper bounds to keep the
coverage guarantee.
Returns an array of shape (n_samples, n_quantiles), or (n_samples,)
when q is a single number.
predict_interval(X=None, alpha=None, *, y_pred=None, sigma=None, groups=None)
¶
Central prediction intervals of shape (n_samples, 2).
Covers with probability at least 1 - alpha. A bound is infinite
when the calibration set (of that group) has fewer than
2 / alpha - 1 points.
predict_cdf(X=None, y=None, *, y_pred=None, sigma=None, groups=None, tau=0.5)
¶
Value Q(y, tau) of each predictive distribution at y.
y is one threshold per sample, or a single number for all.
tau is a number or an array in [0, 1]. Pass uniform random numbers
to get exactly uniform values at the true outcomes; the default 0.5
is the deterministic midpoint. A missing threshold (NaN) gives NaN;
-inf and inf give the values at the two ends.
predict_distribution(X=None, *, y_pred=None, sigma=None)
¶
Support points C_1 <= ... <= C_n of each distribution, as an
array of shape (n_samples, n_calibration). Not available for Mondrian
systems, whose groups can differ in size.
crps(X=None, y=None, *, y_pred=None, sigma=None, groups=None)
¶
Continuous ranked probability score per sample (lower is better).
Scores the distribution that puts mass 1 / n on each support
point (not the randomised distribution Q(y, tau)). Computed in
closed form from prefix sums, in O(log n) per sample, without
building the distributions. A missing outcome (NaN) gives NaN.
ConformalInterquantileRegressor
¶
Bases: _Interquantile
Conformal interquantile regression (CIR and CIR+; Guo, Luo and Zhou, 2026).
For each sample a window starts at the shortest interquantile interval
(the estimated mode) and grows one interval at a time, always taking the
shorter neighbour. The score of a calibration point is the number of
intervals the window needs to reach its outcome. The prediction interval
for a new sample is its window after k steps, where k is the
conformal quantile of the calibration scores. The result is one
interval that leans towards the dense side of a skewed distribution,
which equal-tailed CQR cannot do.
With plus=True (CIR+) the score also carries the relative length of
the last interval added, so the final step is taken only for samples
where it is cheap. Intervals get slightly shorter.
Coverage is at least 1 - alpha under exchangeability. Two details
are fixed here so that this holds exactly:
- The prediction interval is built with the same growing rule as the
score. The paper's formula instead takes the shortest run of
kconsecutive intervals, which is not always the same window;window="shortest"gives that variant. It is there to reproduce the authors' code and has no coverage guarantee: on a two-mode outcome it covered 88% at a 90% target, and on a simple example with exchangeable data it can cover 0% (calibration counts steps along one sequence of windows, prediction can pick a different window of the same length). It warns when used. - For CIR+ the added length is divided by the sample's full predicted range, and the extra step is taken when the resulting score is at most the threshold. The authors' code divides by 100 times the largest calibration outcome instead, which depends on the units and sign of the outcome.
window="shortest" returns the same intervals as the authors' code
(github.com/orince/CIR) when the calibration size is such that the two
rank rules agree; their rank is one higher when (1 - alpha) * (n + 1)
is a whole number.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
quantile model or None
|
A model whose |
None
|
alpha
|
float
|
|
0.1
|
plus
|
bool
|
Use CIR+. |
False
|
window
|
('greedy', 'shortest')
|
"greedy" carries the coverage guarantee. "shortest" reproduces the authors' code, without it. |
"greedy"
|
quantile_levels
|
(int, array - like or None)
|
Levels asked from the model: an array, or a number K for K equal parts. Default: 100 equal parts (levels 0, 0.01, ..., 1). |
None
|
calibrate(X=None, y=None, *, quantiles=None)
¶
Compute scores on data not used for training.
threshold(alpha=None)
¶
Conformal quantile of the calibration scores. For CIR this is the number of interquantile intervals in every prediction interval.
predict_interval(X=None, alpha=None, *, quantiles=None)
¶
Prediction intervals, shape (n_samples, 2), or
(n_samples, 2, n_levels) for a list of levels. Bounds are infinite
when the calibration set is too small for alpha or too many
calibration outcomes lie beyond the predicted quantiles.
ConformalizedQuantileRegressor
¶
Bases: _QuantileBased
Conformalized quantile regression (CQR).
Starts from a predicted lower and upper quantile and shifts both by a constant found on the calibration set. Interval width follows the quantile model, so it adapts to how uncertain each sample is.
From predictions::
cqr = ConformalizedQuantileRegressor(alpha=0.1)
cqr.calibrate(quantiles=q_cal, y=y_cal) # q_cal: (n, 2) lower, upper
cqr.predict_interval(quantiles=q_test)
From a model: pass a pair (lower_model, upper_model), or one model
whose predict(X, quantiles=[...]) returns one column per level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
pair of models, quantile model or None
|
|
None
|
alpha
|
float
|
Default miscoverage level. |
0.1
|
symmetric
|
bool
|
True: one correction for both ends (Romano et al.), from the score
|
True
|
quantile_levels
|
(float, float) or None
|
Levels asked from a single quantile model. Default
|
None
|
calibrate(X=None, y=None, *, quantiles=None)
¶
Compute scores on data not used for training.
corrections(alpha=None)
¶
(lower, upper) amounts by which the two quantiles are moved outwards. Negative values move them inwards.
predict_interval(X=None, alpha=None, *, quantiles=None)
¶
Prediction intervals, shape (n_samples, 2), or (n_samples, 2, n_levels) for a list of levels.
When a correction is negative and the two ends cross, the interval collapses to the crossing midpoint.
ConformalThresholdedIntervals
¶
Bases: _Interquantile
Conformal thresholded intervals (CTI; Luo and Zhou, 2025).
Each interquantile interval holds about the same probability, so a short one means high density. CTI keeps every interval whose length is at most a threshold found on the calibration set, which aims for the smallest possible prediction set. The set can be a union of separate intervals, for example for a bimodal outcome.
The score of a calibration point is the length of the interval its outcome falls in; outcomes beyond the lowest or highest predicted quantile fall in a tail of infinite length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
quantile model or None
|
A model whose |
None
|
alpha
|
float
|
|
0.1
|
quantile_levels
|
(int, array - like or None)
|
Levels asked from the model: an array, or a number K for K equal parts. Default: 100 equal parts (levels 0, 0.01, ..., 1). |
None
|
calibrate(X=None, y=None, *, quantiles=None)
¶
Compute scores on data not used for training.
threshold(alpha=None)
¶
Longest interquantile interval that is kept.
predict_set(X=None, alpha=None, *, quantiles=None)
¶
Which intervals are in the prediction set: a boolean array of shape (n_samples, K + 2). Column 0 is the lower tail, columns 1..K the interquantile intervals, column K + 1 the upper tail. A list of levels adds a last axis.
predict_size(X=None, alpha=None, *, quantiles=None)
¶
Total length of the prediction set per sample, shape (n_samples,).
predict_interval(X=None, alpha=None, *, quantiles=None)
¶
Smallest single interval containing the prediction set, shape (n_samples, 2). It covers at least as often as the set, but can be much wider when the set has gaps. Rows are NaN when the set is empty.
SplitConformalRegressor
¶
Bases: _Conformal
Split (inductive) conformal prediction intervals for regression.
The nonconformity score is the absolute residual |y - y_pred| on a
held-out calibration set. Intervals are y_pred +/- q, where q is
the finite-sample conformal quantile of the calibration scores.
If the calibration and test data are exchangeable, a new interval
contains the true value with probability at least 1 - alpha
(marginal coverage). Intervals have the same width for every input,
unless one of the three options below is used. They are given at
calibrate and again at predict_interval:
sigma: a positive difficulty estimate per sample (normalized conformal prediction). Scores become|y - y_pred| / sigmaand intervalsy_pred +/- q * sigma, wider where the model is less sure.groups: a category per sample (Mondrian conformal prediction). Each category gets its own threshold, so coverage holds within every category.weights: for covariate shift (Tibshirani et al., 2019). Each sample's weight is how much more likely its inputs are under the test distribution than under the calibration distribution. Coverage then holds on the shifted test distribution, if the weights are right.
Works from predictions::
cp = SplitConformalRegressor(alpha=0.1)
cp.calibrate(y_pred=pred_cal, y=y_cal)
cp.predict_interval(y_pred=pred_test)
or from a model::
cp = SplitConformalRegressor(model, alpha=0.1)
cp.fit(X_train, y_train) # skip if already trained
cp.calibrate(X_cal, y_cal)
cp.predict_interval(X_test)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
object or None
|
A regressor with |
None
|
alpha
|
float
|
Default miscoverage level; 0.1 gives 90% intervals. |
0.1
|
calibrate(X=None, y=None, *, y_pred=None, sigma=None, groups=None, weights=None)
¶
Compute scores on data not used for training.
predict(X)
¶
Point predictions from the underlying regressor.
threshold(alpha=None)
¶
Half-width of the interval at level alpha (in units of
sigma for normalized intervals). Not defined with groups or
weights, where it differs between samples.
predict_interval(X=None, alpha=None, *, y_pred=None, sigma=None, groups=None, weights=None)
¶
Prediction intervals, shape (n_samples, 2): lower and upper bound.
alpha overrides the default level without recalibrating. A list
of levels gives shape (n_samples, 2, n_levels). Bounds are infinite
when the calibration set (or the sample's group) is too small for
alpha.
APS
¶
Bases: _Score
Adaptive prediction sets: cumulative probability down to the class. Sets adapt to how hard each sample is.
LAC
¶
Bases: _Score
One minus the probability of the class. Smallest sets on average; sets can be empty.
RAPS
¶
Bases: APS
Regularised APS: adds penalty for every rank beyond k_reg,
which keeps unlikely classes out and makes sets smaller and more stable.
SAPS
¶
Bases: _Score
Sorted APS: uses only the top probability and the rank, so the score does not depend on the (often unreliable) tail probabilities.
CrossVennAbers
¶
Bases: _Conformal
Cross Venn-Abers calibration (CVAP; Vovk and Petej, 2014) for binary classification.
Inductive Venn-Abers sets data aside for calibration. The cross version uses every row: the data are cut into K folds, a model is trained without each fold and calibrated on it, and the K calibrated answers for a new sample are merged. Probabilities are usually a little sharper than with one split, at the cost of training K models.
From a model::
cva = CrossVennAbers(classifier, cv=5)
cva.fit(X, y) # trains and calibrates
cva.predict_proba(X_test)
From scores, when the fold models were trained elsewhere::
cva = CrossVennAbers()
cva.calibrate(scores=oof_scores, y=y, folds=fold_of_each_row)
cva.predict_proba(scores=test_scores) # (n_test, K), column k from model k
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
object or None
|
A binary classifier with |
None
|
cv
|
int
|
|
5
|
merge
|
('log', 'brier')
|
How the K pairs (p0, p1) become one probability: geometric means (best for log loss) or the Brier-optimal formula. |
"log"
|
shuffle
|
bool
|
|
True
|
random_state
|
int or None
|
|
None
|
Reference
Vovk and Petej (2014). Venn-Abers predictors. UAI. Vovk, Petej and Fedorova (2015). Large-scale probabilistic predictors with and without guarantees of validity. NeurIPS.
fit(X, y, **fit_params)
¶
Train one copy of the model without each fold and calibrate it on
that fold. No separate calibrate call is needed.
calibrate(X=None, y=None, *, scores=None, folds=None, classes=None, use_numba=None)
¶
Calibrate from out-of-fold scores: scores[i] must come from
the model trained without row i, and folds[i] says which
model that is (0 .. K - 1). y is boolean, or holds two labels
(the larger one is the positive class unless classes is given).
predict_pairs(X=None, *, scores=None)
¶
The Venn-Abers pair from every fold, shape (n_samples, K, 2):
[..., 0] is p0 and [..., 1] is p1.
predict_proba(X=None, *, scores=None)
¶
Calibrated probabilities, shape (n_samples, 2), columns ordered
as classes_.
predict(X=None, *, scores=None)
¶
Class with the higher calibrated probability.
VennAbers
¶
Bases: _Conformal
calibrate(X=None, y=None, *, proba=None, scores=None, use_numba=None)
¶
Calibrate on data not used for training.
predict_proba(X=None, *, proba=None, scores=None)
¶
Calibrated class probabilities, columns ordered as classes_.
predict_p0_p1(X=None, *, proba=None, scores=None)
¶
Binary problems only: the pair (p0, p1) for classes_[1],
shape (n_samples, 2).
predict(X=None, *, proba=None, scores=None)
¶
Class with the highest calibrated probability.
PanelResult
dataclass
¶
Outcome of :meth:WeightedTQA.run.
Attributes:
| Name | Type | Description |
|---|---|---|
thresholds |
ndarray(n_rounds, n_targets)
|
Score threshold of each prediction set. |
covered |
ndarray of bool (n_rounds, n_targets)
|
Whether the target's outcome fell in its set. Evaluated on every round, revealed or not. |
alphas |
ndarray(n_rounds, n_targets)
|
The adaptive level at each round, before any finitization. |
fallback |
ndarray of bool (n_rounds, n_targets)
|
Rounds where the level was below the target's own weight, so the
set is the largest calibration score ( |
intervals |
ndarray(n_rounds, n_targets, 2) or None
|
|
WeightedTQA
¶
W-TQA for panel data (Tu and Giesecke, 2026); TQA as a special case.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha
|
float
|
Target miscoverage, 0.1 for 90% sets. |
0.1
|
bandwidth
|
float
|
Kernel bandwidth |
0.6
|
gamma
|
float
|
Step size of the level update. |
0.01
|
finite
|
bool
|
When the level falls below the target's own weight the exact
threshold is infinite. |
False
|
Notes
Each target is handled on its own: its own weights and its own level. Past data enter only through the running feature means and the level, so memory does not grow with the number of rounds.
The cross-sectional standard deviation that scales each feature is taken
over the calibration units and the target, with divisor n (the
paper does not say which divisor it uses).
Guarantee: on the rounds where the outcome is revealed, the average
miss rate equals alpha + (alpha - alpha_final) / (gamma * n_revealed)
exactly (Proposition 5.5). With finite=False the level cannot fall
below -gamma (1 - alpha), so that miss rate is at most
alpha + (alpha + gamma (1 - alpha)) / (gamma * n_revealed) for any
data. Without assumptions linking the target to its peers, no method
can guarantee coverage at every round.
Examples:
>>> tqa = WeightedTQA(alpha=0.1)
>>> res = tqa.run(y_pred_cal=P_cal, y_cal=Y_cal, X_cal=X_cal,
... y_pred_target=P_tgt, y_target=Y_tgt, X_target=X_tgt)
>>> res.intervals.shape # (n_rounds, n_targets, 2)
start(n_cal, n_targets=1, n_features=0)
¶
Reset the state for a panel of n_cal calibration units.
weights()
¶
Current normalized weights, shape (n_targets, n_cal + 1); the last column is the target's own weight.
threshold(scores_cal)
¶
Thresholds for the current round from this round's calibration
scores (length n_cal; nan marks a unit with no outcome this
round). Returns (thresholds, fallback), each of length
n_targets.
update(X_cal=None, X_target=None, missed=None)
¶
Close the round: update the running feature means and, for the targets whose outcome was revealed, the level.
missed: per target, True/False if the outcome was
revealed and missed/covered, None or nan if not revealed.
run(*, scores_cal=None, scores_target=None, X_cal=None, X_target=None, revealed=None, y_pred_cal=None, y_cal=None, y_pred_target=None, y_target=None)
¶
Replay a panel.
Give either scores (scores_cal of shape (n_rounds, n_cal) and
scores_target of shape (n_rounds, n_targets)), or predictions
and outcomes, from which absolute-residual scores are formed.
X_cal (n_rounds, n_cal, n_features) and X_target (n_rounds,
n_targets, n_features) feed the similarity weights; leave them out
for equal weights. revealed: bool, (n_rounds,) or (n_rounds,
n_targets); True where the target's outcome becomes known
before the next round. Default: always.
conformal_quantile(scores, alpha, *, allow_inf=False)
¶
Return the split-conformal threshold for nonconformity scores.
The threshold is the k-th smallest calibration score, where
k = ceil((n + 1) * (1 - alpha)) and n is the number of scores.
If the calibration data and a test point are exchangeable, the test
point's score is at most this threshold with probability at least
1 - alpha.
If k > n (too few calibration points for the requested alpha),
the threshold is inf: no finite threshold gives the guarantee.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
array-like of shape (n,)
|
Nonconformity scores computed on the calibration set. |
required |
alpha
|
float
|
Miscoverage level, strictly between 0 and 1. |
required |
Returns:
| Type | Description |
|---|---|
float
|
|
cosine_cdf(coefficients, grid, support=(0.0, 1.0))
¶
Distribution function of the truncated cosine series at the points
grid: shape (n_distributions, n_grid).
cosine_coefficients(samples, n_terms=10, support=(0.0, 1.0))
¶
Cosine-series coefficients of distributions seen through samples.
With the sample rescaled from support to [0, 1], coefficient k
(k = 1 .. n_terms) is the sample mean of sqrt(2) * cos(pi * k * x).
The constant term is always 1 and is left out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
samples
|
array of shape (n_distributions, n_points), a 1-D array for one
|
distribution, or a list of 1-D arrays of different lengths |
required |
n_terms
|
int
|
|
10
|
support
|
(low, high)
|
Interval that contains the data. Values outside it are an error. |
(0.0, 1.0)
|
Returns:
| Type | Description |
|---|---|
ndarray of shape (n_distributions, n_terms)
|
|
cosine_density(coefficients, grid, support=(0.0, 1.0))
¶
Density of the truncated cosine series at grid: shape
(n_distributions, n_grid). A truncated series can dip below zero.
stl(y, period, seasonal=7, trend=None, low_pass=None, seasonal_deg=0, trend_deg=1, low_pass_deg=1, seasonal_jump=None, trend_jump=None, low_pass_jump=None, inner_iter=2)
¶
Seasonal-trend decomposition by loess (no robustness iterations).
Windows must be odd. Defaults are those of R's stl: local constant
seasonal fit, trend window nextodd(ceil(1.5 * period / (1 - 1.5 /
seasonal))), low-pass window nextodd(period), and jumps of
ceil(window / 10). Set the three jumps to 1 to evaluate every point.