-
Notifications
You must be signed in to change notification settings - Fork 8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Group metrics by labels #245
Open
gatli
wants to merge
6
commits into
master
Choose a base branch
from
gunnar-group-by-label
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
76147df
Add Label Grouper
ardila 6387817
All tests except for non matching ones running
gatli 7e9f48e
WIP
gatli 4243f6f
Merge remote-tracking branch 'origin/master' into gunnar-group-by-label
gatli 12886e1
Clean up MetricResult interfaces
gatli 860601d
Cleanup of mypy errors and addressing inconsistencies from PR
gatli File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
from typing import Any, List | ||
|
||
import numpy as np | ||
import pandas as pd | ||
|
||
|
||
class LabelsGrouper: | ||
def __init__(self, annotations_or_predictions_list: List[Any]): | ||
self.items = annotations_or_predictions_list | ||
if len(self.items) > 0: | ||
assert hasattr( | ||
self.items[0], "label" | ||
), f"Expected items to have attribute 'label' found none on {repr(self.items[0])}" | ||
self.codes, self.labels = pd.factorize( | ||
[item.label for item in self.items] | ||
) | ||
self.group_idx = 0 | ||
|
||
def __iter__(self): | ||
self.group_idx = 0 | ||
return self | ||
|
||
def __next__(self): | ||
if self.group_idx >= len(self.labels): | ||
raise StopIteration | ||
label = self.labels[self.group_idx] | ||
label_items = list( | ||
np.take(self.items, np.where(self.codes == self.group_idx)[0]) | ||
) | ||
self.group_idx += 1 | ||
return label, label_items | ||
|
||
def label_group(self, label: str) -> List[Any]: | ||
if len(self.items) == 0: | ||
return [] | ||
idx = np.where(self.labels == label)[0] | ||
if idx >= 0: | ||
label_items = list( | ||
np.take(self.items, np.where(self.codes == idx)[0]) | ||
) | ||
return label_items | ||
else: | ||
return [] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,14 +1,16 @@ | ||
import sys | ||
from abc import abstractmethod | ||
from typing import List, Union | ||
from collections import defaultdict | ||
from typing import Dict, List, Union | ||
|
||
import numpy as np | ||
|
||
from nucleus.annotation import AnnotationList, BoxAnnotation, PolygonAnnotation | ||
from nucleus.prediction import BoxPrediction, PolygonPrediction, PredictionList | ||
|
||
from .base import Metric, ScalarResult | ||
from .base import GroupedScalarResult, Metric, ScalarResult | ||
from .filters import confidence_filter, polygon_label_filter | ||
from .label_grouper import LabelsGrouper | ||
from .metric_utils import compute_average_precision | ||
from .polygon_utils import ( | ||
BoxOrPolygonAnnotation, | ||
|
@@ -80,19 +82,44 @@ def eval( | |
|
||
def __init__( | ||
self, | ||
enforce_label_match: bool = False, | ||
enforce_label_match: bool = True, | ||
confidence_threshold: float = 0.0, | ||
): | ||
"""Initializes PolygonMetric abstract object. | ||
|
||
Args: | ||
enforce_label_match: whether to enforce that annotation and prediction labels must match. Default False | ||
enforce_label_match: whether to enforce that annotation and prediction labels must match. Default True | ||
confidence_threshold: minimum confidence threshold for predictions. Must be in [0, 1]. Default 0.0 | ||
""" | ||
self.enforce_label_match = enforce_label_match | ||
assert 0 <= confidence_threshold <= 1 | ||
self.confidence_threshold = confidence_threshold | ||
|
||
def eval_grouped( | ||
self, | ||
annotations: List[Union[BoxAnnotation, PolygonAnnotation]], | ||
predictions: List[Union[BoxPrediction, PolygonPrediction]], | ||
) -> GroupedScalarResult: | ||
grouped_annotations = LabelsGrouper(annotations) | ||
grouped_predictions = LabelsGrouper(predictions) | ||
results = {} | ||
for label, label_annotations in grouped_annotations: | ||
# TODO(gunnar): Enforce label match -> Why is that a parameter? Should we generally allow IOU matches | ||
# between different labels?!? | ||
Comment on lines
+107
to
+108
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. In general we should have an option to allow this. E.g. you need to compute matches across the classes for the confusion matrix. |
||
match_predictions = ( | ||
grouped_predictions.label_group(label) | ||
if self.enforce_label_match | ||
else predictions | ||
) | ||
eval_fn = label_match_wrapper(self.eval) | ||
result = eval_fn( | ||
label_annotations, | ||
match_predictions, | ||
enforce_label_match=self.enforce_label_match, | ||
) | ||
results[label] = result | ||
return GroupedScalarResult(group_to_scalar=results) | ||
|
||
@abstractmethod | ||
def eval( | ||
self, | ||
|
@@ -102,12 +129,20 @@ def eval( | |
# Main evaluation function that subclasses must override. | ||
pass | ||
|
||
def aggregate_score(self, results: List[ScalarResult]) -> ScalarResult: # type: ignore[override] | ||
return ScalarResult.aggregate(results) | ||
def aggregate_score(self, results: List[GroupedScalarResult]) -> Dict[str, ScalarResult]: # type: ignore[override] | ||
label_to_values = defaultdict(list) | ||
for item_result in results: | ||
for label, label_result in item_result.group_to_scalar.items(): | ||
label_to_values[label].append(label_result) | ||
scores = { | ||
label: ScalarResult.aggregate(values) | ||
for label, values in label_to_values.items() | ||
} | ||
return scores | ||
|
||
def __call__( | ||
self, annotations: AnnotationList, predictions: PredictionList | ||
) -> ScalarResult: | ||
) -> GroupedScalarResult: | ||
if self.confidence_threshold > 0: | ||
predictions = confidence_filter( | ||
predictions, self.confidence_threshold | ||
|
@@ -119,11 +154,9 @@ def __call__( | |
polygon_predictions.extend(predictions.box_predictions) | ||
polygon_predictions.extend(predictions.polygon_predictions) | ||
|
||
eval_fn = label_match_wrapper(self.eval) | ||
result = eval_fn( | ||
result = self.eval_grouped( | ||
polygon_annotations, | ||
polygon_predictions, | ||
enforce_label_match=self.enforce_label_match, | ||
) | ||
return result | ||
|
||
|
@@ -166,7 +199,7 @@ class PolygonIOU(PolygonMetric): | |
# TODO: Remove defaults once these are surfaced more cleanly to users. | ||
def __init__( | ||
self, | ||
enforce_label_match: bool = False, | ||
enforce_label_match: bool = True, | ||
iou_threshold: float = 0.0, | ||
confidence_threshold: float = 0.0, | ||
): | ||
|
@@ -234,7 +267,7 @@ class PolygonPrecision(PolygonMetric): | |
# TODO: Remove defaults once these are surfaced more cleanly to users. | ||
def __init__( | ||
self, | ||
enforce_label_match: bool = False, | ||
enforce_label_match: bool = True, | ||
iou_threshold: float = 0.5, | ||
confidence_threshold: float = 0.0, | ||
): | ||
|
@@ -303,7 +336,7 @@ class PolygonRecall(PolygonMetric): | |
# TODO: Remove defaults once these are surfaced more cleanly to users. | ||
def __init__( | ||
self, | ||
enforce_label_match: bool = False, | ||
enforce_label_match: bool = True, | ||
iou_threshold: float = 0.5, | ||
confidence_threshold: float = 0.0, | ||
): | ||
|
@@ -460,7 +493,7 @@ def __init__( | |
0 <= iou_threshold <= 1 | ||
), "IoU threshold must be between 0 and 1." | ||
self.iou_threshold = iou_threshold | ||
super().__init__(enforce_label_match=False, confidence_threshold=0) | ||
super().__init__(enforce_label_match=True, confidence_threshold=0) | ||
|
||
def eval( | ||
self, | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
:nit: please adjust comment below