-
Notifications
You must be signed in to change notification settings - Fork 1
/
metrics.py
413 lines (342 loc) · 13.8 KB
/
metrics.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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
"""
"""
from numbers import Real
from typing import Any, List, Optional, Sequence, Tuple, Union
import numpy as np
from easydict import EasyDict as ED
from cfg import BaseCfg
from utils import dict_to_str
__all__ = [
"CPSC2020_loss",
"CPSC2020_score",
"eval_score",
]
def CPSC2020_loss(y_true: np.ndarray, y_pred: np.ndarray, y_indices: np.ndarray, dtype: type = str, verbose: int = 0) -> int:
"""finished, updated with the latest (updated on 2020.8.31) official function
Parameters:
-----------
y_true: ndarray,
array of ground truth of beat types
y_true: ndarray,
array of predictions of beat types
y_indices: ndarray,
indices of beat (rpeak) in the original ecg signal
dtype: type, default str,
dtype of `y_true` and `y_pred`
Returns:
--------
total_loss: int,
the total loss of all ectopic beat types (SPB, PVC)
"""
classes = ["S", "V"]
truth_arr = {}
pred_arr = {}
if dtype == str:
for c in classes:
truth_arr[c] = y_indices[np.where(y_true == c)[0]]
pred_arr[c] = y_indices[np.where(y_pred == c)[0]]
elif dtype == int:
for c in classes:
truth_arr[c] = y_indices[np.where(y_true == BaseCfg.class_map[c])[0]]
pred_arr[c] = y_indices[np.where(y_pred == BaseCfg.class_map[c])[0]]
true_positive = {c: 0 for c in classes}
for c in classes:
for tc in truth_arr[c]:
pc = np.where(abs(pred_arr[c] - tc) <= BaseCfg.bias_thr)[0]
if pc.size > 0:
true_positive[c] += 1
false_positive = {c: len(pred_arr[c]) - true_positive[c] for c in classes}
false_negative = {c: len(truth_arr[c]) - true_positive[c] for c in classes}
false_positive_loss = {c: 1 for c in classes}
false_negative_loss = {c: 5 for c in classes}
if verbose >= 1:
print(f"true_positive = {dict_to_str(true_positive)}")
print(f"false_positive = {dict_to_str(false_positive)}")
print(f"false_negative = {dict_to_str(false_negative)}")
total_loss = sum([false_positive[c] * false_positive_loss[c] + false_negative[c] * false_negative_loss[c] for c in classes])
return total_loss
def CPSC2020_score(
spb_true: List[np.ndarray],
pvc_true: List[np.ndarray],
spb_pred: List[np.ndarray],
pvc_pred: List[np.ndarray],
verbose: int = 0,
) -> Union[Tuple[int], dict]:
"""finished, checked,
Score Function for all (test) records
Parameters:
-----------
spb_true, pvc_true, spb_pred, pvc_pred: list of ndarray,
verbose: int
Returns:
--------
retval: tuple or dict,
tuple of (negative) scores for each ectopic beat type (SPB, PVC), or
dict of more scoring details, including
- total_loss: sum of loss of each ectopic beat type (PVC and SPB)
- true_positive: number of true positives of each ectopic beat type
- false_positive: number of false positives of each ectopic beat type
- false_negative: number of false negatives of each ectopic beat type
"""
s_score = np.zeros(
[
len(spb_true),
],
dtype=int,
)
v_score = np.zeros(
[
len(spb_true),
],
dtype=int,
)
true_positive = ED({"S": 0, "V": 0})
false_positive = ED({"S": 0, "V": 0})
false_negative = ED({"S": 0, "V": 0})
## Scoring ##
for i, (s_ref, v_ref, s_pos, v_pos) in enumerate(zip(spb_true, pvc_true, spb_pred, pvc_pred)):
s_tp = 0
s_fp = 0
s_fn = 0
v_tp = 0
v_fp = 0
v_fn = 0
# SPB
if s_ref.size == 0:
s_fp = len(s_pos)
else:
for m, ans in enumerate(s_ref):
s_pos_cand = np.where(abs(s_pos - ans) <= BaseCfg.bias_thr)[0]
if s_pos_cand.size == 0:
s_fn += 1
else:
s_tp += 1
s_fp += len(s_pos_cand) - 1
# PVC
if v_ref.size == 0:
v_fp = len(v_pos)
else:
for m, ans in enumerate(v_ref):
v_pos_cand = np.where(abs(v_pos - ans) <= BaseCfg.bias_thr)[0]
if v_pos_cand.size == 0:
v_fn += 1
else:
v_tp += 1
v_fp += len(v_pos_cand) - 1
# calculate the score
s_score[i] = s_fp * (-1) + s_fn * (-5)
v_score[i] = v_fp * (-1) + v_fn * (-5)
if verbose >= 3:
print(f"for the {i}-th record")
print(f"s_tp = {s_tp}, s_fp = {s_fp}, s_fn = {s_fn}")
print(f"v_tp = {v_tp}, v_fp = {v_fp}, v_fn = {v_fn}")
print(f"s_score[{i}] = {s_score[i]}, v_score[{i}] = {v_score[i]}")
true_positive.S += s_tp
true_positive.V += v_tp
false_positive.S += s_fp
false_positive.V += v_fp
false_negative.S += s_fn
false_negative.V += v_fn
Score1 = np.sum(s_score)
Score2 = np.sum(v_score)
if verbose >= 1:
retval = ED(
total_loss=-(Score1 + Score2),
class_loss={"S": -Score1, "V": -Score2},
true_positive=true_positive,
false_positive=false_positive,
false_negative=false_negative,
)
else:
retval = Score1, Score2
return retval
# -------------------------------------------------------
# the following are borrowed from CINC2020
# for classification of segments of ECGs using ECG_CRNN
def eval_score(classes: List[str], truth: Sequence, binary_pred: Sequence, scalar_pred: Sequence) -> Tuple[float]:
"""finished, checked,
for classification of segments of ECGs
Parameters:
-----------
classes: list of str,
list of all the classes, in the format of abbrevations
truth: sequence,
ground truth array, of shape (n_records, n_classes), with values 0 or 1
binary_pred: sequence,
binary predictions, of shape (n_records, n_classes), with values 0 or 1
scalar_pred: sequence,
probability predictions, of shape (n_records, n_classes), with values within [0,1]
Returns:
--------
auroc: float,
auprc: float,
accuracy: float,
f_measure: float,
f_beta_measure: float,
g_beta_measure: float,
"""
_truth = np.array(truth)
_binary_pred = np.array(binary_pred)
_scalar_pred = np.array(scalar_pred)
print("- AUROC and AUPRC...")
auroc, auprc = compute_auc(_truth, _scalar_pred)
print("- Accuracy...")
accuracy = compute_accuracy(_truth, _binary_pred)
print("- F-measure...")
f_measure = compute_f_measure(_truth, _binary_pred)
print("- F-beta and G-beta measures...")
f_beta_measure, g_beta_measure = compute_beta_measures(_truth, _binary_pred, beta=2)
print("Done.")
# Return the results.
return auroc, auprc, accuracy, f_measure, f_beta_measure, g_beta_measure
# Compute recording-wise accuracy.
def compute_accuracy(labels: np.ndarray, outputs: np.ndarray) -> float:
"""checked,"""
num_recordings, num_classes = np.shape(labels)
num_correct_recordings = 0
for i in range(num_recordings):
if np.all(labels[i, :] == outputs[i, :]):
num_correct_recordings += 1
return float(num_correct_recordings) / float(num_recordings)
# Compute confusion matrices.
def compute_confusion_matrices(labels: np.ndarray, outputs: np.ndarray, normalize: bool = False) -> np.ndarray:
"""checked,"""
# Compute a binary confusion matrix for each class k:
#
# [TN_k FN_k]
# [FP_k TP_k]
#
# If the normalize variable is set to true, then normalize the contributions
# to the confusion matrix by the number of labels per recording.
num_recordings, num_classes = np.shape(labels)
if not normalize:
A = np.zeros((num_classes, 2, 2))
for i in range(num_recordings):
for j in range(num_classes):
if labels[i, j] == 1 and outputs[i, j] == 1: # TP
A[j, 1, 1] += 1
elif labels[i, j] == 0 and outputs[i, j] == 1: # FP
A[j, 1, 0] += 1
elif labels[i, j] == 1 and outputs[i, j] == 0: # FN
A[j, 0, 1] += 1
elif labels[i, j] == 0 and outputs[i, j] == 0: # TN
A[j, 0, 0] += 1
else: # This condition should not happen.
raise ValueError("Error in computing the confusion matrix.")
else:
A = np.zeros((num_classes, 2, 2))
for i in range(num_recordings):
normalization = float(max(np.sum(labels[i, :]), 1))
for j in range(num_classes):
if labels[i, j] == 1 and outputs[i, j] == 1: # TP
A[j, 1, 1] += 1.0 / normalization
elif labels[i, j] == 0 and outputs[i, j] == 1: # FP
A[j, 1, 0] += 1.0 / normalization
elif labels[i, j] == 1 and outputs[i, j] == 0: # FN
A[j, 0, 1] += 1.0 / normalization
elif labels[i, j] == 0 and outputs[i, j] == 0: # TN
A[j, 0, 0] += 1.0 / normalization
else: # This condition should not happen.
raise ValueError("Error in computing the confusion matrix.")
return A
# Compute macro F-measure.
def compute_f_measure(labels: np.ndarray, outputs: np.ndarray) -> float:
"""checked,"""
num_recordings, num_classes = np.shape(labels)
A = compute_confusion_matrices(labels, outputs)
f_measure = np.zeros(num_classes)
for k in range(num_classes):
tp, fp, fn, tn = A[k, 1, 1], A[k, 1, 0], A[k, 0, 1], A[k, 0, 0]
if 2 * tp + fp + fn:
f_measure[k] = float(2 * tp) / float(2 * tp + fp + fn)
else:
f_measure[k] = float("nan")
macro_f_measure = np.nanmean(f_measure)
return macro_f_measure
# Compute F-beta and G-beta measures from the unofficial phase of the Challenge.
def compute_beta_measures(labels: np.ndarray, outputs: np.ndarray, beta: Real) -> Tuple[float, float]:
"""checked,"""
num_recordings, num_classes = np.shape(labels)
A = compute_confusion_matrices(labels, outputs, normalize=True)
f_beta_measure = np.zeros(num_classes)
g_beta_measure = np.zeros(num_classes)
for k in range(num_classes):
tp, fp, fn, tn = A[k, 1, 1], A[k, 1, 0], A[k, 0, 1], A[k, 0, 0]
if (1 + beta**2) * tp + fp + beta**2 * fn:
f_beta_measure[k] = float((1 + beta**2) * tp) / float((1 + beta**2) * tp + fp + beta**2 * fn)
else:
f_beta_measure[k] = float("nan")
if tp + fp + beta * fn:
g_beta_measure[k] = float(tp) / float(tp + fp + beta * fn)
else:
g_beta_measure[k] = float("nan")
macro_f_beta_measure = np.nanmean(f_beta_measure)
macro_g_beta_measure = np.nanmean(g_beta_measure)
return macro_f_beta_measure, macro_g_beta_measure
# Compute macro AUROC and macro AUPRC.
def compute_auc(labels: np.ndarray, outputs: np.ndarray) -> Tuple[float, float]:
"""checked,"""
num_recordings, num_classes = np.shape(labels)
# Compute and summarize the confusion matrices for each class across at distinct output values.
auroc = np.zeros(num_classes)
auprc = np.zeros(num_classes)
for k in range(num_classes):
# We only need to compute TPs, FPs, FNs, and TNs at distinct output values.
thresholds = np.unique(outputs[:, k])
thresholds = np.append(thresholds, thresholds[-1] + 1)
thresholds = thresholds[::-1]
num_thresholds = len(thresholds)
# Initialize the TPs, FPs, FNs, and TNs.
tp = np.zeros(num_thresholds)
fp = np.zeros(num_thresholds)
fn = np.zeros(num_thresholds)
tn = np.zeros(num_thresholds)
fn[0] = np.sum(labels[:, k] == 1)
tn[0] = np.sum(labels[:, k] == 0)
# Find the indices that result in sorted output values.
idx = np.argsort(outputs[:, k])[::-1]
# Compute the TPs, FPs, FNs, and TNs for class k across thresholds.
i = 0
for j in range(1, num_thresholds):
# Initialize TPs, FPs, FNs, and TNs using values at previous threshold.
tp[j] = tp[j - 1]
fp[j] = fp[j - 1]
fn[j] = fn[j - 1]
tn[j] = tn[j - 1]
# Update the TPs, FPs, FNs, and TNs at i-th output value.
while i < num_recordings and outputs[idx[i], k] >= thresholds[j]:
if labels[idx[i], k]:
tp[j] += 1
fn[j] -= 1
else:
fp[j] += 1
tn[j] -= 1
i += 1
# Summarize the TPs, FPs, FNs, and TNs for class k.
tpr = np.zeros(num_thresholds)
tnr = np.zeros(num_thresholds)
ppv = np.zeros(num_thresholds)
for j in range(num_thresholds):
if tp[j] + fn[j]:
tpr[j] = float(tp[j]) / float(tp[j] + fn[j])
else:
tpr[j] = float("nan")
if fp[j] + tn[j]:
tnr[j] = float(tn[j]) / float(fp[j] + tn[j])
else:
tnr[j] = float("nan")
if tp[j] + fp[j]:
ppv[j] = float(tp[j]) / float(tp[j] + fp[j])
else:
ppv[j] = float("nan")
# Compute AUROC as the area under a piecewise linear function with TPR/
# sensitivity (x-axis) and TNR/specificity (y-axis) and AUPRC as the area
# under a piecewise constant with TPR/recall (x-axis) and PPV/precision
# (y-axis) for class k.
for j in range(num_thresholds - 1):
auroc[k] += 0.5 * (tpr[j + 1] - tpr[j]) * (tnr[j + 1] + tnr[j])
auprc[k] += (tpr[j + 1] - tpr[j]) * ppv[j + 1]
# Compute macro AUROC and macro AUPRC across classes.
macro_auroc = np.nanmean(auroc)
macro_auprc = np.nanmean(auprc)
return macro_auroc, macro_auprc