-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathevaluation.py
351 lines (278 loc) · 13.2 KB
/
evaluation.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# Copyright 2022 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Evaluation metrics for conformal prediction."""
from typing import Tuple
import jax
import jax.numpy as jnp
def _check_labels(probabilities: jnp.ndarray, labels: jnp.ndarray):
"""Helper to check shapes or probabilities/sets and labels.
Checks shapes of probabilities of confidence sets and labels for
evaluation.
Args:
probabilities: probabilities or confidence sets
labels: corresponding ground truth labels
Raises:
ValueError if shapes do not match.
"""
if probabilities.ndim != 2:
raise ValueError('Expecting probabilities/confidence sets of '
'shape n_examples x n_classes.')
if labels.ndim != 1:
raise ValueError('Expecting labels of shape n_examples.')
if probabilities.shape[1] == 0:
raise ValueError('Expecting at least one class.')
if probabilities.shape[0] != labels.shape[0]:
raise ValueError('Number of probabilities/confidence sets does '
'not match number of labels.')
if not jnp.issubdtype(labels.dtype, jnp.integer):
raise ValueError('Expecting labels to be integers.')
if jnp.max(labels) >= probabilities.shape[1]:
raise ValueError(
'labels contains more classes than probabilities/confidence sets.')
def _check_one_hot_labels(
probabilities: jnp.ndarray, one_hot_labels: jnp.ndarray):
"""Helper to check shapes of probabilities/sets and one-hot labels.
Args:
probabilities: probabilities or confidence sets
one_hot_labels: corresponding ground truth labels in one-hot format
Raises:
ValueError if shapes do not match.
"""
if probabilities.ndim != 2:
raise ValueError('Expecting probabilities/confidence sets of '
'shape n_examples x n_classes.')
if one_hot_labels.ndim != 2:
raise ValueError('Expecting labels in one-hot format of '
'shape n_examples x n_classes.')
if probabilities.shape[1] == 0:
raise ValueError('Expecting at least one class.')
if probabilities.shape[0] != one_hot_labels.shape[0]:
raise ValueError('Number of probabilities/confidence sets does '
'not match number of labels.')
if probabilities.shape[1] != one_hot_labels.shape[1]:
raise ValueError('Number of classes in probabilities/confidence '
'sets and one-hot labels do not match.')
def _check_conditional_labels(
probabilities: jnp.ndarray,
conditional_labels: jnp.ndarray):
"""Helper to check conditional_labels for metric computation.
Args:
probabilities: probabilities or confidence sets
conditional_labels: labels tp condition on for all examples
Raises:
ValueError if shapes do not match
"""
if conditional_labels.ndim != 1:
raise ValueError('Expecting conditional_labels of shape n_examples.')
if conditional_labels.shape[0] != probabilities.shape[0]:
raise ValueError('Number of probabilities/confidence sets does '
'not match number of conditional labels.')
if not jnp.issubdtype(conditional_labels.dtype, jnp.integer):
raise ValueError('Expecting conditional labels to be integers.')
def compute_conditional_accuracy(
probabilities: jnp.ndarray, labels: jnp.ndarray,
conditional_labels: jnp.ndarray, conditional_label: int) -> float:
"""Computes conditional accuracy given softmax probabilities and labels.
Conditional accuracy is defined as the accuracy on a subset of the examples
as selected using the conditional label(s). For example, this allows
to compute accuracy conditioned on class labels.
Args:
probabilities: predicted probabilities on test set
labels: ground truth labels on test set
conditional_labels: conditional labels to compute accuracy on
conditional_label: selected conditional label to compute accuracy on
Returns:
Accuracy
"""
selected = (conditional_labels == conditional_label)
num_examples = jnp.sum(selected)
predictions = jnp.argmax(probabilities, axis=1)
error = selected * (predictions != labels)
error = jnp.where(num_examples == 0, 1, jnp.sum(error)/num_examples)
return 1 - error
def compute_conditional_accuracy_with_checks(
probabilities: jnp.ndarray, labels: jnp.ndarray,
conditional_labels: jnp.ndarray, conditional_label: int) -> float:
"""compute_conditional_accuracy with extra argument checks."""
_check_labels(probabilities, labels)
_check_conditional_labels(probabilities, conditional_labels)
return compute_conditional_accuracy(
probabilities, labels, conditional_labels, conditional_label)
def compute_accuracy(probabilities: jnp.ndarray, labels: jnp.ndarray) -> float:
"""Compute unconditional accuracy using compute_conditional_accuracy."""
return compute_conditional_accuracy(
probabilities, labels, jnp.zeros(labels.shape, int), 0)
def compute_accuracy_with_checks(
probabilities: jnp.ndarray, labels: jnp.ndarray) -> float:
"""compute_accuracy with additional argument checks raising ValuzeError."""
return compute_conditional_accuracy_with_checks(
probabilities, labels, jnp.zeros(labels.shape, int), 0)
def compute_conditional_multi_coverage(
confidence_sets: jnp.ndarray, one_hot_labels: jnp.ndarray,
conditional_labels: jnp.ndarray, conditional_label: int) -> float:
"""Compute coverage of confidence sets, potentially for multiple labels.
The given labels are assumed to be one-hot labels and the implementation
supports checking coverage of multiple classes, i.e., whether one of
the given ground truth labels is in the confidence set.
Args:
confidence_sets: confidence sets on test set as 0-1 array
one_hot_labels: ground truth labels on test set in one-hot format
conditional_labels: conditional labels to compute coverage on a subset
conditional_label: selected conditional to compute coverage for
Returns:
Coverage.
"""
selected = (conditional_labels == conditional_label)
num_examples = jnp.sum(selected)
coverage = selected * jnp.clip(
jnp.sum(confidence_sets * one_hot_labels, axis=1), 0, 1)
coverage = jnp.where(num_examples == 0, 1, jnp.sum(coverage)/num_examples)
return coverage
def compute_conditional_multi_coverage_with_checks(
confidence_sets: jnp.ndarray, one_hot_labels: jnp.ndarray,
conditional_labels: jnp.ndarray, conditional_label: int) -> float:
"""compute_conditional_multi_coverage with additional argument checks."""
_check_one_hot_labels(confidence_sets, one_hot_labels)
_check_conditional_labels(confidence_sets, conditional_labels)
return compute_conditional_multi_coverage(
confidence_sets, one_hot_labels, conditional_labels, conditional_label)
def compute_coverage(
confidence_sets: jnp.ndarray, labels: jnp.ndarray) -> float:
"""Compute unconditional coverage using compute_conditional_multi_coverage.
Args:
confidence_sets: confidence sets on test set as 0-1 array
labels: ground truth labels on test set (not in one-hot format)
Returns:
Coverage.
"""
one_hot_labels = jax.nn.one_hot(labels, confidence_sets.shape[1])
return compute_conditional_multi_coverage(
confidence_sets, one_hot_labels, jnp.zeros(labels.shape, int), 0)
def compute_coverage_with_checks(
confidence_sets: jnp.ndarray, labels: jnp.ndarray) -> float:
"""compute_coverage with additional argument checks raising ValueError."""
return compute_conditional_coverage_with_checks(
confidence_sets, labels, jnp.zeros(labels.shape, int), 0)
def compute_conditional_coverage(
confidence_sets: jnp.ndarray, labels: jnp.ndarray,
conditional_labels: jnp.ndarray, conditional_label: int) -> float:
"""Compute conditional coverage using compute_conditional_multi_coverage.
Args:
confidence_sets: confidence sets on test set as 0-1 array
labels: ground truth labels on test set (not in one-hot format)
conditional_labels: conditional labels to compute coverage on a subset
conditional_label: selected conditional to compute coverage for
Returns:
Conditional coverage.
"""
one_hot_labels = jax.nn.one_hot(labels, confidence_sets.shape[1])
return compute_conditional_multi_coverage(
confidence_sets, one_hot_labels, conditional_labels, conditional_label)
def compute_conditional_coverage_with_checks(
confidence_sets: jnp.ndarray, labels: jnp.ndarray,
conditional_labels: jnp.ndarray, conditional_label: int) -> float:
"""compute_conditional_coverage with additional argument checks raising."""
_check_labels(confidence_sets, labels)
_check_conditional_labels(confidence_sets, conditional_labels)
return compute_conditional_coverage(
confidence_sets, labels, conditional_labels, conditional_label)
def compute_miscoverage(
confidence_sets: jnp.ndarray, one_hot_labels: jnp.ndarray) -> float:
"""Compute mis-coverage for given one-hot labels.
Mis-coverage is the coverage for multiple labels as given
in one_hot_labels that should not be included in the sets.
Args:
confidence_sets: confidence sets on test set as 0-1 array
one_hot_labels: ground truth labels on test set in one-hot format
Returns:
Mis-coverage.
"""
return compute_conditional_multi_coverage(
confidence_sets, one_hot_labels,
jnp.zeros(confidence_sets.shape[0], int), 0)
def compute_miscoverage_with_checks(
confidence_sets: jnp.ndarray, one_hot_labels: jnp.ndarray) -> float:
"""compute_miscoverage with additional argument checks."""
_check_one_hot_labels(confidence_sets, one_hot_labels)
return compute_miscoverage(confidence_sets, one_hot_labels)
def compute_conditional_miscoverage(
confidence_sets: jnp.ndarray, one_hot_labels: jnp.ndarray,
conditional_labels: jnp.ndarray, conditional_label: int) -> float:
"""Compute conditional mis-coverage for given one-hot labels.
Args:
confidence_sets: confidence sets on test set as 0-1 array
one_hot_labels: ground truth labels on test set in one-hot format
conditional_labels: conditional labels to compute coverage on a subset
conditional_label: selected conditional to compute coverage for
Returns:
Mis-coverage.
"""
return compute_conditional_multi_coverage(
confidence_sets, one_hot_labels,
conditional_labels, conditional_label)
def compute_conditional_miscoverage_with_checks(
confidence_sets: jnp.ndarray, one_hot_labels: jnp.ndarray,
conditional_labels: jnp.ndarray, conditional_label: int) -> float:
"""compute_conditional_miscoverage with additional argument checks."""
_check_one_hot_labels(confidence_sets, one_hot_labels)
_check_conditional_labels(confidence_sets, conditional_labels)
return compute_conditional_miscoverage(
confidence_sets, one_hot_labels, conditional_labels, conditional_label)
def _check_confidence_sets(confidence_sets: jnp.ndarray):
"""Helper to check shape of confidence sets.
Args:
confidence_sets: predicted confidence sets
Raises:
ValueError if shape is incorrect.
"""
if confidence_sets.ndim != 2:
raise ValueError(
'Expecting confidence_sets of shape n_examples x n_classes.')
if confidence_sets.shape[1] == 0:
raise ValueError('Expecting at least one class.')
def compute_conditional_size(
confidence_sets: jnp.ndarray,
conditional_labels: jnp.ndarray,
conditional_label: int) -> Tuple[float, int]:
"""Compute confidence set size.
Args:
confidence_sets: confidence sets on test set
conditional_labels: conditional labels to compute size on
conditional_label: selected conditional to compute size for
Returns:
Average size.
"""
selected = (conditional_labels == conditional_label)
num_examples = jnp.sum(selected)
size = selected * jnp.sum(confidence_sets, axis=1)
size = jnp.where(num_examples == 0, 0, jnp.sum(size)/num_examples)
return size, num_examples
def compute_conditional_size_with_checks(
confidence_sets: jnp.ndarray,
conditional_labels: jnp.ndarray,
conditional_label: int) -> Tuple[float, int]:
"""compute_conditional_size with additional argument checks."""
_check_confidence_sets(confidence_sets)
_check_conditional_labels(confidence_sets, conditional_labels)
return compute_conditional_size(
confidence_sets, conditional_labels, conditional_label)
def compute_size(confidence_sets: jnp.ndarray) -> Tuple[float, int]:
"""Compute unconditional coverage using compute_conditional_coverage."""
return compute_conditional_size(
confidence_sets, jnp.zeros(confidence_sets.shape[0], int), 0)
def compute_size_with_checks(confidence_sets: jnp.ndarray) -> Tuple[float, int]:
"""compute_size with additional argument checks raising ValueError."""
return compute_conditional_size_with_checks(
confidence_sets, jnp.zeros(confidence_sets.shape[0], int), 0)