|
| 1 | +from abc import abstractmethod |
| 2 | +from dataclasses import dataclass |
| 3 | +from typing import List, Set, Tuple, Union |
| 4 | + |
| 5 | +from sklearn.metrics import f1_score |
| 6 | + |
| 7 | +from nucleus.annotation import AnnotationList, CategoryAnnotation |
| 8 | +from nucleus.metrics.base import Metric, MetricResult, ScalarResult |
| 9 | +from nucleus.metrics.filters import confidence_filter |
| 10 | +from nucleus.prediction import CategoryPrediction, PredictionList |
| 11 | + |
| 12 | +F1_METHODS = {"micro", "macro", "samples", "weighted", "binary"} |
| 13 | + |
| 14 | + |
| 15 | +def to_taxonomy_labels( |
| 16 | + anns_or_preds: Union[List[CategoryAnnotation], List[CategoryPrediction]] |
| 17 | +) -> Set[str]: |
| 18 | + """Transforms annotation or prediction lists to taxonomy labels by joining them with a seperator (->)""" |
| 19 | + labels = set() |
| 20 | + for item in anns_or_preds: |
| 21 | + taxonomy_label = ( |
| 22 | + f"{item.taxonomy_name}->{item.label}" |
| 23 | + if item.taxonomy_name |
| 24 | + else item.label |
| 25 | + ) |
| 26 | + labels.add(taxonomy_label) |
| 27 | + return labels |
| 28 | + |
| 29 | + |
| 30 | +@dataclass |
| 31 | +class CategorizationResult(MetricResult): |
| 32 | + annotations: List[CategoryAnnotation] |
| 33 | + predictions: List[CategoryPrediction] |
| 34 | + |
| 35 | + @property |
| 36 | + def value(self): |
| 37 | + annotation_labels = to_taxonomy_labels(self.annotations) |
| 38 | + prediction_labels = to_taxonomy_labels(self.predictions) |
| 39 | + |
| 40 | + # TODO: Change task.py interface such that we can return label matching |
| 41 | + # NOTE: Returning 1 if all taxonomy labels match else 0 |
| 42 | + value = f1_score( |
| 43 | + annotation_labels, prediction_labels, average=self.f1_method |
| 44 | + ) |
| 45 | + return value |
| 46 | + |
| 47 | + |
| 48 | +class CategorizationMetric(Metric): |
| 49 | + """Abstract class for metrics related to Categorization |
| 50 | +
|
| 51 | + The Categorization class automatically filters incoming annotations and |
| 52 | + predictions for only categorization annotations. It also filters |
| 53 | + predictions whose confidence is less than the provided confidence_threshold. |
| 54 | + """ |
| 55 | + |
| 56 | + def __init__( |
| 57 | + self, |
| 58 | + confidence_threshold: float = 0.0, |
| 59 | + ): |
| 60 | + """Initializes CategorizationMetric abstract object. |
| 61 | +
|
| 62 | + Args: |
| 63 | + confidence_threshold: minimum confidence threshold for predictions to be taken into account for evaluation. Must be in [0, 1]. Default 0.0 |
| 64 | + """ |
| 65 | + assert 0 <= confidence_threshold <= 1 |
| 66 | + self.confidence_threshold = confidence_threshold |
| 67 | + |
| 68 | + @abstractmethod |
| 69 | + def eval( |
| 70 | + self, |
| 71 | + annotations: List[ |
| 72 | + CategoryAnnotation |
| 73 | + ], # TODO(gunnar): List to conform with other APIs or single instance? |
| 74 | + predictions: List[CategoryPrediction], |
| 75 | + ) -> CategorizationResult: |
| 76 | + # Main evaluation function that subclasses must override. |
| 77 | + # TODO(gunnar): Allow passing multiple predictions and selecting highest confidence? Allows us to show next |
| 78 | + # contender. Are top-5 scores something that we care about? |
| 79 | + # TODO(gunnar): How do we handle multi-head classification? |
| 80 | + pass |
| 81 | + |
| 82 | + @abstractmethod |
| 83 | + def aggregate_score(self, results: List[CategorizationResult]) -> ScalarResult: # type: ignore[override] |
| 84 | + pass |
| 85 | + |
| 86 | + def __call__( |
| 87 | + self, annotations: AnnotationList, predictions: PredictionList |
| 88 | + ) -> CategorizationResult: |
| 89 | + if self.confidence_threshold > 0: |
| 90 | + predictions = confidence_filter( |
| 91 | + predictions, self.confidence_threshold |
| 92 | + ) |
| 93 | + |
| 94 | + cat_annotations, cat_predictions = self._filter_common_taxonomies( |
| 95 | + annotations.category_annotations, predictions.category_predictions |
| 96 | + ) |
| 97 | + |
| 98 | + result = self.eval( |
| 99 | + cat_annotations, |
| 100 | + cat_predictions, |
| 101 | + ) |
| 102 | + return result |
| 103 | + |
| 104 | + def _filter_common_taxonomies( |
| 105 | + self, |
| 106 | + annotations: List[CategoryAnnotation], |
| 107 | + predictions: List[CategoryPrediction], |
| 108 | + ) -> Tuple[List[CategoryAnnotation], List[CategoryPrediction]]: |
| 109 | + annotated_taxonomies = {ann.taxonomy_name for ann in annotations} |
| 110 | + matching_predictions, matching_taxonomies = self._filter_in_taxonomies( |
| 111 | + predictions, annotated_taxonomies |
| 112 | + ) |
| 113 | + matching_annotations, _ = self._filter_in_taxonomies( |
| 114 | + annotations, matching_taxonomies |
| 115 | + ) |
| 116 | + |
| 117 | + return matching_annotations, matching_predictions # type: ignore |
| 118 | + |
| 119 | + def _filter_in_taxonomies( |
| 120 | + self, |
| 121 | + anns_or_preds: Union[ |
| 122 | + List[CategoryAnnotation], List[CategoryPrediction] |
| 123 | + ], |
| 124 | + filter_on_taxonomies: Set[Union[None, str]], |
| 125 | + ) -> Tuple[ |
| 126 | + Union[List[CategoryAnnotation], List[CategoryPrediction]], |
| 127 | + Set[Union[None, str]], |
| 128 | + ]: |
| 129 | + matching_predictions = [] |
| 130 | + matching_taxonomies = set() |
| 131 | + for pred in anns_or_preds: |
| 132 | + if pred.taxonomy_name in filter_on_taxonomies: |
| 133 | + matching_predictions.append(pred) |
| 134 | + matching_taxonomies.add(pred.taxonomy_name) |
| 135 | + return matching_predictions, matching_taxonomies |
| 136 | + |
| 137 | + |
| 138 | +class CategorizationF1(CategorizationMetric): |
| 139 | + """Evaluation method that matches categories and returns a CategorizationF1Result that aggregates to the F1 score""" |
| 140 | + |
| 141 | + def __init__( |
| 142 | + self, confidence_threshold: float = 0.0, f1_method: str = "macro" |
| 143 | + ): |
| 144 | + """ |
| 145 | + Args: |
| 146 | + confidence_threshold: minimum confidence threshold for predictions to be taken into account for evaluation. Must be in [0, 1]. Default 0.0 |
| 147 | + f1_method: {'micro', 'macro', 'samples','weighted', 'binary'}, \ |
| 148 | + default='macro' |
| 149 | + This parameter is required for multiclass/multilabel targets. |
| 150 | + If ``None``, the scores for each class are returned. Otherwise, this |
| 151 | + determines the type of averaging performed on the data: |
| 152 | +
|
| 153 | + ``'binary'``: |
| 154 | + Only report results for the class specified by ``pos_label``. |
| 155 | + This is applicable only if targets (``y_{true,pred}``) are binary. |
| 156 | + ``'micro'``: |
| 157 | + Calculate metrics globally by counting the total true positives, |
| 158 | + false negatives and false positives. |
| 159 | + ``'macro'``: |
| 160 | + Calculate metrics for each label, and find their unweighted |
| 161 | + mean. This does not take label imbalance into account. |
| 162 | + ``'weighted'``: |
| 163 | + Calculate metrics for each label, and find their average weighted |
| 164 | + by support (the number of true instances for each label). This |
| 165 | + alters 'macro' to account for label imbalance; it can result in an |
| 166 | + F-score that is not between precision and recall. |
| 167 | + ``'samples'``: |
| 168 | + Calculate metrics for each instance, and find their average (only |
| 169 | + meaningful for multilabel classification where this differs from |
| 170 | + :func:`accuracy_score`). |
| 171 | + """ |
| 172 | + super().__init__(confidence_threshold) |
| 173 | + assert ( |
| 174 | + f1_method in F1_METHODS |
| 175 | + ), f"Invalid f1_method {f1_method}, expected one of {F1_METHODS}" |
| 176 | + self.f1_method = f1_method |
| 177 | + |
| 178 | + def eval( |
| 179 | + self, |
| 180 | + annotations: List[CategoryAnnotation], |
| 181 | + predictions: List[CategoryPrediction], |
| 182 | + ) -> CategorizationResult: |
| 183 | + """ |
| 184 | + Notes: This is a little weird eval function. It essentially only does matching of annotation to label and |
| 185 | + the actual metric computation happens in the aggregate step since F1 score only makes sense on a collection. |
| 186 | + """ |
| 187 | + |
| 188 | + return CategorizationResult( |
| 189 | + annotations=annotations, predictions=predictions |
| 190 | + ) |
| 191 | + |
| 192 | + def aggregate_score(self, results: List[CategorizationResult]) -> ScalarResult: # type: ignore[override] |
| 193 | + gt = [] |
| 194 | + predicted = [] |
| 195 | + for result in results: |
| 196 | + gt.extend(list(to_taxonomy_labels(result.annotations))) |
| 197 | + predicted.extend(list(to_taxonomy_labels(result.predictions))) |
| 198 | + value = f1_score(gt, predicted, average=self.f1_method) |
| 199 | + return ScalarResult(value) |
0 commit comments