Download src/otfusion/calibration.py from BioinstLab/bnet-ot-fusion: direct link, hf CLI and curl.
- Browser
- Download file 1.86 kB
-
https://huggingface.co/BioinstLab/bnet-ot-fusion/resolve/main/src/otfusion/calibration.py
- Command line
-
hf download hf://BioinstLab/bnet-ot-fusion/src/otfusion/calibration.py
-
curl -L -o calibration.py https://huggingface.co/BioinstLab/bnet-ot-fusion/resolve/main/src/otfusion/calibration.py
1.86 kB
| """Probability calibration of the fused output with isotonic regression. | |
| The calibrator must be fitted on data that is not used for evaluation: | |
| either a separate calibration split, or out-of-fold (cross-fitted) predictions. | |
| Fitting and scoring on the same labels gives an optimistic picture of | |
| calibration and of threshold-based metrics. | |
| """ | |
| from __future__ import annotations | |
| import numpy as np | |
| from sklearn.isotonic import IsotonicRegression | |
| from sklearn.model_selection import StratifiedKFold | |
| class IsotonicCalibrator: | |
| """Thin wrapper around :class:`sklearn.isotonic.IsotonicRegression`.""" | |
| def __init__(self) -> None: | |
| self._iso = IsotonicRegression(out_of_bounds="clip", y_min=0.0, y_max=1.0) | |
| self.fitted = False | |
| def fit(self, probs: np.ndarray, y: np.ndarray) -> "IsotonicCalibrator": | |
| self._iso.fit(np.asarray(probs, dtype=np.float64), np.asarray(y, dtype=np.float64)) | |
| self.fitted = True | |
| return self | |
| def transform(self, probs: np.ndarray) -> np.ndarray: | |
| if not self.fitted: | |
| raise RuntimeError("call fit() before transform()") | |
| return self._iso.transform(np.asarray(probs, dtype=np.float64)) | |
| def cross_fitted_calibration( | |
| probs: np.ndarray, y: np.ndarray, n_splits: int = 5, seed: int = 0 | |
| ) -> np.ndarray: | |
| """Calibrate every sample with a calibrator that never saw its label. | |
| Use this when no separate calibration split is available. | |
| """ | |
| probs = np.asarray(probs, dtype=np.float64) | |
| y = np.asarray(y).astype(int) | |
| out = np.empty_like(probs) | |
| folds = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=seed) | |
| for train_idx, test_idx in folds.split(probs.reshape(-1, 1), y): | |
| cal = IsotonicCalibrator().fit(probs[train_idx], y[train_idx]) | |
| out[test_idx] = cal.transform(probs[test_idx]) | |
| return out | |