Calibration¶
uncertainty_flow.calibration
¶
Calibration diagnostics for uncertainty models.
RecalibratedModel
¶
Bases: BaseUncertaintyModel
Wrap a fitted model with isotonic recalibration.
Learns a monotone mapping from predicted quantile levels to empirical coverage using isotonic regression (Kuleshov et al., 2018).
Supports two modes:
- Separate calibration set (default): fit the isotonic map on held-out
data provided to fit().
- Cross-fitting (cross_calibrate=True): K-fold fit on the inner
model's training data to avoid overfitting the isotonic map.
Examples:
>>> from sklearn.ensemble import GradientBoostingRegressor
>>> from uncertainty_flow.wrappers import ConformalRegressor
>>> from uncertainty_flow.calibration import RecalibratedModel
>>> import polars as pl
>>>
>>> base = ConformalRegressor(base_model=GradientBoostingRegressor())
>>> base.fit(df_train, target="y")
>>> recal = RecalibratedModel(model=base)
>>> recal.fit(df_calib, target="y")
>>> pred = recal.predict(df_test)
Source code in uncertainty_flow/calibration/recalibration.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | |
__init__(model, quantile_levels=None, cross_calibrate=False, n_folds=5, random_state=None)
¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
BaseUncertaintyModel
|
A fitted BaseUncertaintyModel to recalibrate. |
required |
quantile_levels
|
list[float] | None
|
Quantile levels for the output predictions. Defaults to the inner model's levels. |
None
|
cross_calibrate
|
bool
|
If True, use K-fold cross-fitting on the calibration data to avoid overfitting the isotonic map. |
False
|
n_folds
|
int
|
Number of folds when cross_calibrate=True. |
5
|
random_state
|
int | None
|
Random seed for cross-fitting. |
None
|
Source code in uncertainty_flow/calibration/recalibration.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | |
fit(data, target=None, **kwargs)
¶
Learn the isotonic recalibration mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
PolarsInput
|
Calibration dataset. If cross_calibrate=True, this data is split into K folds for cross-fitting. |
required |
target
|
TargetSpec | None
|
Target column name(s). |
None
|
Returns:
| Type | Description |
|---|---|
RecalibratedModel
|
self |
Source code in uncertainty_flow/calibration/recalibration.py
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | |
predict(data)
¶
Generate recalibrated predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
PolarsInput
|
Input data for prediction. |
required |
Returns:
| Type | Description |
|---|---|
DistributionPrediction
|
DistributionPrediction with recalibrated quantile values. |
Source code in uncertainty_flow/calibration/recalibration.py
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 | |
calibration_report(model, data, target, quantile_levels=None)
¶
Generate calibration report for a fitted model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
BaseUncertaintyModel
|
Fitted uncertainty model |
required |
data
|
DataFrame
|
Validation data |
required |
target
|
str | list[str]
|
Target column name(s) |
required |
quantile_levels
|
list[float] | None
|
Quantile levels to evaluate (default: [0.8, 0.9, 0.95]) |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame with calibration metrics: |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
Examples:
>>> from uncertainty_flow.wrappers import ConformalRegressor
>>> from sklearn.ensemble import GradientBoostingRegressor
>>> model = ConformalRegressor(GradientBoostingRegressor())
>>> model.fit(train_df, target="price")
>>> report = model.calibration_report(val_df, target="price")
>>> print(report)
Source code in uncertainty_flow/utils/calibration_utils.py
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
compute_uncertainty_drivers(residuals, features)
¶
Compute correlation between features and squared residuals.
Features with high correlation to squared residuals indicate heteroscedasticity - they drive uncertainty in predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
residuals
|
ndarray
|
Model residuals (y_true - y_pred) |
required |
features
|
DataFrame
|
Feature DataFrame |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame with columns: |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
Sorted by absolute correlation descending. |
Examples:
>>> import numpy as np
>>> import polars as pl
>>> residuals = np.array([1, -2, 3, -1, 2])
>>> features = pl.DataFrame({
... "a": [1, 2, 3, 4, 5],
... "b": [5, 4, 3, 2, 1],
... })
>>> compute_uncertainty_drivers(residuals, features)
shape: (2, 3)
┌─────────┬─────────────────────┬─────────┐
│ feature ┆ residual_correlation ┆ p_value │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞═════════╪══════════════════════╪═════════╡
│ a ┆ 0.89 ┆ 0.11 │
│ b ┆ -0.89 ┆ 0.11 │
└─────────┴─────────────────────┴─────────┘
Source code in uncertainty_flow/calibration/residual_analysis.py
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | |
uncertainty_shap(model, X, background=None, quantile_pairs=None)
¶
Compute SHAP values for quantile intervals to identify interval width drivers.
Runs SHAP on the upper and lower quantile predictions separately, then computes the difference to identify what drives interval width.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Fitted uncertainty model with predict() returning DistributionPrediction |
required | |
X
|
DataFrame
|
Feature DataFrame for SHAP evaluation |
required |
background
|
DataFrame | None
|
Background dataset for SHAP explanation. If None, uses X[:100] as suggested in roadmap. |
None
|
quantile_pairs
|
list[tuple[float, float]] | None
|
List of (lower, upper) quantile pairs to analyze. Defaults to [(0.1, 0.9), (0.05, 0.95)]. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame with columns: |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
Examples:
>>> import numpy as np
>>> import polars as pl
>>> from uncertainty_flow import DeepQuantileNet
>>> from uncertainty_flow.calibration import uncertainty_shap
>>>
>>> np.random.seed(42)
>>> n = 100
>>> df = pl.DataFrame({
... "x1": np.random.randn(n),
... "x2": np.random.randn(n),
... "y": 3 * np.random.randn(n) + 5,
... })
>>> model = DeepQuantileNet(random_state=42)
>>> model.fit(df, target="y")
>>> X = df.select(["x1", "x2"])
>>> shap_df = uncertainty_shap(model, X)
>>> shap_df
Source code in uncertainty_flow/calibration/shap_values.py
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 | |