Download calibration.py from brainfish/x-virality-model: direct link, hf CLI and curl.
- Browser
- Download file 2.48 kB
-
https://huggingface.co/brainfish/x-virality-model/resolve/main/calibration.py
- Command line
-
hf download hf://brainfish/x-virality-model/calibration.py
-
curl -L -o calibration.py https://huggingface.co/brainfish/x-virality-model/resolve/main/calibration.py
2.48 kB
| """Probability calibrators (Platt scaling / isotonic regression).""" | |
| import numpy as np | |
| from sklearn.linear_model import LogisticRegression | |
| from sklearn.isotonic import IsotonicRegression | |
| class Calibrator: | |
| def __init__(self, method): self.method = method | |
| def fit(self, p, y): | |
| if self.method == 'platt': | |
| z = np.log(np.clip(p, 1e-6, 1 - 1e-6) / (1 - np.clip(p, 1e-6, 1 - 1e-6))).reshape(-1, 1) | |
| self.m = LogisticRegression(C=1e6).fit(z, y) | |
| else: | |
| self.m = IsotonicRegression(out_of_bounds='clip', y_min=0.001, y_max=0.999).fit(p, y) | |
| return self | |
| def predict(self, p): | |
| p = np.asarray(p, float) | |
| if self.method == 'platt': | |
| z = np.log(np.clip(p, 1e-6, 1 - 1e-6) / (1 - np.clip(p, 1e-6, 1 - 1e-6))).reshape(-1, 1) | |
| return self.m.predict_proba(z)[:, 1] | |
| return self.m.predict(p) | |
| class ScoreCalibrator: | |
| """v2: maps any model score (probability, ranker score or regression output) to P(viral). | |
| 'temperature': sigmoid(logit(p)/T) for probability outputs (Guo et al. 2017, single parameter) | |
| 'platt' : sigmoid(a*s+b) on the raw score (needed for ranker/regressor scores) | |
| 'isotonic' : monotone step function on the raw score""" | |
| def __init__(self, method, score_is_prob=True): | |
| self.method = method; self.score_is_prob = score_is_prob | |
| def _z(self, s): | |
| s = np.asarray(s, float) | |
| if self.score_is_prob: | |
| s = np.clip(s, 1e-6, 1 - 1e-6); return np.log(s / (1 - s)) | |
| return s | |
| def fit(self, s, y): | |
| y = np.asarray(y, int); z = self._z(s) | |
| if self.method == 'temperature': | |
| from scipy.optimize import minimize_scalar | |
| def nll(logT): | |
| q = np.clip(1 / (1 + np.exp(-z / np.exp(logT))), 1e-9, 1 - 1e-9) | |
| return -np.mean(y * np.log(q) + (1 - y) * np.log(1 - q)) | |
| self.T = float(np.exp(minimize_scalar(nll, bounds=(-3, 3), method='bounded').x)) | |
| elif self.method == 'platt': | |
| self.m = LogisticRegression(C=1e6).fit(z.reshape(-1, 1), y) | |
| else: | |
| self.m = IsotonicRegression(out_of_bounds='clip', y_min=0.001, y_max=0.999).fit(z, y) | |
| return self | |
| def predict(self, s): | |
| z = self._z(s) | |
| if self.method == 'temperature': return 1 / (1 + np.exp(-z / self.T)) | |
| if self.method == 'platt': return self.m.predict_proba(z.reshape(-1, 1))[:, 1] | |
| return self.m.predict(z) | |