-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalibrators.py
143 lines (109 loc) · 3.77 KB
/
calibrators.py
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
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
import numpy as np
import torch
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from tqdm import tqdm
def softplus(x):
"""Transform the input to positive output."""
return F.softplus(x, 1.0, 20.0) + 1e-6
def inv_softplus(y):
"""Inverse softplus function."""
if torch.any(y <= 0.0):
raise ValueError("Input to `inv_softplus` must be positive.")
_y = y - 1e-6
return _y + torch.log(-torch.expm1(-_y))
def BCE(yhat, y):
"""Compute binary cross-entropy loss for a vector of predictions
Parameters
----------
yhat
An array with len(yhat) predictions between [0, 1]
y
An array with len(y) labels where each is one of {0, 1}
"""
yhat = np.clip(yhat, 1e-6, 1 - 1e-6)
return -(y * np.log(yhat) + (1 - y) * np.log(1 - yhat)).mean()
class Calibrator(torch.nn.Module):
def __init__(self):
super().__init__()
self.epsilon = 1e-2
def preprocess_probs(self, probs):
if not isinstance(probs, torch.Tensor):
probs = torch.tensor(probs)
probs = probs.view(-1, 1).float()
probs = torch.clip(probs, self.epsilon, 1 - self.epsilon)
return probs
def preprocess_labels(self, labels):
if not isinstance(labels, torch.Tensor):
labels = torch.tensor(labels)
labels = labels.view(-1, 1).float()
return labels
def fit(self, probs, labels, num_iter=300):
probs = self.preprocess_probs(probs)
labels = self.preprocess_labels(labels)
criterion = torch.nn.BCELoss()
optimizer = torch.optim.LBFGS(self.parameters())
def closure():
if torch.is_grad_enabled():
optimizer.zero_grad()
new_probs = self.forward(probs)
loss = criterion(new_probs, labels)
if loss.requires_grad:
loss.backward()
return loss
self.train()
old_loss = None
for _ in tqdm(range(num_iter)):
loss = optimizer.step(closure)
if old_loss is None:
old_loss = loss.item()
else:
delta = abs(loss - old_loss)
if delta < 1e-2:
break
self.eval()
def save_model(self, model_path):
torch.save(self.state_dict(), model_path)
def load_model(self, model_path):
self.load_state_dict(torch.load(model_path))
self.eval()
def transform(self, probs):
raise NotImplementedError
def forward(self, probs):
raise NotImplementedError
class DoublyBoundedScaling(Calibrator):
def __init__(self):
super().__init__()
self._a = Parameter(inv_softplus(torch.tensor(1.0)))
self._b = Parameter(inv_softplus(torch.tensor(1.0)))
@property
def a(self):
return softplus(self._a)
@property
def b(self):
return softplus(self._b)
def forward(self, probs):
new_probs = 1 - (1 - probs**self.a)**self.b
return new_probs
def transform(self, probs):
with torch.no_grad():
probs = self.preprocess_probs(probs)
new_probs = self(probs)
return new_probs.numpy().ravel()
class PlattScaling(Calibrator):
def __init__(self):
super().__init__()
self.w = Parameter(torch.tensor(1.0))
self.b = Parameter(torch.tensor(0.0))
def forward(self, probs):
new_probs = torch.sigmoid(self.w * probs + self.b)
return new_probs
def transform(self, probs):
with torch.no_grad():
probs = self.preprocess_probs(probs)
new_probs = self(probs)
return new_probs.numpy().ravel()
class TemperatureScaling(PlattScaling):
def __init__(self):
super().__init__()
self.b.requires_grad = False