File size: 2,476 Bytes
853e005 | 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 43 44 45 46 47 48 49 50 51 52 53 54 | """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)
|