File size: 1,251 Bytes
3752a39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"""
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