anomalib.models.components.dimensionality_reduction.random_projection

This module comprises PatchCore Sampling Methods for the embedding.

  • Random Sparse Projector

    Sparse Random Projection using PyTorch Operations

Module Contents

Classes

SparseRandomProjection

Sparse Random Projection using PyTorch operations.

exception anomalib.models.components.dimensionality_reduction.random_projection.NotFittedError[source]

Bases: ValueError, AttributeError

Raise Exception if estimator is used before fitting.

class anomalib.models.components.dimensionality_reduction.random_projection.SparseRandomProjection(eps: float = 0.1, random_state: Optional[int] = None)[source]

Sparse Random Projection using PyTorch operations.

Parameters
  • eps (float, optional) – Minimum distortion rate parameter for calculating Johnson-Lindenstrauss minimum dimensions. Defaults to 0.1.

  • random_state (Optional[int], optional) – Uses the seed to set the random state for sample_without_replacement function. Defaults to None.

_sparse_random_matrix(self, n_features: int)[source]

Random sparse matrix. Based on https://web.stanford.edu/~hastie/Papers/Ping/KDD06_rp.pdf.

Parameters

n_features (int) – Dimentionality of the original source space

Returns

Sparse matrix of shape (n_components, n_features).

The generated Gaussian random matrix is in CSR (compressed sparse row) format.

Return type

Tensor

johnson_lindenstrauss_min_dim(self, n_samples: int, eps: float = 0.1)[source]

Find a ‘safe’ number of components to randomly project to.

Ref eqn 2.1 https://cseweb.ucsd.edu/~dasgupta/papers/jl.pdf

Parameters
  • n_samples (int) – Number of samples used to compute safe components

  • eps (float, optional) – Minimum distortion rate. Defaults to 0.1.

fit(self, embedding: torch.Tensor) SparseRandomProjection[source]

Generates sparse matrix from the embedding tensor.

Parameters

embedding (Tensor) – embedding tensor for generating embedding

Returns

Return self to be used as >>> generator = SparseRandomProjection() >>> generator = generator.fit()

Return type

(SparseRandomProjection)

transform(self, embedding: torch.Tensor) torch.Tensor[source]

Project the data by using matrix product with the random matrix.

Parameters

embedding (Tensor) – Embedding of shape (n_samples, n_features) The input data to project into a smaller dimensional space

Returns

Sparse matrix of shape

(n_samples, n_components) Projected array.

Return type

projected_embedding (Tensor)