pyconformal 0.0.1__tar.gz

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.
@@ -0,0 +1,12 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ build/
5
+ dist/
6
+ .venv/
7
+ venv/
8
+ .pytest_cache/
9
+ .coverage
10
+ htmlcov/
11
+ .ipynb_checkpoints/
12
+ .DS_Store
@@ -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.
@@ -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,53 @@
1
+ # pyconformal
2
+
3
+ Conformal prediction for Python: prediction intervals and prediction sets with
4
+ finite-sample coverage guarantees, for any model.
5
+
6
+ > **Status: early development (0.0.1).** The API will change before 1.0.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ pip install pyconformal
12
+ ```
13
+
14
+ ## Regression: prediction intervals
15
+
16
+ ```python
17
+ from sklearn.ensemble import RandomForestRegressor
18
+ from pyconformal import SplitConformalRegressor
19
+
20
+ model = SplitConformalRegressor(RandomForestRegressor(), alpha=0.1)
21
+ model.fit(X_train, y_train) # train the model
22
+ model.calibrate(X_cal, y_cal) # held-out calibration data
23
+ intervals = model.predict_interval(X_test) # shape (n, 2): lower, upper
24
+ ```
25
+
26
+ ## Classification: prediction sets
27
+
28
+ ```python
29
+ from sklearn.linear_model import LogisticRegression
30
+ from pyconformal import SplitConformalClassifier
31
+
32
+ model = SplitConformalClassifier(LogisticRegression(), alpha=0.1)
33
+ model.fit(X_train, y_train)
34
+ model.calibrate(X_cal, y_cal)
35
+ sets = model.predict_set(X_test) # boolean (n, n_classes), columns = model.classes_
36
+ ```
37
+
38
+ Already have a trained model? Pass `prefit=True` and skip `fit`.
39
+
40
+ ## The guarantee
41
+
42
+ If the calibration data and the test point are exchangeable (for example,
43
+ i.i.d.), the interval or set contains the true value with probability at least
44
+ `1 - alpha`. The guarantee is marginal (on average over test points), not
45
+ conditional on each input. It holds for any model and any data distribution.
46
+
47
+ The calibration data must not be used to train the model. If the calibration
48
+ set is too small for the chosen `alpha` (fewer than `1/alpha - 1` points), the
49
+ intervals are infinite, which is the only way to keep the guarantee.
50
+
51
+ ## Licence
52
+
53
+ MIT. Copyright (c) 2026 Valery Manokhin.
@@ -0,0 +1,13 @@
1
+ name: pyconformal
2
+ channels:
3
+ - conda-forge
4
+ dependencies:
5
+ - python=3.12
6
+ - numpy>=1.22
7
+ - scikit-learn>=1.0
8
+ - pytest>=7
9
+ - pip
10
+ - pip:
11
+ - build
12
+ - twine
13
+ - -e .
@@ -0,0 +1,49 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "pyconformal"
7
+ dynamic = ["version"]
8
+ description = "Conformal prediction for Python: distribution-free prediction intervals and prediction sets with finite-sample coverage guarantees."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Valery Manokhin", email = "val@valeriy.ai" }]
13
+ requires-python = ">=3.9"
14
+ dependencies = ["numpy>=1.22"]
15
+ keywords = [
16
+ "conformal prediction",
17
+ "uncertainty quantification",
18
+ "prediction intervals",
19
+ "prediction sets",
20
+ "machine learning",
21
+ "calibration",
22
+ ]
23
+ classifiers = [
24
+ "Development Status :: 2 - Pre-Alpha",
25
+ "Intended Audience :: Science/Research",
26
+ "Intended Audience :: Developers",
27
+ "Operating System :: OS Independent",
28
+ "Programming Language :: Python :: 3",
29
+ "Programming Language :: Python :: 3 :: Only",
30
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
31
+ "Topic :: Scientific/Engineering :: Mathematics",
32
+ ]
33
+
34
+ [project.optional-dependencies]
35
+ test = ["pytest>=7", "scikit-learn>=1.0"]
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/valeman/pyconformal"
39
+ Source = "https://github.com/valeman/pyconformal"
40
+ Issues = "https://github.com/valeman/pyconformal/issues"
41
+
42
+ [tool.hatch.version]
43
+ path = "src/pyconformal/__init__.py"
44
+
45
+ [tool.hatch.build.targets.wheel]
46
+ packages = ["src/pyconformal"]
47
+
48
+ [tool.pytest.ini_options]
49
+ testpaths = ["tests"]
@@ -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
+ ]
@@ -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,131 @@
1
+ import math
2
+
3
+ import numpy as np
4
+ import pytest
5
+ from sklearn.linear_model import LinearRegression, LogisticRegression
6
+
7
+ from pyconformal import (
8
+ SplitConformalClassifier,
9
+ SplitConformalRegressor,
10
+ conformal_quantile,
11
+ )
12
+
13
+
14
+ # ---------------------------------------------------------------- quantile
15
+
16
+
17
+ def test_quantile_picks_kth_smallest():
18
+ scores = np.arange(1, 20) # n = 19
19
+ # k = ceil(20 * 0.95) = 19 -> 19th smallest = 19
20
+ assert conformal_quantile(scores, 0.05) == 19.0
21
+ # k = ceil(20 * 0.9) = 18 -> 18
22
+ assert conformal_quantile(scores, 0.1) == 18.0
23
+
24
+
25
+ def test_quantile_is_infinite_when_calibration_set_too_small():
26
+ # n = 5, alpha = 0.1: k = ceil(6 * 0.9) = 6 > 5
27
+ assert math.isinf(conformal_quantile([1, 2, 3, 4, 5], 0.1))
28
+
29
+
30
+ def test_quantile_ignores_input_order():
31
+ rng = np.random.default_rng(0)
32
+ s = rng.normal(size=101)
33
+ assert conformal_quantile(s, 0.2) == conformal_quantile(np.sort(s), 0.2)
34
+
35
+
36
+ @pytest.mark.parametrize("alpha", [0, 1, -0.1, 1.5])
37
+ def test_quantile_rejects_bad_alpha(alpha):
38
+ with pytest.raises(ValueError):
39
+ conformal_quantile([1.0, 2.0], alpha)
40
+
41
+
42
+ def test_quantile_rejects_empty_and_nonfinite():
43
+ with pytest.raises(ValueError):
44
+ conformal_quantile([], 0.1)
45
+ with pytest.raises(ValueError):
46
+ conformal_quantile([1.0, np.nan], 0.1)
47
+
48
+
49
+ # --------------------------------------------------------------- coverage
50
+
51
+
52
+ def _empirical_coverage(make_model, n_trials=200, n_cal=200, alpha=0.1):
53
+ rng = np.random.default_rng(42)
54
+ hits = []
55
+ for _ in range(n_trials):
56
+ hits.append(make_model(rng, n_cal, alpha))
57
+ return float(np.mean(hits))
58
+
59
+
60
+ def test_regressor_coverage():
61
+ def trial(rng, n_cal, alpha):
62
+ n_train, n_test = 200, 500
63
+ n = n_train + n_cal + n_test
64
+ X = rng.normal(size=(n, 3))
65
+ y = X @ np.array([1.0, -2.0, 0.5]) + rng.standard_t(df=3, size=n)
66
+ model = SplitConformalRegressor(LinearRegression(), alpha=alpha)
67
+ model.fit(X[:n_train], y[:n_train])
68
+ model.calibrate(X[n_train:n_train + n_cal], y[n_train:n_train + n_cal])
69
+ iv = model.predict_interval(X[n_train + n_cal:])
70
+ yt = y[n_train + n_cal:]
71
+ return np.mean((iv[:, 0] <= yt) & (yt <= iv[:, 1]))
72
+
73
+ cov = _empirical_coverage(trial)
74
+ # Theory: 0.9 <= E[coverage] <= 0.9 + 1/201 ~ 0.905
75
+ assert 0.89 <= cov <= 0.915
76
+
77
+
78
+ def test_classifier_coverage():
79
+ def trial(rng, n_cal, alpha):
80
+ n_train, n_test = 300, 500
81
+ n = n_train + n_cal + n_test
82
+ y = rng.integers(0, 3, size=n)
83
+ X = rng.normal(size=(n, 2)) + np.array([[0, 0], [1.5, 0], [0, 1.5]])[y]
84
+ model = SplitConformalClassifier(LogisticRegression(), alpha=alpha)
85
+ model.fit(X[:n_train], y[:n_train])
86
+ model.calibrate(X[n_train:n_train + n_cal], y[n_train:n_train + n_cal])
87
+ sets = model.predict_set(X[n_train + n_cal:])
88
+ yt = y[n_train + n_cal:]
89
+ col = np.searchsorted(model.classes_, yt)
90
+ return np.mean(sets[np.arange(len(yt)), col])
91
+
92
+ cov = _empirical_coverage(trial)
93
+ assert 0.89 <= cov <= 0.915
94
+
95
+
96
+ # ------------------------------------------------------------------- API
97
+
98
+
99
+ def test_regressor_interval_shape_and_alpha_override():
100
+ rng = np.random.default_rng(1)
101
+ X = rng.normal(size=(300, 2))
102
+ y = X.sum(axis=1) + rng.normal(size=300)
103
+ m = SplitConformalRegressor(LinearRegression()).fit(X[:100], y[:100])
104
+ m.calibrate(X[100:200], y[100:200])
105
+ narrow = m.predict_interval(X[200:], alpha=0.5)
106
+ wide = m.predict_interval(X[200:], alpha=0.05)
107
+ assert narrow.shape == (100, 2)
108
+ assert np.all(wide[:, 1] - wide[:, 0] >= narrow[:, 1] - narrow[:, 0])
109
+
110
+
111
+ def test_prefit_and_errors():
112
+ rng = np.random.default_rng(2)
113
+ X = rng.normal(size=(100, 2))
114
+ y = X[:, 0] + rng.normal(size=100)
115
+ est = LinearRegression().fit(X[:50], y[:50])
116
+ m = SplitConformalRegressor(est, prefit=True)
117
+ with pytest.raises(RuntimeError):
118
+ m.predict_interval(X)
119
+ with pytest.raises(RuntimeError):
120
+ m.fit(X, y)
121
+ m.calibrate(X[50:], y[50:])
122
+ assert m.predict_interval(X).shape == (100, 2)
123
+
124
+
125
+ def test_classifier_rejects_unknown_calibration_label():
126
+ rng = np.random.default_rng(3)
127
+ X = rng.normal(size=(60, 2))
128
+ y = (X[:, 0] > 0).astype(int)
129
+ m = SplitConformalClassifier(LogisticRegression()).fit(X, y)
130
+ with pytest.raises(ValueError):
131
+ m.calibrate(X[:3], np.array([0, 1, 7]))