anomalib.models.dfm.torch_model

PyTorch model for DFM model implementation.

Module Contents

Classes

SingleClassGaussian

Model Gaussian distribution over a set of points.

DFMModel

Model for the DFM algorithm.

class anomalib.models.dfm.torch_model.SingleClassGaussian[source]

Bases: anomalib.models.components.DynamicBufferModule

Model Gaussian distribution over a set of points.

fit(dataset: torch.Tensor) None[source]

Fit a Gaussian model to dataset X.

Covariance matrix is not calculated directly using: C = X.X^T Instead, it is represented in terms of the Singular Value Decomposition of X: X = U.S.V^T Hence, C = U.S^2.U^T This simplifies the calculation of the log-likelihood without requiring full matrix inversion.

Parameters

dataset (Tensor) – Input dataset to fit the model.

score_samples(features: torch.Tensor) torch.Tensor[source]

Compute the NLL (negative log likelihood) scores.

Parameters

features (Tensor) – semantic features on which density modeling is performed.

Returns

Torch tensor of scores

Return type

nll (Tensor)

forward(dataset: torch.Tensor) None[source]

Provides the same functionality as fit.

Transforms the input dataset based on singular values calculated earlier.

Parameters

dataset (Tensor) – Input dataset

class anomalib.models.dfm.torch_model.DFMModel(backbone: str, layer: str, pre_trained: bool = True, pooling_kernel_size: int = 4, n_comps: float = 0.97, score_type: str = 'fre')[source]

Bases: torch.nn.Module

Model for the DFM algorithm.

Parameters
  • backbone (str) – Pre-trained model backbone.

  • layer (str) – Layer from which to extract features.

  • pre_trained (bool, optional) – Boolean to check whether to use a pre_trained backbone.

  • pooling_kernel_size (int, optional) – Kernel size to pool features extracted from the CNN.

  • n_comps (float, optional) – Ratio from which number of components for PCA are calculated. Defaults to 0.97.

  • score_type (str, optional) – Scoring type. Options are fre and nll. Defaults to “fre”.

fit(dataset: torch.Tensor) None[source]

Fit a pca transformation and a Gaussian model to dataset.

Parameters

dataset (Tensor) – Input dataset to fit the model.

score(features: torch.Tensor) torch.Tensor[source]

Compute scores.

Scores are either PCA-based feature reconstruction error (FRE) scores or the Gaussian density-based NLL scores

Parameters

features (torch.Tensor) – semantic features on which PCA and density modeling is performed.

Returns

numpy array of scores

Return type

score (Tensor)

get_features(batch: torch.Tensor) torch.Tensor[source]

Extract features from the pretrained network.

Parameters

batch (Tensor) – Image batch.

Returns

Tensor containing extracted features.

Return type

Tensor

forward(batch: torch.Tensor) torch.Tensor[source]

Computer score from input images.

Parameters

batch (Tensor) – Input images

Returns

Scores

Return type

Tensor