-
Notifications
You must be signed in to change notification settings - Fork 33
/
utils.py
325 lines (265 loc) · 10.6 KB
/
utils.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
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
import sys
import numpy as np
def model_conversion(model):
"""Convert model to callable."""
if safe_isinstance(model, "sklearn.base.ClassifierMixin"):
return lambda x: model.predict_proba(x)
elif safe_isinstance(model, "sklearn.base.RegressorMixin"):
return lambda x: model.predict(x)
elif safe_isinstance(model, "catboost.CatBoostClassifier"):
return lambda x: model.predict_proba(x)
elif safe_isinstance(model, "catboost.CatBoostRegressor"):
return lambda x: model.predict(x)
elif safe_isinstance(model, "lightgbm.basic.Booster"):
return lambda x: model.predict(x)
elif safe_isinstance(model, "xgboost.core.Booster"):
import xgboost
return lambda x: model.predict(xgboost.DMatrix(x))
elif safe_isinstance(model, "torch.nn.Module"):
print(
"Setting up imputer for PyTorch model, assuming that any "
"necessary output activations are applied properly. If "
"not, please set up nn.Sequential with nn.Sigmoid or nn.Softmax"
)
import torch
model.eval()
device = next(model.parameters()).device
return (
lambda x: model(torch.tensor(x, dtype=torch.float32, device=device))
.cpu()
.data.numpy()
)
elif safe_isinstance(model, "keras.Model"):
print(
"Setting up imputer for keras model, assuming that any "
"necessary output activations are applied properly. If not, "
"please set up keras.Sequential with keras.layers.Softmax()"
)
return lambda x: model(x, training=False).numpy()
elif callable(model):
# Assume model is compatible function or callable object.
return model
else:
raise ValueError(
"model cannot be converted automatically, "
"please convert to a lambda function"
)
def dataset_output(imputer, X, batch_size):
"""Get model output for entire dataset."""
Y = []
for i in range(int(np.ceil(len(X) / batch_size))):
x = X[i * batch_size : (i + 1) * batch_size]
pred = imputer(x, np.ones((len(x), imputer.num_groups), dtype=bool))
Y.append(pred)
return np.concatenate(Y)
def verify_model_data(imputer, X, Y, loss, batch_size):
"""Ensure that model and data are set up properly."""
check_labels = True
if Y is None:
print("Calculating model sensitivity (Shapley Effects, not SAGE)")
check_labels = False
Y = dataset_output(imputer, X, batch_size)
# Fix output shape for classification tasks.
if isinstance(loss, (CrossEntropyLoss, ZeroOneLoss)):
if Y.shape == (len(X),):
Y = Y[:, np.newaxis]
if Y.shape[1] == 1:
Y = np.concatenate([1 - Y, Y], axis=1)
if isinstance(loss, (CrossEntropyLoss, ZeroOneLoss)):
x = X[:batch_size]
probs = imputer(x, np.ones((len(x), imputer.num_groups), dtype=bool))
# Check labels shape.
if check_labels:
Y = Y.astype(int)
if Y.shape == (len(X),):
# This is the preferred shape.
pass
elif Y.shape == (len(X), 1):
Y = Y[:, 0]
else:
raise ValueError(
"labels shape should be (batch,) or (batch, 1)"
" for cross entropy loss"
)
if (probs.ndim == 1) or (probs.shape[1] == 1):
# Check label encoding.
if check_labels:
unique_labels = np.unique(Y)
if np.array_equal(unique_labels, np.array([0, 1])):
# This is the preferred labeling.
pass
elif np.array_equal(unique_labels, np.array([-1, 1])):
# Set -1 to 0.
Y = Y.copy()
Y[Y == -1] = 0
else:
raise ValueError(
"labels for binary classification must be " "[0, 1] or [-1, 1]"
)
# Check for valid probability outputs.
valid_probs = np.all(np.logical_and(probs >= 0, probs <= 1))
elif probs.ndim == 2:
# Multiclass output, check for valid probability outputs.
valid_probs = np.all(np.logical_and(probs >= 0, probs <= 1))
ones = np.sum(probs, axis=1)
valid_probs = valid_probs and np.allclose(ones, np.ones(ones.shape))
else:
raise ValueError("prediction has too many dimensions")
if not valid_probs:
raise ValueError("predictions are not valid probabilities")
return X, Y
class ImportanceTracker:
"""For tracking feature importance using a dynamic average."""
def __init__(self):
self.mean = 0
self.sum_squares = 0
self.N = 0
def update(self, scores, num_samples=None):
"""
Update mean and sum of squares using Welford's algorithm.
Args:
scores: array of consisting of n samples with shape (n, dim).
num_samples: array of size (dim,) representing the number of samples
for each dimension. For sparse updates, with void samples
represented by zeros.
"""
if num_samples is None:
# Welford's algorithm.
self.N += len(scores)
diff = scores - self.mean
self.mean += np.sum(diff, axis=0) / self.N
diff2 = scores - self.mean
self.sum_squares += np.sum(diff * diff2, axis=0)
else:
# Welford's algorithm with correction for void samples.
assert num_samples.shape == scores.shape[1:]
self.N = self.N + num_samples
num_void = len(scores) - num_samples
orig_mean = np.copy(self.mean)
diff = scores - self.mean
self.mean += (np.sum(diff, axis=0) + self.mean * num_void) / np.maximum(
self.N, 1
)
diff2 = scores - self.mean
self.sum_squares += (
np.sum(diff * diff2, axis=0) - orig_mean * self.mean * num_void
)
@property
def values(self):
return self.mean
@property
def var(self):
# print('sum_squares', self.sum_squares)
return self.sum_squares / (np.maximum(self.N, 1) ** 2)
@property
def std(self):
return self.var**0.5
class MSELoss:
"""MSE loss that sums over non-batch dimensions."""
def __init__(self, reduction="mean"):
assert reduction in ("none", "mean")
self.reduction = reduction
def __call__(self, pred, target):
# Add dimension if necessary.
if target.shape[-1] == 1 and len(target.shape) - len(pred.shape) == 1:
pred = np.expand_dims(pred, -1)
elif pred.shape[-1] == 1 and len(pred.shape) - len(target.shape) == 1:
target = np.expand_dims(target, -1)
elif not target.shape == pred.shape:
raise ValueError(
"shape mismatch, pred has shape {} and target " "has shape {}".format(
pred.shape, target.shape
)
)
loss = np.sum(np.reshape((pred - target) ** 2, (len(pred), -1)), axis=1)
if self.reduction == "mean":
return np.mean(loss)
else:
return loss
class ZeroOneLoss:
"""zero-one loss that expects probabilities."""
def __init__(self, reduction="mean"):
assert reduction in ("none", "mean")
self.reduction = reduction
def __call__(self, pred, target):
# Add a dimension to prediction probabilities if necessary.
if pred.ndim == 1:
pred = pred[:, np.newaxis]
if pred.shape[1] == 1:
pred = np.append(1 - pred, pred, axis=1)
if target.ndim == 1:
# Class labels.
loss = (np.argmax(pred, axis=1) != target).astype(float)
elif target.ndim == 2:
# Probabilistic labels.
loss = (np.argmax(pred, axis=1) != np.argmax(target, axis=1)).astype(float)
else:
raise ValueError("incorrect labels shape for zero-one loss")
if self.reduction == "mean":
return np.mean(loss)
return loss
class CrossEntropyLoss:
"""Cross entropy loss that expects probabilities."""
def __init__(self, reduction="mean"):
assert reduction in ("none", "mean")
self.reduction = reduction
def __call__(self, pred, target, eps=1e-12):
# Clip.
pred = np.clip(pred, eps, 1 - eps)
# Add a dimension to prediction probabilities if necessary.
if pred.ndim == 1:
pred = pred[:, np.newaxis]
if pred.shape[1] == 1:
pred = np.append(1 - pred, pred, axis=1)
# Calculate loss.
if target.ndim == 1:
# Class labels.
loss = -np.log(pred[np.arange(len(pred)), target])
elif target.ndim == 2:
# Probabilistic labels.
loss = -np.sum(target * np.log(pred), axis=1)
else:
raise ValueError("incorrect labels shape for cross entropy loss")
if self.reduction == "mean":
return np.mean(loss)
else:
return loss
def get_loss(loss, reduction="mean"):
"""Get loss function by name."""
if loss == "cross entropy":
loss_fn = CrossEntropyLoss(reduction=reduction)
elif loss == "mse":
loss_fn = MSELoss(reduction=reduction)
else:
raise ValueError("unsupported loss: {}".format(loss))
return loss_fn
def sample_subset_feature(input_size, n, ind):
"""
Sample a subset of features where a given feature index must not be
included. This helper function is used for estimating Shapley values, so
the subset is sampled by 1) sampling the number of features to be included
from a uniform distribution, and 2) sampling the features to be included.
"""
S = np.zeros((n, input_size), dtype=bool)
choices = list(range(input_size))
del choices[ind]
for row in S:
inds = np.random.choice(
choices,
size=np.random.choice(input_size),
replace=False,
)
row[inds] = 1
return S
def safe_isinstance(obj, class_str):
"""Check isinstance without requiring imports."""
if not isinstance(class_str, str):
return False
module_name, class_name = class_str.rsplit(".", 1)
if module_name not in sys.modules:
return False
module = sys.modules[module_name]
class_type = getattr(module, class_name, None)
if class_type is None:
return False
return isinstance(obj, class_type)