### Create and Setup ShanghaiTech Datamodule Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/data/datamodules/video/shanghaitech.html Instantiate the ShanghaiTech datamodule with custom parameters and set up the data for training. This example shows how to access the data keys after setup. ```python >>> from anomalib.data import ShanghaiTech >>> datamodule = ShanghaiTech( ... root="./datasets/shanghaitech", ... scene=1, ... clip_length_in_frames=2, ... frames_between_clips=1, ... ) >>> datamodule.setup() >>> i, data = next(enumerate(datamodule.train_dataloader())) >>> data.keys() dict_keys(['image', 'video_path', 'frames', 'label']) ``` -------------------------------- ### Create and Setup Datumaro Datamodule Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/data/datamodules/image/datumaro.html Instantiate the Datumaro datamodule with specified parameters and set up the data splits. This example shows how to access the keys of the data returned by the training dataloader. ```python >>> from pathlib import Path >>> from anomalib.data import Datumaro >>> datamodule = Datumaro( ... root="./datasets/datumaro", ... train_batch_size=32, ... eval_batch_size=32, ... num_workers=8, ... ) >>> datamodule.setup() >>> i, data = next(enumerate(datamodule.train_dataloader())) >>> data.keys() dict_keys(['image_path', 'label', 'image']) ``` -------------------------------- ### Create and Setup a Tabular Datamodule Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/data/datamodules/image/tabular.html Initialize a Tabular datamodule with sample data and then call the setup() method to prepare the data for training and evaluation. ```python from anomalib.data import Tabular samples = { "image_path": ["images/image1.png", "images/image2.png", "images/image3.png", ... ], "label_index": [LabelName.NORMAL, LabelName.NORMAL, LabelName.ABNORMAL, ... ], "split": [Split.TRAIN, Split.TRAIN, Split.TEST, ... ], } datamodule = Tabular( name="custom", samples=samples, root="./datasets/custom", ) datamodule.setup() ``` -------------------------------- ### BTech Datamodule Initialization and Setup Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/data/datamodules/image/btech.html Instantiate the BTech datamodule with specified parameters and then call the setup method to prepare the data for use. ```APIDOC ## BTech Datamodule Initialization and Setup ### Description Instantiate the BTech datamodule with specified parameters and then call the setup method to prepare the data for use. ### Parameters * **root** (`Path` | `str` | `None`) - Path to the root of the dataset. Defaults to `./datasets/BTech`. * **category** (`str`) - Category of the BTech dataset (e.g. `"01"`, `"02"`, or `"03"`). Defaults to `"01"`. * **train_batch_size** (`int`) - Training batch size. Defaults to `32`. * **eval_batch_size** (`int`) - Test batch size. Defaults to `32`. * **num_workers** (`int`) - Number of workers. Defaults to `8`. * **train_augmentations** (`Transform` | `None`) - Augmentations to apply to the training images Defaults to `None`. * **val_augmentations** (`Transform` | `None`) - Augmentations to apply to the validation images. Defaults to `None`. * **test_augmentations** (`Transform` | `None`) - Augmentations to apply to the test images. Defaults to `None`. * **augmentations** (`Transform` | `None`) - General augmentations to apply if stage-specific augmentations are not provided. * **test_split_mode** (`TestSplitMode` | `str`) - Setting that determines how the testing subset is obtained. Defaults to `TestSplitMode.FROM_DIR`. * **test_split_ratio** (`float`) - Fraction of images from the train set that will be reserved for testing. Defaults to `0.2`. * **val_split_mode** (`ValSplitMode` | `str`) - Setting that determines how the validation subset is obtained. Defaults to `ValSplitMode.SAME_AS_TEST`. * **val_split_ratio** (`float`) - Fraction of train or test images that will be reserved for validation. Defaults to `0.5`. * **seed** (`int` | `None`) - Seed which may be set to a fixed value for reproducibility. Defaults to `None`. ### Example ```python from anomalib.data import BTech datamodule = BTech( root="./datasets/BTech", category="01", train_batch_size=32, eval_batch_size=32, num_workers=8, ) datamodule.setup() ``` ``` -------------------------------- ### Initialize and Setup BTech Datamodule Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/data/datamodules/image/btech.html Create and set up the BTech datamodule with custom batch sizes and number of workers. The `setup()` method prepares the data for training and evaluation. ```python from anomalib.data import BTech datamodule = BTech( root="./datasets/BTech", category="01", train_batch_size=32, eval_batch_size=32, num_workers=8, ) datamodule.setup() ``` -------------------------------- ### Install Full Dependencies via Anomalib Source: https://anomalib.readthedocs.io/en/latest/_sources/markdown/guides/developer/contributing.md Install all dependencies, including optional ones, using 'anomalib install' with the 'full' option. ```bash anomalib install --option full ``` -------------------------------- ### setup Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/metrics/index.html Move metrics to cpu if `num_devices == 1` and `compute_on_cpu` is set to `True`. ```APIDOC ## setup(_trainer_, _pl_module_, _stage_) ### Description Move metrics to cpu if `num_devices == 1` and `compute_on_cpu` is set to `True`. ### Parameters * **_trainer_**: The PyTorch Lightning trainer. * **_pl_module_**: The PyTorch Lightning module. * **_stage_**: The current stage (e.g., 'fit', 'validate', 'test'). Return type: `None` ``` -------------------------------- ### Install Full Dependencies via Pip Source: https://anomalib.readthedocs.io/en/latest/_sources/markdown/guides/developer/contributing.md Install all dependencies using pip with an editable install and the 'full' extra. ```bash pip install -e .[full] ``` -------------------------------- ### Install Anomalib from Source Source: https://anomalib.readthedocs.io/en/latest/index.html Clone the repository and install Anomalib in editable mode for development. A virtual environment is highly recommended. ```bash # Use of virtual environment is highy recommended # Using conda yes | conda create -n anomalib_env python=3.10 conda activate anomalib_env # Or using your favorite virtual environment # ... # Clone the repository and install in editable mode git clone https://github.com/open-edge-platform/anomalib.git cd anomalib pip install -e . ``` -------------------------------- ### Update WinClipModel Setup with Reference Images Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/image/winclip.html Initializes the WinClipModel with a class name and later updates the setup by providing reference images. Demonstrates the change in k_shot. ```python model = WinClipModel("transistor") model.k_shot model.setup(reference_images=ref_images) model.k_shot ``` -------------------------------- ### Create and Setup Folder Datamodule with Masks Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/data/datamodules/image/folder.html Initialize a Folder datamodule including a directory for mask annotations and then call the setup() method to prepare the dataloaders. This is used when ground truth masks are available for anomaly detection. ```python from anomalib.data import Folder datamodule = Folder( name="custom", root="./datasets/custom", normal_dir="good", abnormal_dir="defect", mask_dir="mask" ) datamodule.setup() ``` -------------------------------- ### Setup Tabular Datamodule Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/data/datamodules/image/tabular.html Instantiate and set up the Tabular Datamodule. Ensure the dataset path is correctly specified. ```python from anomalib.data import Tabular datamodule = Tabular( root="./datasets/custom", ) datamodule.setup() ``` -------------------------------- ### Install and Configure Pre-commit Hooks Source: https://anomalib.readthedocs.io/en/latest/_sources/markdown/guides/developer/contributing.md Install and configure pre-commit hooks for automated code quality checks. ```bash prek install ``` -------------------------------- ### Advanced Installation with uv Source: https://anomalib.readthedocs.io/en/latest/_sources/markdown/get_started/anomalib.md Install Anomalib with hardware-specific extras using uv for better compatibility. ```bash uv pip install anomalib[all] ``` -------------------------------- ### CflowModel Initialization Example Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/image/cflow.html A simplified example of initializing the CflowModel. This is useful for basic usage scenarios. ```python >>> model = CflowModel( ... backbone="resnet18", ... layers=["layer1", "layer2", "layer3"] ... ) >>> x = torch.randn(32, 3, 256, 256) >>> predictions = model(x) ``` -------------------------------- ### Initialize and Fit GaussianMixture and KMeans Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/components/cluster.html Demonstrates how to initialize and fit both GaussianMixture and KMeans models with example features. ```python >>> from anomalib.models.components.cluster import GaussianMixture, KMeans >>> # Create and fit a GMM >>> gmm = GaussianMixture(n_components=3) >>> features = torch.randn(100, 10) # Example features >>> gmm.fit(features) >>> # Create and fit KMeans >>> kmeans = KMeans(n_clusters=5) >>> kmeans.fit(features) ``` -------------------------------- ### DataModule Setup for Datasets Source: https://anomalib.readthedocs.io/en/latest/_sources/markdown/guides/how_to/data/datamodules.md Implements the setup method for a DataModule to create and assign train, validation, and test datasets using AnomalibDataset. ```python def setup(self, stage: str | None = None): """Set up train, validation and test datasets.""" if stage == "fit" or stage is None: self.train_dataset = AnomalibDataset( root=self.root, category=self.category, transform=self.transform, split="train" ) self.val_dataset = AnomalibDataset( root=self.root, category=self.category, transform=self.transform, split="val" ) if stage == "test" or stage is None: self.test_dataset = AnomalibDataset( root=self.root, category=self.category, transform=self.transform, split="test" ) ``` -------------------------------- ### Example of Upscale and Downscale Image Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/data/utils/tiling.html Demonstrates how to use `upscale_image` and `downscale_image` together and verify that the original image can be recovered. ```python >>> x = torch.rand(1, 3, 512, 512) >>> y = upscale_image(x, (555, 555), "padding") >>> z = downscale_image(y, (512, 512), "padding") >>> torch.allclose(x, z) True ``` -------------------------------- ### Install Anomalib from Source Source: https://anomalib.readthedocs.io/en/latest/_sources/index.md Use these commands to install Anomalib from its source code. This method is recommended if you plan to make changes to the library's source code. ```bash git clone https://github.com/open-mmlab/anomalib.git cd anomalib pip install -e . ``` -------------------------------- ### AllInOneBlock Example Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/components/normalizing_flows.html Demonstrates how to create and apply an AllInOneBlock for flow transformation. Requires PyTorch and Anomalib's flow module. ```python import torch from anomalib.models.components.flow import AllInOneBlock # Create flow block flow = AllInOneBlock(channels=64) # Apply flow transformation x = torch.randn(1, 64, 32, 32) y, logdet = flow(x) ``` -------------------------------- ### setup Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/image/winclip.html Sets up the WinCLIP model by configuring the class name, collecting text embeddings, and gathering reference images for few-shot inference. ```APIDOC ## setup ### Description Setup WinCLIP model. This method: - Sets the class name used in the prompt ensemble - Collects text embeddings for zero-shot inference - Collects reference images for few-shot inference if `k_shot > 0`. Note This hook is called before the model is moved to the target device. ### Returns * **None** ``` -------------------------------- ### Instantiate and Use DSR Model Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/image/dsr.html Example of how to instantiate the DSR model and pass an input tensor to get the anomaly map. Ensure you have torch and anomalib installed. ```python >>> from anomalib.models.image.dsr.torch_model import DsrModel >>> model = DsrModel() >>> input_tensor = torch.randn(32, 3, 256, 256) >>> output = model(input_tensor) >>> output["anomaly_map"].shape torch.Size([32, 256, 256]) ``` -------------------------------- ### Log an Image with MLFlow Logger Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/loggers/index.html This example demonstrates how to log a generated image using the `add_image` method of the AnomalibMLFlowLogger. Ensure you have numpy installed for image generation. ```python import numpy as np image = np.random.rand(32, 32, 3) # doctest: +SKIP mlflow_logger.add_image( image=image, name="test_image" ) # doctest: +SKIP ``` -------------------------------- ### Log Model Graph to TensorBoard Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/callbacks/index.html Example of how to configure the GraphLogger to log the model graph to TensorBoard. This setup involves initializing the AnomalibTensorBoardLogger and the GraphLogger callback, then passing them to the anomalib Engine. ```python from anomalib.callbacks import GraphLogger from anomalib.loggers import AnomalibTensorBoardLogger from anomalib.engine import Engine logger = AnomalibTensorBoardLogger() callbacks = [GraphLogger()] engine = Engine(logger=logger, callbacks=callbacks) ``` -------------------------------- ### on_train_start() Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/image/efficient_ad.html Sets up the model environment before training begins. This includes validating training parameters, setting up the pre-trained teacher model, preparing the ImageNette dataset, and calculating channel statistics. ```APIDOC ## on_train_start() ### Description Set up model before training begins. Performs the following steps: 1. Validates training parameters (batch size=1, no normalization) 2. Sets up pretrained teacher model 3. Prepares ImageNette dataset 4. Calculates channel statistics ### Raises **ValueError** – If `train_batch_size != 1` or transforms contain normalization. ``` -------------------------------- ### Custom DataModule Implementation Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/how_to/data/datamodules.html Implement a custom DataModule by inheriting from PyTorch Lightning's LightningDataModule. This example shows how to define the constructor, setup the training dataset, and create a training dataloader using a custom collate function. ```python from pytorch_lightning import LightningDataModule from torch.utils.data import DataLoader from anomalib.data.dataclasses import ImageBatch class CustomDataModule(LightningDataModule): def __init__( self, root: str, category: str, train_batch_size: int = 32, **kwargs ): super().__init__() self.root = root self.category = category self.image_size = image_size self.train_batch_size = train_batch_size def setup(self, stage: str | None = None): """Initialize datasets.""" if stage == "fit" or stage is None: self.train_dataset = CustomDataset( root=self.root, category=self.category, split="train" ) def train_dataloader(self) -> DataLoader: """Create train dataloader.""" return DataLoader( dataset=self.train_dataset, batch_size=self.train_batch_size, shuffle=True, collate_fn=ImageBatch.collate ) ``` -------------------------------- ### Install Anomalib with uv Source: https://anomalib.readthedocs.io/en/latest/_sources/markdown/get_started/anomalib.md Install Anomalib and its core dependencies using the uv package installer. ```bash uv pip install anomalib ``` -------------------------------- ### on_train_start() Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/image/dsr.html Sets up the model before training begins. Validates pre-processor normalization and loads pretrained weights. ```APIDOC ## on_train_start() ### Description Set up model before training begins. Performs the following steps: 1. Validates that pre_processor uses no normalization 2. Load pretrained weights of the discrete model ### Raises **ValueError** – If transforms contain normalization. ### Return type `None` ``` -------------------------------- ### Install Full Dependencies via pip Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/developer/contributing.html Install all dependencies for Anomalib using pip with an editable install and the 'full' extra. ```bash pip install -e .[full] ``` -------------------------------- ### Install Development Requirements via Pip Source: https://anomalib.readthedocs.io/en/latest/_sources/markdown/guides/developer/contributing.md Install development dependencies using pip with an editable install and the 'dev' extra. ```bash pip install -e .[dev] ``` -------------------------------- ### Install Development Requirements via Anomalib Source: https://anomalib.readthedocs.io/en/latest/_sources/markdown/guides/developer/contributing.md Install development dependencies using the 'anomalib install' command with the 'dev' option. ```bash anomalib install --option dev ``` -------------------------------- ### Advanced Pre-processor with Compose and Normalize Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/how_to/models/pre_processor.html This example demonstrates creating a pre-processor by composing multiple transforms, including Resize and Normalize. This ensures all necessary transformations are applied correctly. ```python from anomalib.data.transforms import Compose, Resize, Normalize from anomalib.models.components import PreProcessor from anomalib.models import Padim transform = Compose( Resize(size=(240, 240), interpolation=InterpolationMode.BILINEAR, antialias=True), Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], inplace=False), ) pre_processor = PreProcessor(transform=transform) model = Padim(pre_processor=pre_processor) ``` -------------------------------- ### Initialize and Use SparseRandomProjection Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/components/dimensionality_reduction.html Demonstrates how to initialize, fit, and transform data using SparseRandomProjection. Ensure torch is imported. ```python >>> import torch >>> from anomalib.models.components import SparseRandomProjection >>> # Create sample data >>> data = torch.randn(100, 50) # 100 samples, 50 features >>> # Initialize and fit projector >>> projector = SparseRandomProjection(eps=0.1) >>> projector.fit(data) >>> # Transform data >>> projected = projector.transform(data) >>> print(projected.shape) ``` -------------------------------- ### Install Development Requirements via pip Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/developer/contributing.html Install the development requirements for Anomalib using pip with an editable install and the 'dev' extra. ```bash pip install -e .[dev] ``` -------------------------------- ### Sample Coreset using KCenterGreedy Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/components/sampling_components.html Demonstrates how to initialize KCenterGreedy with an embedding and sampling ratio, then directly sample the coreset. ```python import torch embedding = torch.randn(219520, 1536) sampler = KCenterGreedy(embedding=embedding, sampling_ratio=0.001) coreset = sampler.sample_coreset() coreset.shape ``` -------------------------------- ### Install Anomalib with uv or pip Source: https://anomalib.readthedocs.io/en/latest/markdown/get_started/anomalib.html Install Anomalib and its core dependencies using uv or pip. PyTorch is installed based on default behavior. ```bash # With uv uv pip install anomalib # Or with pip pip install anomalib ``` -------------------------------- ### Install Anomalib with Hardware-Specific Extras (pip) Source: https://anomalib.readthedocs.io/en/latest/markdown/get_started/anomalib.html Install Anomalib with specific hardware backends like CPU or CUDA using pip. A full installation with all optional dependencies is also supported. ```bash # To ensure a specific hardware backend, you must specify an extra. # For example, for CPU: pip install "anomalib[cpu]" # Or for CUDA 13.0: pip install "anomalib[cu130]" # For a full installation with all optional dependencies on CPU: pip install "anomalib[full,cpu]" ``` -------------------------------- ### Branch Naming Examples Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/developer/contributing.html Illustrative examples of branch names following the specified convention. ```text feat/model/add-transformer ``` ```text fix/data/load-image-bug ``` ```text docs/readme/update-installation ``` ```text refactor/utils/optimize-performance ``` -------------------------------- ### CFA Model Initialization Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/image/cfa.html Shows how to instantiate the CfaModel with various configuration parameters. ```python model = CfaModel( backbone="resnet18", gamma_c=1, gamma_d=1, num_nearest_neighbors=3, num_hard_negative_features=3, radius=0.5 ) ``` -------------------------------- ### Install Anomalib with Hardware-Specific Extras (uv) Source: https://anomalib.readthedocs.io/en/latest/markdown/get_started/anomalib.html Install Anomalib with specific hardware backends like CPU, CUDA, ROCm, or Intel XPU using uv. You can also combine extras and install all optional dependencies. ```bash # CPU support (works on all platforms) uv pip install "anomalib[cpu]" # CUDA support (Linux/Windows with NVIDIA GPU) uv pip install "anomalib[cu126]" # CUDA 12.6 uv pip install "anomalib[cu130]" # CUDA 13.0 uv pip install "anomalib[cu118]" # CUDA 11.8 # ROCm support (Linux with AMD GPU) uv pip install "anomalib[rocm]" # Intel XPU support (Linux/Windows with Intel GPU) uv pip install "anomalib[xpu]" # You can combine extras. For example, to install with CUDA 13.0 and OpenVINO support: uv pip install "anomalib[openvino,cu130]" # For a full installation with all optional dependencies on CPU: uv pip install "anomalib[full,cpu]" ``` -------------------------------- ### Initialize Engine from Configuration Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/engine/index.html Create an Engine instance along with a model and datamodule by loading configuration from a YAML file. This allows for custom training setups. ```python engine, model, datamodule = Engine.from_config(config_path="config.yaml") ``` -------------------------------- ### Install SHAP Library Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/how_to/pipelines/custom_pipeline.html Installs the SHAP library, which is required for computing and visualizing feature contributions. ```bash pip install shap ``` -------------------------------- ### Initialize KDEClassifier with FeatureScalingMethod Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/components/classification.html Demonstrates how to create an instance of KDEClassifier, specifying the feature scaling method. ```python >>> from anomalib.models.components.classification import KDEClassifier >>> from anomalib.models.components.classification import FeatureScalingMethod >>> # Create KDE classifier with min-max scaling >>> classifier = KDEClassifier( ... scaling_method=FeatureScalingMethod.MIN_MAX ... ) ``` -------------------------------- ### Advanced Installation with pip Source: https://anomalib.readthedocs.io/en/latest/_sources/markdown/get_started/anomalib.md Install Anomalib with hardware-specific extras using pip for better compatibility. ```bash pip install "anomalib[all]" ``` -------------------------------- ### Initialize MEBinPostProcessor with a model Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/post_processing/index.html Instantiate the MEBinPostProcessor and then use it to initialize a model like Padim. This sets up the model to use MEBin for post-processing. ```python >>> from anomalib.models import Padim >>> from anomalib.post_processing import MEBinPostProcessor >>> post_processor = MEBinPostProcessor() >>> model = Padim(post_processor=post_processor) ``` -------------------------------- ### Setup WinClipModel with Class Name and Reference Images Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/image/winclip.html Initializes and sets up the WinClipModel with a class name and reference images for few-shot inference. Retrieves visual embeddings and updates k_shot. ```python ref_images = torch.rand(2, 3, 240, 240) model = WinClipModel() model.setup("transistor", ref_images) model.k_shot model.visual_embeddings[0].shape ``` -------------------------------- ### Initialize and Use GaussianKDE Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/components/stats.html Demonstrates how to initialize, fit, and predict density using GaussianKDE. The bandwidth is automatically selected using Scott’s rule. ```python >>> import torch >>> from anomalib.models.components.stats import GaussianKDE >>> # Create density estimator >>> kde = GaussianKDE() >>> # Fit and evaluate density >>> features = torch.randn(100, 10) # 100 samples, 10 dimensions >>> kde.fit(features) >>> density = kde.predict(features) ``` -------------------------------- ### Cflow Example Usage Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/image/cflow.html A basic example demonstrating how to import and instantiate the Cflow model in PyTorch. ```python import torch from anomalib.models.image.cflow import Cflow # Instantiate the model model = Cflow() # Example input tensor (batch_size=1, channels=3, height=256, width=256) # Note: Input size might need adjustment based on model configuration and dataset. input_tensor = torch.randn(1, 3, 256, 256) # Forward pass (example - actual usage might involve training_step or validation_step) # This is a simplified example and may not represent a full training/inference cycle. # The model's forward method is typically called internally by PyTorch Lightning. # For direct forward pass, you might need to handle feature extraction and decoder logic manually or via specific methods. # print(model(input_tensor)) # This line is commented out as direct forward pass might not be the intended usage pattern outside of LightningModule methods. ``` -------------------------------- ### WinClipModel.setup Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/image/winclip.html Sets up the WinClip model with class names and/or reference images. This method collects text and visual embeddings used during inference. It can be called manually to update embeddings after initialization. ```APIDOC ## WinClipModel.setup ### Description Sets up the WinClip model with class name and/or reference images. This method collects text and visual embeddings used during inference. The `k_shot` attribute is updated based on the number of reference images. This method is called by the constructor but can also be called manually to update embeddings after initialization. ### Parameters * **class_name** (`str` | `None`) - Optional - Name of object class for prompt ensemble. Defaults to `None`. * **reference_images** (`Tensor` | `None`) - Optional - Reference images of shape `(batch_size, C, H, W)`. Defaults to `None`. ### Return Type `None` ### Raises **RuntimeError** – If patch embeddings not collected via `setup`. ### Examples ```python >>> model = WinClipModel() >>> model.setup("transistor") >>> model.text_embeddings.shape torch.Size([2, 640]) ``` ```python >>> ref_images = torch.rand(2, 3, 240, 240) >>> model = WinClipModel() >>> model.setup("transistor", ref_images) >>> model.k_shot 2 >>> model.visual_embeddings[0].shape torch.Size([2, 196, 640]) ``` ```python >>> model = WinClipModel("transistor") >>> model.k_shot 0 >>> model.setup(reference_images=ref_images) >>> model.k_shot 2 ``` ```python >>> model = WinClipModel( ... class_name="transistor", ... reference_images=ref_images ... ) >>> model.text_embeddings.shape torch.Size([2, 640]) >>> model.visual_embeddings[0].shape torch.Size([2, 196, 640]) ``` ``` -------------------------------- ### Development Commit Examples Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/developer/contributing.html Examples of individual commit messages during development, which can use any format before the PR title is finalized. ```bash git add git commit -m "wip: working on transformer model" git commit -m "fix typo" git commit -m "address review comments" ``` -------------------------------- ### Initialize MEBinPostProcessor with custom parameters Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/post_processing/index.html Instantiate the MEBinPostProcessor with custom sample_rate and min_interval_len parameters. This allows for finer control over the thresholding process. The processor can then be used with a model like Patchcore. ```python >>> from anomalib.post_processing import MEBinPostProcessor >>> processor = MEBinPostProcessor(sample_rate=4, min_interval_len=4) >>> # Use with a model >>> from anomalib.models import Patchcore >>> model = Patchcore(post_processor=processor) ``` -------------------------------- ### Initialize and configure INP-Former model Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/image/inp_former.html Demonstrates basic usage with default parameters and provides an example of custom configuration for the INP-Former model, including specifying the encoder and the number of INPs. ```python from anomalib.data import MVTecAD from anomalib.models import InpFormer # Basic usage with default parameters model = InpFormer() # Custom configuration model = InpFormer( encoder_name="dinov2reg_vit_large_14", inp_num=6 ) # Training with datamodule datamodule = MVTecAD() engine = Engine() engine.fit(model, datamodule=datamodule) ``` -------------------------------- ### AnomalyMapGenerator Initialization Example Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/image/cflow.html An example demonstrating the initialization of AnomalyMapGenerator with specific pooling layers and generating an anomaly map from sample distributions. ```python >>> pool_layers = ["layer1", "layer2", "layer3"] >>> generator = AnomalyMapGenerator(pool_layers=pool_layers) >>> distribution = [torch.randn(32, 64) for _ in range(3)] >>> height = [32, 16, 8] >>> width = [32, 16, 8] >>> anomaly_map = generator( ... distribution=distribution, ... height=height, ... width=width ... ) ``` -------------------------------- ### Instantiate Kolektor Datamodule Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/data/datamodules/image/kolektor.html Instantiate the Kolektor Datamodule with specified parameters and set up the data loaders. This example shows how to initialize the module and access the training data. ```python from anomalib.data import Kolektor datamodule = Kolektor( root="./datasets/kolektor", train_batch_size=32, eval_batch_size=32, num_workers=8, ) datamodule.setup() i, data = next(enumerate(datamodule.train_dataloader())) data.keys() ``` -------------------------------- ### Benchmark Configuration Example Source: https://anomalib.readthedocs.io/en/latest/_sources/markdown/guides/reference/pipelines/benchmark/index.md This YAML configuration defines the parameters for a benchmark run, including accelerators, model classes, and dataset categories for grid search. ```yaml accelerator: - cuda - cpu benchmark: seed: 42 model: class_path: grid_search: [Padim, Patchcore] data: class_path: MVTecAD init_args: category: grid: - bottle - cable - capsule ``` -------------------------------- ### Conventional Commit PR Title Examples Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/developer/contributing.html Examples demonstrating the correct format for pull request titles, including different types and scopes. ```text feat(model): add transformer architecture for anomaly detection ``` ```text fix(data): handle corrupted image files during training ``` ```text docs: update installation instructions for Windows ``` ```text chore(ci): migrate from commit message validation to PR title validation ``` -------------------------------- ### EfficientAdModel Instantiation and Inference (Detailed) Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/image/efficient_ad.html Shows how to import and instantiate the EfficientAdModel, then perform inference. This example is similar to the first but includes the import statement within the code block. ```python >>> from anomalib.models.image.efficient_ad.torch_model import ( ... EfficientAdModel, ... ) >>> model = EfficientAdModel() >>> model.eval() >>> input_tensor = torch.randn(32, 3, 256, 256) >>> output = model(input_tensor) >>> output.anomaly_map.shape torch.Size([32, 1, 256, 256]) ``` -------------------------------- ### Initialize model and datamodule Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/image/fre.html Instantiate the MVTecAD datamodule, the Fre model, and the Engine. ```python datamodule = MVTecAD() model = Fre() engine = Engine() ``` -------------------------------- ### Anomalib CLI Example Source: https://anomalib.readthedocs.io/en/latest/_sources/markdown/guides/how_to/pipelines/custom_pipeline.md This snippet shows an example of how to use the Anomalib CLI to run a custom pipeline. Ensure the pipeline configuration is correctly set up. ```bash anomalib pipeline experiment --config configs/dummy/dummy_pipeline.yaml ``` -------------------------------- ### Instantiate WinClip Model Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/image/winclip.html Demonstrates different ways to instantiate the WinClip model, including zero-shot, few-shot with a specified number of reference images, and with a custom class name. ```python from anomalib.models.image import WinClip # Zero-shot approach model = WinClip() # Few-shot with 5 reference images model = WinClip(k_shot=5) # Custom class name model = WinClip(class_name="transistor") ``` -------------------------------- ### Example DataFrame Structure Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/how_to/data/datasets.html This example shows the structure of the DataFrame used to manage dataset samples, including image paths, labels, and mask paths. ```python import pandas as pd df = pd.DataFrame({ 'image_path': ['path/to/image.png'], 'label': ['anomalous'], 'label_index': [1], 'mask_path': ['path/to/mask.png'], 'split': ['train'] }) ``` -------------------------------- ### Initialize GaussianKDE with Dataset Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/components/stats.html Shows how to initialize GaussianKDE directly with a dataset or fit it later. The model estimates probability density using a Gaussian kernel function. ```python >>> import torch >>> from anomalib.models.components.stats import GaussianKDE >>> features = torch.randn(100, 10) # 100 samples, 10 dimensions >>> # Initialize and fit in one step >>> kde = GaussianKDE(dataset=features) >>> # Or fit later >>> kde = GaussianKDE() >>> kde.fit(features) >>> # Get density estimates >>> density = kde(features) ``` -------------------------------- ### Install Anomalib via PyPI Source: https://anomalib.readthedocs.io/en/latest/_sources/index.md Use this command to install the Anomalib library from PyPI. This is recommended for users who want to use the library without modifying its source code. ```bash pip install anomalib ``` -------------------------------- ### Initialize and Use KCenterGreedy Sampler Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/components/sampling_components.html Demonstrates how to initialize the KCenterGreedy sampler and use it to select a coreset from a set of feature embeddings. ```python import torch from anomalib.models.components.sampling import KCenterGreedy # Create sampler sampler = KCenterGreedy() # Sample from feature embeddings features = torch.randn(100, 512) # 100 samples with 512 dimensions selected_idx = sampler.select_coreset(features, n=10) ``` -------------------------------- ### Setup WinClipModel with Class Name Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/models/image/winclip.html Initializes and sets up the WinClipModel with a class name for zero-shot inference. Retrieves text embeddings. ```python model = WinClipModel() model.setup("transistor") model.text_embeddings.shape ``` -------------------------------- ### Get all keys from NumpyBatch Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/data/dataclasses/numpy.html Use the `keys()` method to retrieve a list of field names from a NumpyBatch instance. By default, it includes all possible fields, even if their values are None. Set `include_none=False` to get only the fields that contain data. ```python import numpy as np from anomalib.data.dataclasses.numpy import NumpyBatch batch = NumpyBatch(image=np.random.rand(2, 224, 224, 3)) all_keys = batch.keys() # Default: include_none=True print('pred_score' in all_keys) set_keys = batch.keys(include_none=False) print('pred_score' in set_keys) ``` -------------------------------- ### Experiment Logging with CLI Source: https://anomalib.readthedocs.io/en/latest/_sources/markdown/get_started/anomalib.md Run a training experiment with experiment tracking enabled via the CLI. This requires a configuration file. ```bash python tools/train.py model_name=patchcore dataset_path=./datasets/mvtec/bottle logger=wandb ``` -------------------------------- ### Create VideoItem and VideoBatch Source: https://anomalib.readthedocs.io/en/latest/_sources/markdown/guides/how_to/data/dataclasses.md Instantiate `VideoItem` for a single video and `VideoBatch` for multiple videos, including temporal frame data. ```python from anomalib.data.dataclasses.torch import VideoItem, VideoBatch # Single video item item = VideoItem( image=torch.rand(10, 3, 224, 224), # 10 frames gt_label=torch.tensor(0), video_path="path/to/video.mp4", ) # Batch of video items batch = VideoBatch( image=torch.rand(32, 10, 3, 224, 224), # 32 videos, 10 frames gt_label=torch.randint(0, 2, (32,)), video_path=["video_{}.mp4".format(i) for i in range(32)], ) ``` -------------------------------- ### anomalib.data.utils.image.get_image_filename Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/data/utils/image_video.html Get validated image filename. ```APIDOC ## anomalib.data.utils.image.get_image_filename ### Description Get validated image filename. ### Parameters #### Path Parameters - **filename** (str | Path) - Required - Path to image file ### Returns Validated path to image file ### Return Type Path ### Raises **FileNotFoundError** – If file does not exist **ValueError** – If file is not an image ### Examples ```python >>> from anomalib.data.utils import get_image_filename >>> get_image_filename("image.jpg") PosixPath('image.jpg') >>> get_image_filename("missing.jpg") Traceback (most recent call last): ... FileNotFoundError: File not found: missing.jpg >>> get_image_filename("text.txt") Traceback (most recent call last): ... ValueError: ``filename`` is not an image file: text.txt ``` ``` -------------------------------- ### GraphLogger on_train_start Example Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/callbacks/index.html Demonstrates the `on_train_start` method of the GraphLogger callback. This method is automatically called at the beginning of training, particularly for setting up model watching with graph logging enabled for W&B. ```python from anomalib.callbacks import GraphLogger callback = GraphLogger() # Called automatically by trainer # callback.on_train_start(trainer, model) ``` -------------------------------- ### anomalib.data.utils.image.get_image_filenames_from_dir Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/data/utils/image_video.html Get list of image filenames from directory. ```APIDOC ## anomalib.data.utils.image.get_image_filenames_from_dir ### Description Get list of image filenames from directory. ### Parameters #### Path Parameters - **path** (str | Path) - Required - Path to directory containing images ### Returns List of paths to image files ### Return Type list[Path] ### Raises **ValueError** – If path is not a directory or no images found ### Examples ```python >>> from anomalib.data.utils import get_image_filenames_from_dir >>> get_image_filenames_from_dir("images/") [PosixPath('images/001.jpg'), PosixPath('images/002.png')] >>> get_image_filenames_from_dir("empty/") Traceback (most recent call last): ... ValueError: Found 0 images in empty/ ``` ``` -------------------------------- ### anomalib.data.utils.image.get_image_filenames Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/data/utils/image_video.html Get list of image filenames from path. ```APIDOC ## anomalib.data.utils.image.get_image_filenames ### Description Get list of image filenames from path. ### Parameters #### Path Parameters - **path** (str | Path) - Required - Path to image file or directory - **base_dir** (str | Path | None) - Optional - Base directory to restrict file access ### Returns List of paths to image files ### Return Type list[Path] ### Examples ```python >>> from anomalib.data.utils import get_image_filenames >>> get_image_filenames("image.jpg") [PosixPath('image.jpg')] >>> get_image_filenames("images/") [PosixPath('images/001.jpg'), PosixPath('images/002.png')] >>> get_image_filenames("images/", base_dir="allowed/") Traceback (most recent call last): ... ValueError: Access denied: Path is outside the allowed directory ``` ``` -------------------------------- ### anomalib.data.utils.image.get_image_height_and_width Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/data/utils/image_video.html Get height and width from image size parameter. ```APIDOC ## anomalib.data.utils.image.get_image_height_and_width ### Description Get height and width from image size parameter. ### Parameters #### Path Parameters - **image_size** (int | Sequence[int]) - Required - Single int for square, or (H,W) sequence ### Returns Image height and width ### Return Type tuple[int, int] ### Raises **TypeError** – If image_size is not int or sequence of ints ### Examples ```python >>> from anomalib.data.utils import get_image_height_and_width >>> get_image_height_and_width(256) (256, 256) >>> get_image_height_and_width((480, 640)) (480, 640) ``` ``` -------------------------------- ### Initialize BenchmarkJob Source: https://anomalib.readthedocs.io/en/latest/markdown/guides/reference/pipelines/benchmark/job.html Initialize the BenchmarkJob with a model, datamodule, accelerator, seed, and configuration. ```python # Initialize model, datamodule and job model = Padim() datamodule = MVTecAD(category="bottle") job = BenchmarkJob( accelerator="gpu", model=model, datamodule=datamodule, seed=42, flat_cfg={"model.name": "padim"} ) ```