Upload proto_model/metrics.py with huggingface_hub
Browse files- proto_model/metrics.py +133 -0
proto_model/metrics.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, Any, Callable, List
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torchmetrics
|
| 5 |
+
|
| 6 |
+
from torchmetrics.metric import Metric
|
| 7 |
+
from torchmetrics import AUROC, PrecisionRecallCurve
|
| 8 |
+
from torchmetrics.functional import auroc
|
| 9 |
+
from torchmetrics.utilities.data import dim_zero_cat
|
| 10 |
+
import logging
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class PR_AUC(Metric):
|
| 15 |
+
def __init__(self, num_classes, compute_on_step=False, dist_sync_on_step=False):
|
| 16 |
+
super().__init__(compute_on_step=compute_on_step, dist_sync_on_step=dist_sync_on_step)
|
| 17 |
+
self.add_state("prauc", default=[], dist_reduce_fx='cat')
|
| 18 |
+
self.pr_curve = PrecisionRecallCurve(num_classes=num_classes).to(self.device)
|
| 19 |
+
self.auc = torchmetrics.AUC().to(self.device)
|
| 20 |
+
|
| 21 |
+
def update(self, prediction: torch.Tensor, target: torch.Tensor):
|
| 22 |
+
precision, recall, thresholds = self.pr_curve(prediction, target)
|
| 23 |
+
auc_values = [self.auc(r, p) for r, p in zip(recall, precision)]
|
| 24 |
+
|
| 25 |
+
pr_auc = torch.mean(torch.tensor([v for v in auc_values if not v.isnan()])).to(self.device)
|
| 26 |
+
self.prauc += [pr_auc.detach()]
|
| 27 |
+
|
| 28 |
+
def compute(self):
|
| 29 |
+
return torch.mean(self.prauc.detach())
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class PR_AUCPerBucket(PR_AUC):
|
| 33 |
+
def __init__(self, num_classes, bucket, compute_on_step=False, dist_sync_on_step=False):
|
| 34 |
+
super().__init__(num_classes=len(bucket), compute_on_step=compute_on_step, dist_sync_on_step=dist_sync_on_step)
|
| 35 |
+
self.bucket = set(bucket)
|
| 36 |
+
self.num_classes = num_classes
|
| 37 |
+
|
| 38 |
+
def update(self, prediction: torch.Tensor, target: torch.Tensor):
|
| 39 |
+
|
| 40 |
+
mask = np.zeros((self.num_classes), dtype=bool)
|
| 41 |
+
for c in range(self.num_classes):
|
| 42 |
+
if c in self.bucket:
|
| 43 |
+
mask[c] = True
|
| 44 |
+
filtered_target = target[:, mask]
|
| 45 |
+
filtered_preds = prediction[:, mask]
|
| 46 |
+
|
| 47 |
+
if len((filtered_target > 0).nonzero()) > 0:
|
| 48 |
+
precision, recall, thresholds = self.pr_curve(filtered_preds, filtered_target)
|
| 49 |
+
auc_values = [self.auc(r, p) for r, p in zip(recall, precision)]
|
| 50 |
+
|
| 51 |
+
pr_auc = torch.mean(torch.tensor([v for v in auc_values if not v.isnan()])).to(self.device)
|
| 52 |
+
self.prauc += [pr_auc.detach()]
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def calculate_pr_auc(prediction: torch.Tensor, target: torch.Tensor, num_classes, device):
|
| 56 |
+
pr_curve = PrecisionRecallCurve(num_classes=num_classes).to(device)
|
| 57 |
+
auc = torchmetrics.AUC().to(device)
|
| 58 |
+
|
| 59 |
+
precision, recall, thresholds = pr_curve(prediction, target)
|
| 60 |
+
auc_values = [auc(r, p) for r, p in zip(recall, precision)]
|
| 61 |
+
|
| 62 |
+
pr_auc = torch.mean(torch.tensor([v for v in auc_values if not v.isnan()])).to(device)
|
| 63 |
+
return pr_auc.detach()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class FilteredAUROC(AUROC):
|
| 67 |
+
def compute(self) -> torch.Tensor:
|
| 68 |
+
|
| 69 |
+
preds = dim_zero_cat(self.preds)
|
| 70 |
+
target = dim_zero_cat(self.target)
|
| 71 |
+
|
| 72 |
+
mask = np.ones((self.num_classes), dtype=bool)
|
| 73 |
+
for c in range(self.num_classes):
|
| 74 |
+
if torch.max(target[:, c]) == 0:
|
| 75 |
+
mask[c] = False
|
| 76 |
+
filtered_target = target[:, mask]
|
| 77 |
+
filtered_preds = preds[:, mask]
|
| 78 |
+
|
| 79 |
+
num_filtered_cols = np.count_nonzero(mask == False)
|
| 80 |
+
logging.info(f"{num_filtered_cols} columns not considered for ROC AUC calculation!")
|
| 81 |
+
|
| 82 |
+
return _auroc_compute(
|
| 83 |
+
filtered_preds,
|
| 84 |
+
filtered_target,
|
| 85 |
+
self.mode,
|
| 86 |
+
self.num_classes - num_filtered_cols,
|
| 87 |
+
self.pos_label,
|
| 88 |
+
self.average,
|
| 89 |
+
self.max_fpr,
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class FilteredAUROCPerBucket(AUROC):
|
| 94 |
+
def __init__(
|
| 95 |
+
self,
|
| 96 |
+
bucket: List[int],
|
| 97 |
+
num_classes: Optional[int] = None,
|
| 98 |
+
pos_label: Optional[int] = None,
|
| 99 |
+
average: Optional[str] = "macro",
|
| 100 |
+
max_fpr: Optional[float] = None,
|
| 101 |
+
compute_on_step: bool = True,
|
| 102 |
+
dist_sync_on_step: bool = False,
|
| 103 |
+
process_group: Optional[Any] = None,
|
| 104 |
+
dist_sync_fn: Callable = None
|
| 105 |
+
):
|
| 106 |
+
super().__init__(num_classes, pos_label, average, max_fpr, compute_on_step, dist_sync_on_step, process_group,
|
| 107 |
+
dist_sync_fn)
|
| 108 |
+
self.bucket = set(bucket)
|
| 109 |
+
|
| 110 |
+
def compute(self) -> torch.Tensor:
|
| 111 |
+
|
| 112 |
+
preds = dim_zero_cat(self.preds)
|
| 113 |
+
target = dim_zero_cat(self.target)
|
| 114 |
+
|
| 115 |
+
mask = np.zeros((self.num_classes), dtype=bool)
|
| 116 |
+
for c in range(self.num_classes):
|
| 117 |
+
if torch.max(target[:, c]) > 0 and c in self.bucket:
|
| 118 |
+
mask[c] = True
|
| 119 |
+
filtered_target = target[:, mask]
|
| 120 |
+
filtered_preds = preds[:, mask]
|
| 121 |
+
|
| 122 |
+
num_filtered_cols = np.count_nonzero(mask == False)
|
| 123 |
+
logging.info(f"{num_filtered_cols} columns not considered for ROC AUC calculation!")
|
| 124 |
+
|
| 125 |
+
return _auroc_compute(
|
| 126 |
+
filtered_preds,
|
| 127 |
+
filtered_target,
|
| 128 |
+
self.mode,
|
| 129 |
+
self.num_classes - num_filtered_cols,
|
| 130 |
+
self.pos_label,
|
| 131 |
+
self.average,
|
| 132 |
+
self.max_fpr,
|
| 133 |
+
)
|