-
Notifications
You must be signed in to change notification settings - Fork 705
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
Configurable metrics #230
Merged
Merged
Configurable metrics #230
Changes from 2 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
efb9dfc
make metrics configurable
djdameln 2ba582d
simplify import
djdameln ebf90b3
allow omitting image or pixel metrics
djdameln b195ac8
upgrade torch metrics
djdameln 34f7fbc
update all config files
djdameln 5d30287
small bugfix
djdameln bbc51bb
update threshold test
djdameln c492955
disable compute groups
djdameln 4da264c
fix visualizer tests
djdameln b38f8d5
fix normalizer tests
djdameln 6c3b1ef
Merge branch 'development' into da/feature/optional-metrics
djdameln 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
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 |
---|---|---|
@@ -1,8 +1,61 @@ | ||
"""Custom anomaly evaluation metrics.""" | ||
import importlib | ||
import warnings | ||
from typing import List, Optional, Tuple, Union | ||
|
||
import torchmetrics | ||
from omegaconf import DictConfig, ListConfig | ||
|
||
from .adaptive_threshold import AdaptiveThreshold | ||
from .anomaly_score_distribution import AnomalyScoreDistribution | ||
from .auroc import AUROC | ||
from .collection import AnomalibMetricCollection | ||
from .min_max import MinMax | ||
from .optimal_f1 import OptimalF1 | ||
|
||
__all__ = ["AUROC", "OptimalF1", "AdaptiveThreshold", "AnomalyScoreDistribution", "MinMax"] | ||
|
||
|
||
def get_metrics(config: Union[ListConfig, DictConfig]) -> Tuple[AnomalibMetricCollection, AnomalibMetricCollection]: | ||
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. We might need to modify this for LightningCLI |
||
"""Create metric collections based on the config. | ||
|
||
Args: | ||
config (Union[DictConfig, ListConfig]): Config.yaml loaded using OmegaConf | ||
|
||
Returns: | ||
AnomalibMetricCollection: Image-level metric collection | ||
AnomalibMetricCollection: Pixel-level metric collection | ||
""" | ||
image_metrics = metric_collection_from_names(config.metrics.image, "image_") | ||
pixel_metrics = metric_collection_from_names(config.metrics.pixel, "pixel_") | ||
return image_metrics, pixel_metrics | ||
|
||
|
||
def metric_collection_from_names(metric_names: List[str], prefix: Optional[str]) -> AnomalibMetricCollection: | ||
"""Create a metric collection from a list of metric names. | ||
|
||
The function will first try to retrieve the metric from the metrics defined in Anomalib metrics module, | ||
then in TorchMetrics package. | ||
|
||
Args: | ||
metric_names (List[str]): List of metric names to be included in the collection. | ||
prefix (Optional[str]): prefix to assign to the metrics in the collection. | ||
|
||
Returns: | ||
AnomalibMetricCollection: Collection of metrics. | ||
""" | ||
metrics_module = importlib.import_module("anomalib.utils.metrics") | ||
metrics = AnomalibMetricCollection([], prefix=prefix) | ||
for metric_name in metric_names: | ||
if hasattr(metrics_module, metric_name): | ||
metric_cls = getattr(metrics_module, metric_name) | ||
metrics.add_metrics(metric_cls(compute_on_step=False)) | ||
elif hasattr(torchmetrics, metric_name): | ||
try: | ||
metric_cls = getattr(torchmetrics, metric_name) | ||
metrics.add_metrics(metric_cls(compute_on_step=False)) | ||
except TypeError: | ||
warnings.warn(f"Incorrect constructor arguments for {metric_name} metric from TorchMetrics package.") | ||
else: | ||
warnings.warn(f"No metric with name {metric_name} found in Anomalib metrics or TorchMetrics.") | ||
return metrics |
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,48 @@ | ||
"""Anomalib Metric Collection.""" | ||
|
||
# Copyright (C) 2020 Intel Corporation | ||
# | ||
# 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. | ||
|
||
from torchmetrics import MetricCollection | ||
|
||
|
||
class AnomalibMetricCollection(MetricCollection): | ||
"""Extends the MetricCollection class for use in the Anomalib pipeline.""" | ||
|
||
def __init__(self, *args, **kwargs): | ||
super().__init__(*args, **kwargs) | ||
self._update_called = False | ||
self._threshold = 0.5 | ||
|
||
def set_threshold(self, threshold_value): | ||
"""Update the threshold value for all metrics that have the threshold attribute.""" | ||
self._threshold = threshold_value | ||
for metric in self.values(): | ||
if hasattr(metric, "threshold"): | ||
metric.threshold = threshold_value | ||
|
||
def update(self, *args, **kwargs) -> None: | ||
"""Add data to the metrics.""" | ||
super().update(*args, **kwargs) | ||
self._update_called = True | ||
|
||
@property | ||
def update_called(self) -> bool: | ||
"""Returns a boolean indicating if the update method has been called at least once.""" | ||
return self._update_called | ||
|
||
@property | ||
def threshold(self) -> float: | ||
"""Return the value of the anomaly threshold.""" | ||
return self._threshold |
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.
Is there something planned for classification models which do not have pixel metrics? When I removed the pixel metric key from the config file it threw error for padim
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.
This should work:
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.
Works now 🙂
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.
Not sure why my comments disappeared from here, but ideally
should also work fine.