calpit.estimator
CalPIT: diagnose and recalibrate conditional density estimates, scikit-learn style.
Attributes
Exceptions
CalPIT was used before it was fitted, as in scikit-learn. |
Classes
Diagnoses and recalibrates conditional density estimates (CDEs) with Cal-PIT. |
Functions
|
|
|
Module Contents
- _TORCH_ONLY_PARAMS = ('val_fraction', 'n_alpha_val', 'oversample', 'batch_size', 'max_epochs', 'lr', 'weight_decay',...[source]
- exception NotFittedError[source]
Bases:
ValueError,AttributeErrorCalPIT was used before it was fitted, as in scikit-learn.
- class CalPIT(model: Any = None, *, rearrange: bool = True, val_fraction: float = 0.1, n_alpha_val: int = 201, oversample: float = 1, batch_size: int = 2048, predict_batch_size: int = 2048, max_epochs: int = 1000, lr: float = 0.001, weight_decay: float = 1e-05, lr_decay: float = 0.99, patience: int = 20, num_workers: int = 0, trainer_kwargs: collections.abc.Mapping[str, Any] | None = None, n_alpha: int = 50, random_state: int | None = DEFAULT_RANDOM_STATE, verbose: bool = False)[source]
Diagnoses and recalibrates conditional density estimates (CDEs) with Cal-PIT.
Cal-PIT learns r(alpha; x) = P(PIT <= alpha | x), the conditional CDF of the probability integral transform, by regressing the indicator PIT <= alpha on (alpha, x) over a calibration set. Its predictions give local P-P plots that diagnose the CDEs at any x (predict, diagnose), and recalibrate them by composing each CDF with r (transform).
The model can be a PyTorch network, trained with PyTorch Lightning, or a scikit-learn classifier. A network follows the contract in calpit.nn.models: forward(alpha, x) returns the logit of r, or r itself if its output attribute is “probability”. A classifier is fitted on rows [alpha, x] with n_alpha stratified alpha per object (calpit.coverage).
The estimator follows the scikit-learn API: the constructor only stores its arguments, get_params and set_params work with sklearn.base.clone, fit returns the estimator, and what fit learns ends in an underscore. The model passed in is copied, never trained in place.
- Parameters:
model – A torch.nn.Module; a callable that takes n_features and returns one, such as functools.partial(calpit.nn.MLP, hidden_layers=[64, 64]); a scikit-learn classifier with predict_proba; or None for calpit.nn.IsplineNN(n_features).
rearrange – Whether to sort the predictions of r along alpha so they are non-decreasing (calpit.coverage.rearrange), which CalPIT.transform needs. Predictions that are already non-decreasing, such as those of IsplineNN or MonotonicNN, are unchanged.
val_fraction – Torch only. The fraction of calibration objects held out to stop training early; 0 trains for max_epochs.
n_alpha_val – Torch only. The number of alpha, from 0.001 to 0.999, every validation object is scored at.
oversample – Torch only. How many training items each object yields per epoch, each with a fresh alpha.
batch_size – Torch only. The number of (alpha, x) rows per training batch.
predict_batch_size – The number of objects per prediction batch; each batch has predict_batch_size * n_alpha rows.
max_epochs – Torch only. The maximum number of epochs.
lr – Torch only. The initial AdamW learning rate.
weight_decay – Torch only. The AdamW weight decay.
lr_decay – Torch only. The learning rate is lr * lr_decay**epoch.
patience – Torch only. The number of epochs without improvement in the validation loss to stop after.
num_workers – Torch only. The number of DataLoader worker processes.
trainer_kwargs – Torch only. Arguments for lightning.Trainer, such as accelerator, devices, precision, logger or callbacks, that override calpit’s defaults.
n_alpha – Scikit-learn only. The number of stratified alpha per calibration object; the classifier is fitted on n_objects * n_alpha rows. Predictions are made at n_alpha + 1 evenly spaced alpha and interpolated linearly in between.
random_state – The seed of the train/validation split, the alpha draws, the model initialization of a factory or the default model, and the torch random numbers in training. None leaves them unseeded.
verbose – Whether to show training progress.
- Variables:
model – The fitted network or classifier.
backend – “torch” or “sklearn”.
n_features_in – The number of features seen in fit.
train_loss – Torch only. The training loss per epoch.
val_bce – Torch only. The validation binary cross entropy per epoch.
best_val_bce – Torch only. The lowest validation loss, whose weights model_ has.
device – Torch only. The device the network was trained on.
- classmethod from_fitted(model: Any, **params: Any) Self[source]
Wraps a network or classifier that was trained outside CalPIT.
Use it after a hand-written training loop: the result predicts, diagnoses and transforms like a fitted CalPIT. The model is used as is, not copied.
- Parameters:
model – A trained network that follows the contract in calpit.nn.models, or a classifier fitted on [alpha, x] rows with boolean targets PIT <= alpha.
**params – Other constructor arguments, such as rearrange or predict_batch_size.
- Returns:
The fitted CalPIT.
- get_params(deep: bool = True) dict[str, Any][source]
Returns the constructor arguments, as scikit-learn estimators do.
- Parameters:
deep – Whether to add the parameters of a model that has get_params, such as a scikit-learn classifier, as model__<name>.
- Returns:
The arguments by name.
- set_params(**params: Any) Self[source]
Sets constructor arguments, as scikit-learn estimators do.
- Parameters:
**params – The arguments to set, by name; model__<name> sets a parameter of the model.
- Returns:
The estimator.
- __getstate__() dict[str, Any][source]
Returns the state to pickle, with a fitted network moved to the CPU.
predict moves the network to the device it was trained on, so without this a CalPIT pickled after predicting on a GPU would only load where CUDA is available. The network is moved in place; the next predict moves it back.
- __sklearn_is_fitted__() bool[source]
Returns whether fit has run, for sklearn.utils.validation.check_is_fitted.
- fit(x: numpy.typing.ArrayLike, y: numpy.typing.ArrayLike | None = None, cde: calpit.representations.ConditionalDensities | None = None, *, pit: numpy.typing.ArrayLike | None = None) Self[source]
Learns r(alpha; x) from a calibration set.
- Parameters:
x – The features, shape (n_objects, n_features).
y – The true values, shape (n_objects,).
cde – The CDEs of the calibration objects: a calpit.GridCDE, QuantileCDE or SampleCDE (calpit.qp_io.from_qp converts a qp ensemble).
pit – The PIT values, shape (n_objects,), in place of y and cde.
- Returns:
The fitted estimator.
- predict(x: numpy.typing.ArrayLike, alpha: numpy.typing.ArrayLike | None = None) FloatArray[source]
Predicts r(alpha; x) = P(PIT <= alpha | x), the local P-P curves.
- Parameters:
x – The features, shape (n_objects, n_features).
alpha – The coverage levels, shape (n_alpha,) for the same levels for every object, or (n_objects, n_alpha). None uses 101 levels from 0 to 1.
- Returns:
The predicted PIT CDF in [0, 1], shape (n_objects, n_alpha), rearranged to be non-decreasing in alpha unless rearrange is False.
- diagnose(x: numpy.typing.ArrayLike, alpha: numpy.typing.ArrayLike | None = None) calpit.diagnostics.LocalCalibration[source]
Predicts the local P-P curves and how far they stray from the diagonal.
- Parameters:
x – The features, shape (n_objects, n_features).
alpha – The increasing coverage levels, shape (n_alpha,). None uses 101 levels from 0 to 1.
- Returns:
The local calibration of the CDEs at each x.
- transform(x: numpy.typing.ArrayLike, cde: _Cde) _Cde[source]
Recalibrates CDEs.
- Parameters:
x – The features, shape (n_objects, n_features).
cde – The CDEs to recalibrate, one per row of x.
- Returns:
The recalibrated CDEs, in the same representation as cde.
- fit_transform(x: numpy.typing.ArrayLike, y: numpy.typing.ArrayLike, cde: _Cde) _Cde[source]
Fits on a calibration set and recalibrates its own CDEs.
- Parameters:
x – The features, shape (n_objects, n_features).
y – The true values, shape (n_objects,).
cde – The CDEs, one per row of x.
- Returns:
The recalibrated CDEs, in the same representation as cde.