-
Notifications
You must be signed in to change notification settings - Fork 652
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* add min-max normalization * persist min and max observed values of validation set * pylint * license headers * removing print statement * revert default category * improve visualizer * switch to mean normalization * disable normalization for dfm * Revert "disable normalization for dfm" This reverts commit ef6f6dd. * limit values between 0 and 1 * move normalization functionality to functions * skip dfm test * rename cdf normalization * rename normalization files
- Loading branch information
Showing
18 changed files
with
327 additions
and
58 deletions.
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,83 @@ | ||
"""Anomaly Score Normalization Callback that uses min-max normalization.""" | ||
|
||
# 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 typing import Any, Dict | ||
|
||
import pytorch_lightning as pl | ||
from pytorch_lightning import Callback | ||
from pytorch_lightning.utilities.types import STEP_OUTPUT | ||
|
||
from anomalib.utils.normalization.min_max import normalize | ||
|
||
|
||
class MinMaxNormalizationCallback(Callback): | ||
"""Callback that normalizes the image-level and pixel-level anomaly scores using min-max normalization.""" | ||
|
||
def on_test_start(self, _trainer: pl.Trainer, pl_module: pl.LightningModule) -> None: | ||
"""Called when the test begins.""" | ||
pl_module.image_metrics.F1.threshold = 0.5 | ||
pl_module.pixel_metrics.F1.threshold = 0.5 | ||
|
||
def on_validation_batch_end( | ||
self, | ||
_trainer: pl.Trainer, | ||
pl_module: pl.LightningModule, | ||
outputs: STEP_OUTPUT, | ||
_batch: Any, | ||
_batch_idx: int, | ||
_dataloader_idx: int, | ||
) -> None: | ||
"""Called when the validation batch ends, update the min and max observed values.""" | ||
if "anomaly_maps" in outputs.keys(): | ||
pl_module.min_max(outputs["anomaly_maps"]) | ||
else: | ||
pl_module.min_max(outputs["pred_scores"]) | ||
|
||
def on_test_batch_end( | ||
self, | ||
_trainer: pl.Trainer, | ||
pl_module: pl.LightningModule, | ||
outputs: STEP_OUTPUT, | ||
_batch: Any, | ||
_batch_idx: int, | ||
_dataloader_idx: int, | ||
) -> None: | ||
"""Called when the test batch ends, normalizes the predicted scores and anomaly maps.""" | ||
self._normalize_batch(outputs, pl_module) | ||
|
||
def on_predict_batch_end( | ||
self, | ||
_trainer: pl.Trainer, | ||
pl_module: pl.LightningModule, | ||
outputs: Dict, | ||
_batch: Any, | ||
_batch_idx: int, | ||
_dataloader_idx: int, | ||
) -> None: | ||
"""Called when the predict batch ends, normalizes the predicted scores and anomaly maps.""" | ||
self._normalize_batch(outputs, pl_module) | ||
|
||
@staticmethod | ||
def _normalize_batch(outputs, pl_module): | ||
"""Normalize a batch of predictions.""" | ||
stats = pl_module.min_max | ||
outputs["pred_scores"] = normalize( | ||
outputs["pred_scores"], pl_module.image_threshold.value, stats.min, stats.max | ||
) | ||
if "anomaly_maps" in outputs.keys(): | ||
outputs["anomaly_maps"] = normalize( | ||
outputs["anomaly_maps"], pl_module.pixel_threshold.value, stats.min, stats.max | ||
) |
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 @@ | ||
"""Module that tracks the min and max values of the observations in each batch.""" | ||
|
||
# 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 typing import Tuple | ||
|
||
import torch | ||
from torch import Tensor | ||
from torchmetrics import Metric | ||
|
||
|
||
class MinMax(Metric): | ||
"""Track the min and max values of the observations in each batch.""" | ||
|
||
def __init__(self, **kwargs): | ||
super().__init__(**kwargs) | ||
self.add_state("min", torch.tensor(float("inf")), persistent=True) # pylint: disable=not-callable | ||
self.add_state("max", torch.tensor(float("-inf")), persistent=True) # pylint: disable=not-callable | ||
|
||
self.min = torch.tensor(float("inf")) # pylint: disable=not-callable | ||
self.max = torch.tensor(float("-inf")) # pylint: disable=not-callable | ||
|
||
# pylint: disable=arguments-differ | ||
def update(self, predictions: Tensor) -> None: # type: ignore | ||
"""Update the min and max values.""" | ||
self.max = torch.max(self.max, torch.max(predictions)) | ||
self.min = torch.min(self.min, torch.min(predictions)) | ||
|
||
def compute(self) -> Tuple[Tensor, Tensor]: | ||
"""Return min and max values.""" | ||
return self.min, self.max |
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
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.