-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathmetric_wrapper.py
333 lines (269 loc) · 10.7 KB
/
metric_wrapper.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
326
327
328
329
330
331
332
333
import operator as op
from copy import deepcopy
from typing import Union, Callable, Optional, Dict, Any
import warnings
import torch
from torchmetrics.functional import (
accuracy,
average_precision,
confusion_matrix,
f1,
fbeta,
precision_recall_curve,
precision,
recall,
auroc,
mean_absolute_error,
mean_squared_error,
)
from torchmetrics.utilities import reduce
EPS = 1e-5
class Thresholder:
def __init__(
self,
threshold: float,
operator: str = "greater",
th_on_preds: bool = True,
th_on_target: bool = False,
target_to_int: bool = False,
):
# Basic params
self.threshold = threshold
self.th_on_target = th_on_target
self.th_on_preds = th_on_preds
self.target_to_int = target_to_int
# Operator can either be a string, or a callable
if isinstance(operator, str):
op_name = operator.lower()
if op_name in ["greater", "gt"]:
op_str = ">"
operator = op.gt
elif op_name in ["lower", "lt"]:
op_str = "<"
operator = op.lt
else:
raise ValueError(f"operator `{op_name}` not supported")
elif callable(operator):
op_str = operator.__name__
elif operator is None:
pass
else:
raise TypeError(f"operator must be either `str` or `callable`, "
f"provided: `{type(operator)}`")
self.operator = operator
self.op_str = op_str
def compute(self, preds: torch.Tensor, target: torch.Tensor):
# Apply the threshold on the predictions
if self.th_on_preds:
preds = self.operator(preds, self.threshold)
# Apply the threshold on the targets
if self.th_on_target:
target = self.operator(target, self.threshold)
if self.target_to_int:
target = target.to(int)
return preds, target
def __call__(self, preds: torch.Tensor, target: torch.Tensor):
return self.compute(preds, target)
def __repr__(self):
r"""
Control how the class is printed
"""
return f"{self.op_str}{self.threshold}"
def pearsonr(preds: torch.Tensor, target: torch.Tensor,
reduction: str = "elementwise_mean") -> torch.Tensor:
r"""
Computes the pearsonr correlation.
Parameters:
preds: estimated labels
target: ground truth labels
reduction: a method to reduce metric score over labels.
- ``'elementwise_mean'``: takes the mean (default)
- ``'sum'``: takes the sum
- ``'none'``: no reduction will be applied
Returns:
Tensor with the pearsonr
!!! Example
``` python linenums="1"
x = torch.tensor([0., 1, 2, 3])
y = torch.tensor([0., 1, 2, 2])
pearsonr(x, y)
>>> tensor(0.9439)
```
"""
preds, target = preds.to(torch.float32), target.to(torch.float32)
shifted_x = preds - torch.mean(preds, dim=0)
shifted_y = target - torch.mean(target, dim=0)
sigma_x = torch.sqrt(torch.sum(shifted_x ** 2, dim=0))
sigma_y = torch.sqrt(torch.sum(shifted_y ** 2, dim=0))
pearson = torch.sum(shifted_x * shifted_y, dim=0) / (sigma_x * sigma_y + EPS)
pearson = torch.clamp(pearson, min=-1, max=1)
pearson = reduce(pearson, reduction=reduction)
return pearson
def _get_rank(values):
arange = torch.arange(values.shape[0],
dtype=values.dtype, device=values.device)
val_sorter = torch.argsort(values, dim=0)
val_rank = torch.empty_like(values)
if values.ndim == 1:
val_rank[val_sorter] = arange
elif values.ndim == 2:
for ii in range(val_rank.shape[1]):
val_rank[val_sorter[:, ii], ii] = arange
else:
raise ValueError(f"Only supports tensors of dimensions 1 and 2, "
f"provided dim=`{values.ndim}`")
return val_rank
def spearmanr(preds: torch.Tensor, target: torch.Tensor,
reduction: str = "elementwise_mean") -> torch.Tensor:
r"""
Computes the spearmanr correlation.
Parameters:
preds: estimated labels
target: ground truth labels
reduction: a method to reduce metric score over labels.
- ``'elementwise_mean'``: takes the mean (default)
- ``'sum'``: takes the sum
- ``'none'``: no reduction will be applied
Returns:
Tensor with the spearmanr
!!! Example
x = torch.tensor([0., 1, 2, 3])
y = torch.tensor([0., 1, 2, 1.5])
spearmanr(x, y)
tensor(0.8)
"""
spearman = pearsonr(_get_rank(preds), _get_rank(target), reduction=reduction)
return spearman
METRICS_CLASSIFICATION = {
"accuracy": accuracy,
"averageprecision": average_precision,
"auroc": auroc,
"confusionmatrix": confusion_matrix,
"f1": f1,
"fbeta": fbeta,
"precisionrecallcurve": precision_recall_curve,
"precision": precision,
"recall": recall,
}
METRICS_REGRESSION = {
"mae": mean_absolute_error,
"mse": mean_squared_error,
"pearsonr": pearsonr,
"spearmanr": spearmanr,
}
METRICS_DICT = deepcopy(METRICS_CLASSIFICATION)
METRICS_DICT.update(METRICS_REGRESSION)
class MetricWrapper:
r"""
Allows to initialize a metric from a name or Callable, and initialize the
`Thresholder` in case the metric requires a threshold.
"""
def __init__(
self,
metric: Union[str, Callable],
threshold_kwargs: Optional[Dict[str, Any]] = None,
target_nan_mask: Optional[Union[str, int]] = None,
**kwargs,
):
r"""
Parameters
metric:
The metric to use. See `METRICS_DICT`
threshold_kwargs:
If `None`, no threshold is applied.
Otherwise, we use the class `Thresholder` is initialized with the
provided argument, and called before the `compute`
target_nan_mask:
- None: Do not change behaviour if there are NaNs
- int, float: Value used to replace NaNs. For example, if `target_nan_mask==0`, then
all NaNs will be replaced by zeros
- 'ignore-flatten': The Tensor will be reduced to a vector without the NaN values.
- 'ignore-mean-label': NaNs will be ignored when computing the loss. Note that each column
has a different number of NaNs, so the metric will be computed separately
on each column, and the metric result will be averaged over all columns.
*This option might slowdown the computation if there are too many labels*
kwargs:
Other arguments to call with the metric
"""
self.metric = METRICS_DICT[metric] if isinstance(metric, str) else metric
self.thresholder = None
if threshold_kwargs is not None:
self.thresholder = Thresholder(**threshold_kwargs)
self.target_nan_mask = target_nan_mask
self.kwargs = kwargs
def compute(self, preds: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
r"""
Compute the metric, apply the thresholder if provided, and manage the NaNs
"""
if preds.ndim == 1:
preds = preds.unsqueeze(-1)
if target.ndim == 1:
target = target.unsqueeze(-1)
target_nans = torch.isnan(target)
# Threshold the prediction
if self.thresholder is not None:
preds, target = self.thresholder(preds, target)
# Manage the NaNs
if self.target_nan_mask is None:
pass
elif isinstance(self.target_nan_mask, (int, float)):
target = target.clone()
target[torch.isnan(target)] = self.target_nan_mask
elif self.target_nan_mask == "ignore-flatten":
target = target[~target_nans]
preds = preds[~target_nans]
elif self.target_nan_mask == "ignore-mean-label":
target_list = [target[..., ii][~target_nans[..., ii]] for ii in range(target.shape[-1])]
preds_list = [preds[..., ii][~target_nans[..., ii]] for ii in range(preds.shape[-1])]
target = target_list
preds = preds_list
else:
raise ValueError(f"Invalid option `{self.target_nan_mask}`")
if self.target_nan_mask == "ignore-mean-label":
warnings.filterwarnings("error")
# Compute the metric for each column, and output nan if there's an error on a given column
metric_val = []
for ii in range(len(target)):
try:
kwargs = self.kwargs.copy()
if 'cast_to_int' in kwargs and kwargs['cast_to_int']:
del kwargs['cast_to_int']
res = self.metric(preds[ii], target[ii].int(), **kwargs)
else:
res = self.metric(preds[ii], target[ii], **kwargs)
metric_val.append(res)
except Exception as e:
# For torchmetrics.functional.auroc do not include 0 for
# targets that don't have positive examples. This is what
# the OGB evaluator does, i.e. ignore those targets.
# Catching the Warning risen by torchmetrics.functional.auroc
# already prevents the 0 to be appended, nothing else needs
# to be done.
if str(e) == 'No positive samples in targets, ' \
'true positive value should be meaningless. ' \
'Returning zero tensor in true positive score':
pass
else:
print(e)
warnings.filterwarnings("default")
# Average the metric
# metric_val = torch.nanmean(torch.stack(metric_val)) # PyTorch1.10
x = torch.stack(metric_val) # PyTorch<=1.9
metric_val = torch.div(torch.nansum(x),
(~torch.isnan(x)).count_nonzero())
else:
metric_val = self.metric(preds, target, **self.kwargs)
return metric_val
def __call__(self, preds: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
r"""
Compute the metric with the method `self.compute`
"""
return self.compute(preds, target)
def __repr__(self):
r"""
Control how the class is printed
"""
full_str = f"{self.metric.__name__}"
if self.thresholder is not None:
full_str += f"({self.thresholder})"
return full_str