pyconformal 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyconformal/__init__.py +14 -0
- pyconformal/_quantile.py +53 -0
- pyconformal/classification.py +84 -0
- pyconformal/regression.py +70 -0
- pyconformal-0.0.1.dist-info/METADATA +79 -0
- pyconformal-0.0.1.dist-info/RECORD +8 -0
- pyconformal-0.0.1.dist-info/WHEEL +4 -0
- pyconformal-0.0.1.dist-info/licenses/LICENSE +21 -0
pyconformal/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""pyconformal: conformal prediction for Python."""
|
|
2
|
+
|
|
3
|
+
from pyconformal._quantile import conformal_quantile
|
|
4
|
+
from pyconformal.classification import SplitConformalClassifier
|
|
5
|
+
from pyconformal.regression import SplitConformalRegressor
|
|
6
|
+
|
|
7
|
+
__version__ = "0.0.1"
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"SplitConformalClassifier",
|
|
11
|
+
"SplitConformalRegressor",
|
|
12
|
+
"conformal_quantile",
|
|
13
|
+
"__version__",
|
|
14
|
+
]
|
pyconformal/_quantile.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Finite-sample conformal quantile."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from fractions import Fraction
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _check_alpha(alpha: float) -> float:
|
|
12
|
+
alpha = float(alpha)
|
|
13
|
+
if not 0.0 < alpha < 1.0:
|
|
14
|
+
raise ValueError(f"alpha must be strictly between 0 and 1, got {alpha}.")
|
|
15
|
+
return alpha
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def conformal_quantile(scores, alpha: float) -> float:
|
|
19
|
+
"""Return the split-conformal threshold for nonconformity ``scores``.
|
|
20
|
+
|
|
21
|
+
The threshold is the ``k``-th smallest calibration score, where
|
|
22
|
+
``k = ceil((n + 1) * (1 - alpha))`` and ``n`` is the number of scores.
|
|
23
|
+
If the calibration data and a test point are exchangeable, the test
|
|
24
|
+
point's score is at most this threshold with probability at least
|
|
25
|
+
``1 - alpha``.
|
|
26
|
+
|
|
27
|
+
If ``k > n`` (too few calibration points for the requested ``alpha``),
|
|
28
|
+
the threshold is ``inf``: no finite threshold gives the guarantee.
|
|
29
|
+
|
|
30
|
+
Parameters
|
|
31
|
+
----------
|
|
32
|
+
scores : array-like of shape (n,)
|
|
33
|
+
Nonconformity scores computed on the calibration set.
|
|
34
|
+
alpha : float
|
|
35
|
+
Miscoverage level, strictly between 0 and 1.
|
|
36
|
+
|
|
37
|
+
Returns
|
|
38
|
+
-------
|
|
39
|
+
float
|
|
40
|
+
"""
|
|
41
|
+
alpha = _check_alpha(alpha)
|
|
42
|
+
scores = np.asarray(scores, dtype=float).ravel()
|
|
43
|
+
n = scores.size
|
|
44
|
+
if n == 0:
|
|
45
|
+
raise ValueError("scores must contain at least one value.")
|
|
46
|
+
if not np.all(np.isfinite(scores)):
|
|
47
|
+
raise ValueError("scores must be finite.")
|
|
48
|
+
# Exact rational arithmetic: in floating point (19 + 1) * (1 - 0.05)
|
|
49
|
+
# is 19.000000000000004, which would wrongly round k up to 20.
|
|
50
|
+
k = math.ceil((n + 1) * (1 - Fraction(repr(alpha))))
|
|
51
|
+
if k > n:
|
|
52
|
+
return math.inf
|
|
53
|
+
return float(np.partition(scores, k - 1)[k - 1])
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Split conformal classification."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from pyconformal._quantile import _check_alpha, conformal_quantile
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class SplitConformalClassifier:
|
|
11
|
+
"""Split (inductive) conformal prediction sets for classification.
|
|
12
|
+
|
|
13
|
+
Wraps any classifier with ``fit``, ``predict_proba`` and ``classes_``.
|
|
14
|
+
The nonconformity score is ``1 - p_hat(y | x)``, one minus the predicted
|
|
15
|
+
probability of the true class (the LAC score of Sadinle, Lei and
|
|
16
|
+
Wasserman, 2019). A class enters the prediction set when its score is at
|
|
17
|
+
most the finite-sample conformal quantile of the calibration scores.
|
|
18
|
+
|
|
19
|
+
If the calibration and test data are exchangeable, the prediction set
|
|
20
|
+
contains the true label with probability at least ``1 - alpha``
|
|
21
|
+
(marginal coverage). Sets can be empty or contain several classes.
|
|
22
|
+
|
|
23
|
+
Parameters
|
|
24
|
+
----------
|
|
25
|
+
estimator : object
|
|
26
|
+
A classifier exposing ``fit``, ``predict_proba`` and ``classes_``.
|
|
27
|
+
alpha : float, default=0.1
|
|
28
|
+
Default miscoverage level; 0.1 gives 90% prediction sets.
|
|
29
|
+
prefit : bool, default=False
|
|
30
|
+
If True, ``estimator`` is already trained and ``fit`` must not be
|
|
31
|
+
called; go straight to ``calibrate``.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(self, estimator, alpha: float = 0.1, prefit: bool = False):
|
|
35
|
+
self.estimator = estimator
|
|
36
|
+
self.alpha = _check_alpha(alpha)
|
|
37
|
+
self.prefit = prefit
|
|
38
|
+
self.calibration_scores_ = None
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def classes_(self):
|
|
42
|
+
return self.estimator.classes_
|
|
43
|
+
|
|
44
|
+
def fit(self, X, y):
|
|
45
|
+
"""Train the underlying classifier on the proper training set."""
|
|
46
|
+
if self.prefit:
|
|
47
|
+
raise RuntimeError("prefit=True: the estimator is already trained.")
|
|
48
|
+
self.estimator.fit(X, y)
|
|
49
|
+
return self
|
|
50
|
+
|
|
51
|
+
def calibrate(self, X_cal, y_cal):
|
|
52
|
+
"""Compute scores on data not used for training."""
|
|
53
|
+
y_cal = np.asarray(y_cal).ravel()
|
|
54
|
+
proba = np.asarray(self.estimator.predict_proba(X_cal), dtype=float)
|
|
55
|
+
if proba.shape[0] != y_cal.shape[0]:
|
|
56
|
+
raise ValueError("X_cal and y_cal have different numbers of rows.")
|
|
57
|
+
classes = np.asarray(self.classes_)
|
|
58
|
+
index = {c: i for i, c in enumerate(classes.tolist())}
|
|
59
|
+
try:
|
|
60
|
+
cols = np.array([index[c] for c in y_cal.tolist()])
|
|
61
|
+
except KeyError as err:
|
|
62
|
+
raise ValueError(
|
|
63
|
+
f"Calibration label {err.args[0]!r} is not among the "
|
|
64
|
+
"estimator's classes_."
|
|
65
|
+
) from None
|
|
66
|
+
self.calibration_scores_ = 1.0 - proba[np.arange(len(cols)), cols]
|
|
67
|
+
return self
|
|
68
|
+
|
|
69
|
+
def predict(self, X):
|
|
70
|
+
"""Point predictions from the underlying classifier."""
|
|
71
|
+
return self.estimator.predict(X)
|
|
72
|
+
|
|
73
|
+
def predict_set(self, X, alpha: float | None = None):
|
|
74
|
+
"""Return prediction sets as a boolean array (n_samples, n_classes).
|
|
75
|
+
|
|
76
|
+
Entry ``[i, j]`` is True when ``classes_[j]`` is in the set for
|
|
77
|
+
sample ``i``.
|
|
78
|
+
"""
|
|
79
|
+
if self.calibration_scores_ is None:
|
|
80
|
+
raise RuntimeError("Call calibrate() before predict_set().")
|
|
81
|
+
alpha = self.alpha if alpha is None else _check_alpha(alpha)
|
|
82
|
+
q = conformal_quantile(self.calibration_scores_, alpha)
|
|
83
|
+
proba = np.asarray(self.estimator.predict_proba(X), dtype=float)
|
|
84
|
+
return (1.0 - proba) <= q
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Split conformal regression."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from pyconformal._quantile import _check_alpha, conformal_quantile
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class SplitConformalRegressor:
|
|
11
|
+
"""Split (inductive) conformal prediction intervals for regression.
|
|
12
|
+
|
|
13
|
+
Wraps any regressor with ``fit(X, y)`` and ``predict(X)`` methods. The
|
|
14
|
+
nonconformity score is the absolute residual ``|y - y_hat|`` on a held-out
|
|
15
|
+
calibration set. Intervals are ``y_hat +/- q``, where ``q`` is the
|
|
16
|
+
finite-sample conformal quantile of the calibration scores.
|
|
17
|
+
|
|
18
|
+
If the calibration and test data are exchangeable, a new interval
|
|
19
|
+
contains the true value with probability at least ``1 - alpha``
|
|
20
|
+
(marginal coverage). Intervals have the same width for every input.
|
|
21
|
+
|
|
22
|
+
Parameters
|
|
23
|
+
----------
|
|
24
|
+
estimator : object
|
|
25
|
+
A regressor exposing ``fit`` and ``predict``.
|
|
26
|
+
alpha : float, default=0.1
|
|
27
|
+
Default miscoverage level; 0.1 gives 90% intervals.
|
|
28
|
+
prefit : bool, default=False
|
|
29
|
+
If True, ``estimator`` is already trained and ``fit`` must not be
|
|
30
|
+
called; go straight to ``calibrate``.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(self, estimator, alpha: float = 0.1, prefit: bool = False):
|
|
34
|
+
self.estimator = estimator
|
|
35
|
+
self.alpha = _check_alpha(alpha)
|
|
36
|
+
self.prefit = prefit
|
|
37
|
+
self.calibration_scores_ = None
|
|
38
|
+
|
|
39
|
+
def fit(self, X, y):
|
|
40
|
+
"""Train the underlying regressor on the proper training set."""
|
|
41
|
+
if self.prefit:
|
|
42
|
+
raise RuntimeError("prefit=True: the estimator is already trained.")
|
|
43
|
+
self.estimator.fit(X, y)
|
|
44
|
+
return self
|
|
45
|
+
|
|
46
|
+
def calibrate(self, X_cal, y_cal):
|
|
47
|
+
"""Compute absolute-residual scores on data not used for training."""
|
|
48
|
+
y_cal = np.asarray(y_cal, dtype=float).ravel()
|
|
49
|
+
y_hat = np.asarray(self.estimator.predict(X_cal), dtype=float).ravel()
|
|
50
|
+
if y_hat.shape != y_cal.shape:
|
|
51
|
+
raise ValueError("X_cal and y_cal have different numbers of rows.")
|
|
52
|
+
self.calibration_scores_ = np.abs(y_cal - y_hat)
|
|
53
|
+
return self
|
|
54
|
+
|
|
55
|
+
def predict(self, X):
|
|
56
|
+
"""Point predictions from the underlying regressor."""
|
|
57
|
+
return np.asarray(self.estimator.predict(X), dtype=float).ravel()
|
|
58
|
+
|
|
59
|
+
def predict_interval(self, X, alpha: float | None = None):
|
|
60
|
+
"""Return prediction intervals as an array of shape (n_samples, 2).
|
|
61
|
+
|
|
62
|
+
Column 0 is the lower bound, column 1 the upper bound. Bounds are
|
|
63
|
+
infinite when the calibration set is too small for ``alpha``.
|
|
64
|
+
"""
|
|
65
|
+
if self.calibration_scores_ is None:
|
|
66
|
+
raise RuntimeError("Call calibrate() before predict_interval().")
|
|
67
|
+
alpha = self.alpha if alpha is None else _check_alpha(alpha)
|
|
68
|
+
q = conformal_quantile(self.calibration_scores_, alpha)
|
|
69
|
+
y_hat = self.predict(X)
|
|
70
|
+
return np.column_stack([y_hat - q, y_hat + q])
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pyconformal
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Conformal prediction for Python: distribution-free prediction intervals and prediction sets with finite-sample coverage guarantees.
|
|
5
|
+
Project-URL: Homepage, https://github.com/valeman/pyconformal
|
|
6
|
+
Project-URL: Source, https://github.com/valeman/pyconformal
|
|
7
|
+
Project-URL: Issues, https://github.com/valeman/pyconformal/issues
|
|
8
|
+
Author-email: Valery Manokhin <val@valeriy.ai>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: calibration,conformal prediction,machine learning,prediction intervals,prediction sets,uncertainty quantification
|
|
12
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
20
|
+
Requires-Python: >=3.9
|
|
21
|
+
Requires-Dist: numpy>=1.22
|
|
22
|
+
Provides-Extra: test
|
|
23
|
+
Requires-Dist: pytest>=7; extra == 'test'
|
|
24
|
+
Requires-Dist: scikit-learn>=1.0; extra == 'test'
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# pyconformal
|
|
28
|
+
|
|
29
|
+
Conformal prediction for Python: prediction intervals and prediction sets with
|
|
30
|
+
finite-sample coverage guarantees, for any model.
|
|
31
|
+
|
|
32
|
+
> **Status: early development (0.0.1).** The API will change before 1.0.
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install pyconformal
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Regression: prediction intervals
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from sklearn.ensemble import RandomForestRegressor
|
|
44
|
+
from pyconformal import SplitConformalRegressor
|
|
45
|
+
|
|
46
|
+
model = SplitConformalRegressor(RandomForestRegressor(), alpha=0.1)
|
|
47
|
+
model.fit(X_train, y_train) # train the model
|
|
48
|
+
model.calibrate(X_cal, y_cal) # held-out calibration data
|
|
49
|
+
intervals = model.predict_interval(X_test) # shape (n, 2): lower, upper
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Classification: prediction sets
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from sklearn.linear_model import LogisticRegression
|
|
56
|
+
from pyconformal import SplitConformalClassifier
|
|
57
|
+
|
|
58
|
+
model = SplitConformalClassifier(LogisticRegression(), alpha=0.1)
|
|
59
|
+
model.fit(X_train, y_train)
|
|
60
|
+
model.calibrate(X_cal, y_cal)
|
|
61
|
+
sets = model.predict_set(X_test) # boolean (n, n_classes), columns = model.classes_
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Already have a trained model? Pass `prefit=True` and skip `fit`.
|
|
65
|
+
|
|
66
|
+
## The guarantee
|
|
67
|
+
|
|
68
|
+
If the calibration data and the test point are exchangeable (for example,
|
|
69
|
+
i.i.d.), the interval or set contains the true value with probability at least
|
|
70
|
+
`1 - alpha`. The guarantee is marginal (on average over test points), not
|
|
71
|
+
conditional on each input. It holds for any model and any data distribution.
|
|
72
|
+
|
|
73
|
+
The calibration data must not be used to train the model. If the calibration
|
|
74
|
+
set is too small for the chosen `alpha` (fewer than `1/alpha - 1` points), the
|
|
75
|
+
intervals are infinite, which is the only way to keep the guarantee.
|
|
76
|
+
|
|
77
|
+
## Licence
|
|
78
|
+
|
|
79
|
+
MIT. Copyright (c) 2026 Valery Manokhin.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
pyconformal/__init__.py,sha256=_0cWk-G3qG8gbdQPTLg9WW1O-dV1V6f5H61lVLl335A,375
|
|
2
|
+
pyconformal/_quantile.py,sha256=WRCcQwp-69de8Wzn2e_JgCXXTvXn6AEAqYgN3H5N85I,1732
|
|
3
|
+
pyconformal/classification.py,sha256=VfwmJzLd1XkXTNUgjnFut6BiBWC2sHfxMJzQTpT1ugc,3352
|
|
4
|
+
pyconformal/regression.py,sha256=IHE3ke_V-wQZk6YJP8gN03DsmDupFJqmukRl4IhjjBg,2856
|
|
5
|
+
pyconformal-0.0.1.dist-info/METADATA,sha256=9t3PgYlY9Z-GLbyYayusT0-_A9BT0ChuqKKTtaz6Ff4,2938
|
|
6
|
+
pyconformal-0.0.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
pyconformal-0.0.1.dist-info/licenses/LICENSE,sha256=8s10xOw9IpBEEDXnK5INiRQnOJQ1HWGncssTp8kAi4w,1072
|
|
8
|
+
pyconformal-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Valery Manokhin
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|