Download src/split_conformal.py from At1uri/conformal-prediction-vault: direct link, hf CLI and curl.
- Browser
- Download file 1.25 kB
-
https://huggingface.co/At1uri/conformal-prediction-vault/resolve/main/src/split_conformal.py
- Command line
-
hf download hf://At1uri/conformal-prediction-vault/src/split_conformal.py
-
curl -L -o split_conformal.py https://huggingface.co/At1uri/conformal-prediction-vault/resolve/main/src/split_conformal.py
1.25 kB
| """ | |
| Split Conformal Prediction with Finite-Sample Coverage Guarantees | |
| Author: Ramprasad Atluri (At1uri) | |
| Repository: At1uri/conformal-prediction-vault | |
| """ | |
| import numpy as np | |
| class SplitConformalPredictor: | |
| """ | |
| Standard Split Conformal Prediction algorithm. | |
| Guarantees: P(Y in C(X)) >= 1 - alpha under exchangeability. | |
| """ | |
| def __init__(self, alpha=0.10): | |
| self.alpha = alpha | |
| self.q_hat = None | |
| def calibrate(self, y_true, y_pred): | |
| """ | |
| Calibrates on validation residuals s_i = |y_i - y_pred_i|. | |
| """ | |
| n = len(y_true) | |
| scores = np.abs(y_true - y_pred) | |
| # Finite-sample quantile index: ceil((n + 1) * (1 - alpha)) / n | |
| k = int(np.ceil((n + 1) * (1.0 - self.alpha))) - 1 | |
| k = min(n - 1, max(0, k)) | |
| sorted_scores = np.sort(scores) | |
| self.q_hat = float(sorted_scores[k]) | |
| return self.q_hat | |
| def predict(self, y_pred): | |
| """ | |
| Constructs prediction intervals: [y_pred - q_hat, y_pred + q_hat]. | |
| """ | |
| if self.q_hat is None: | |
| raise ValueError("Model must be calibrated before predicting intervals.") | |
| lower = y_pred - self.q_hat | |
| upper = y_pred + self.q_hat | |
| return lower, upper | |