Skip to content
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

Allow specifying feature layer and pool factor in DFM #215

Merged
merged 4 commits into from
Apr 12, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions anomalib/models/dfm/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ dataset:
model:
name: dfm
backbone: resnet18
layer: layer3
pool: 4
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe this could be renamed to pool_factor to make the parameter a bit more self explanatory

pca_level: 0.97
score_type: fre # nll: for Gaussian modeling, fre: pca feature reconstruction error
project_path: ./results
Expand Down
12 changes: 10 additions & 2 deletions anomalib/models/dfm/dfm_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import torch
import torchvision
from torch import Tensor, nn
import torch.nn.functional as F

from anomalib.models.components import PCA, DynamicBufferModule, FeatureExtractor

Expand Down Expand Up @@ -89,14 +90,15 @@ class DFMModel(nn.Module):
score_type (str, optional): Scoring type. Options are `fre` and `nll`. Defaults to "fre".
"""

def __init__(self, backbone: str, n_comps: float = 0.97, score_type: str = "fre"):
def __init__(self, backbone: str, layer: str, pool: int, n_comps: float = 0.97, score_type: str = "fre"):
super().__init__()
self.backbone = getattr(torchvision.models, backbone)
self.pool = pool
self.n_components = n_comps
self.pca_model = PCA(n_components=self.n_components)
self.gaussian_model = SingleClassGaussian()
self.score_type = score_type
self.feature_extractor = FeatureExtractor(backbone=self.backbone(pretrained=True), layers=["avgpool"]).eval()
self.feature_extractor = FeatureExtractor(backbone=self.backbone(pretrained=True), layers=[layer]).eval()

def fit(self, dataset: Tensor) -> None:
"""Fit a pca transformation and a Gaussian model to dataset.
Expand Down Expand Up @@ -143,6 +145,12 @@ def get_features(self, batch: Tensor) -> Tensor:
"""
self.feature_extractor.eval()
layer_outputs = self.feature_extractor(batch)
for k in layer_outputs:
s0 = len(layer_outputs[k])
if self.pool > 1:
layer_outputs[k] = F.avg_pool2d(layer_outputs[k], self.pool)
layer_outputs[k] = layer_outputs[k].view(s0, -1)

layer_outputs = torch.cat(list(layer_outputs.values())).detach()
return layer_outputs

Expand Down
3 changes: 2 additions & 1 deletion anomalib/models/dfm/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ def __init__(self, hparams: Union[DictConfig, ListConfig]):
super().__init__(hparams)

self.model: DFMModel = DFMModel(
backbone=hparams.model.backbone, n_comps=hparams.model.pca_level, score_type=hparams.model.score_type
backbone=hparams.model.backbone, layer=hparams.model.layer, pool=hparams.model.pool,
n_comps=hparams.model.pca_level, score_type=hparams.model.score_type
)
self.automatic_optimization = False
self.embeddings: List[Tensor] = []
Expand Down