Anomalib in 15 Minutes#
This section will walk you through the steps to train a model and use it to detect anomalies in a dataset.
Installation#
Anomalib can be installed from PyPI. We recommend using a virtual environment and a modern package installer like uv or pip.
Quick Install#
For a standard installation, you can use uv or pip. This will install the latest version of Anomalib with its core dependencies. PyTorch will be installed based on its default behavior, which usually works for CPU and standard CUDA setups.
# With uv
uv pip install anomalib
# Or with pip
pip install anomalib
For more control over the installation, such as specifying the PyTorch backend or installing extra dependencies, see the advanced options below.
Advanced: Install with Hardware-Specific Extras
To ensure compatibility with your hardware, you can specify a backend during installation. This is the recommended approach for production environments and for hardware other than CPU or standard CUDA.
Using uv:
# To ensure a specific hardware backend, use one of the following extras:
# CPU support (works on all platforms)
uv pip install "anomalib[cpu]"
# CUDA support (Linux/Windows with NVIDIA GPU)
uv pip install "anomalib[cu124]" # CUDA 12.4
uv pip install "anomalib[cu121]" # CUDA 12.1
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 12.4 and OpenVINO support:
uv pip install "anomalib[openvino,cu124]"
# For a full installation with all optional dependencies on CPU:
uv pip install "anomalib[full,cpu]"
Using pip:
# To ensure a specific hardware backend, you must specify an extra.
# For example, for CPU:
pip install "anomalib[cpu]"
# Or for CUDA 12.4:
pip install "anomalib[cu124]"
# For a full installation with all optional dependencies on CPU:
pip install "anomalib[full,cpu]"
Training#
Anomalib supports both API and CLI-based training. The API is more flexible and allows for more customization, while the CLI training utilizes command line interfaces, and might be easier for those who would like to use anomalib off-the-shelf.
# 1. Import required modules
from anomalib.data import MVTecAD
from anomalib.engine import Engine
from anomalib.models import EfficientAd
# 2. Create a dataset
# MVTecAD is a popular dataset for anomaly detection
datamodule = MVTecAD(
root="./datasets/MVTecAD", # Path to download/store the dataset
category="bottle", # MVTec category to use
train_batch_size=32, # Number of images per training batch
eval_batch_size=32, # Number of images per validation/test batch
num_workers=8, # Number of parallel processes for data loading
)
# 3. Initialize the model
# EfficientAd is a good default choice for beginners
model = EfficientAd()
# 4. Create the training engine
engine = Engine(max_epochs=10) # Train for 10 epochs
# 5. Train the model
engine.fit(datamodule=datamodule, model=model)
#!/bin/bash
# Copyright (C) 2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# Getting Started with Anomalib Training
# ------------------------------------
# This example shows the basic steps to train an anomaly detection model.
# 1. Basic Training
# Train a model using default configuration (recommended for beginners)
echo "Training with default configuration..."
anomalib train --model efficient_ad
# 2. Training with Basic Customization
# Customize basic parameters like batch size and epochs
echo -e "\nTraining with custom parameters..."
anomalib train --model efficient_ad \
--data.train_batch_size 32 \
--trainer.max_epochs 10
# 3. Using a Different Dataset
# Train on a specific category of MVTecAD dataset
echo -e "\nTraining on MVTecAD bottle category..."
anomalib train --model efficient_ad \
--data.category bottle
Inference#
Anomalib includes multiple inferencing scripts, including Torch, Lightning, Gradio, and OpenVINO inferencers to perform inference using the trained/exported model. Here we show an inference example using the Lightning inferencer.
Lightning Inference
# Copyright (C) 2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""Getting Started with Anomalib Inference using the Python API.
This example shows how to perform inference on a trained model
using the Anomalib Python API.
"""
# 1. Import required modules
from pathlib import Path
from anomalib.data import PredictDataset
from anomalib.engine import Engine
from anomalib.models import EfficientAd
# 2. Initialize the model and load weights
model = EfficientAd()
engine = Engine()
# 3. Prepare test data
# You can use a single image or a folder of images
dataset = PredictDataset(
path=Path("path/to/test/images"),
image_size=(256, 256),
)
# 4. Get predictions
predictions = engine.predict(
model=model,
dataset=dataset,
ckpt_path="path/to/model.ckpt",
)
# 5. Access the results
if predictions is not None:
for prediction in predictions:
image_path = prediction.image_path
anomaly_map = prediction.anomaly_map # Pixel-level anomaly heatmap
pred_label = prediction.pred_label # Image-level label (0: normal, 1: anomalous)
pred_score = prediction.pred_score # Image-level anomaly score
#!/usr/bin/env bash
# shellcheck shell=bash
# Copyright (C) 2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# Getting Started with Anomalib Inference
# This example shows how to perform inference using Engine().predict() arguments.
echo "=== Anomalib Inference Examples ==="
echo -e "\n1. Basic Inference with Checkpoint Path"
echo "# Predict using a model checkpoint"
anomalib predict \
--ckpt_path "./results/efficient_ad/mvtecad/bottle/weights/model.ckpt" \
--data_path path/to/image.jpg
echo -e "\n2. Inference with Directory Path"
echo "# Predict on all images in a directory"
anomalib predict \
--ckpt_path "./results/efficient_ad/mvtecad/bottle/weights/model.ckpt" \
--data_path "./datasets/mvtecad/bottle/test"
echo -e "\n3. Inference with Datamodule"
echo "# Use a datamodule for inference"
anomalib predict \
--ckpt_path "./results/my_dataset/weights/model.ckpt" \
--datamodule.class_path anomalib.data.Folder \
--datamodule.init_args.name "my_dataset" \
--datamodule.init_args.root "./datasets/my_dataset" \
--datamodule.init_args.normal_dir "good" \
--datamodule.init_args.abnormal_dir "defect"
echo -e "\n4. Inference with Return Predictions"
echo "# Return predictions instead of saving to disk"
anomalib predict \
--ckpt_path "./results/efficient_ad/mvtecad/bottle/weights/model.ckpt" \
--data_path path/to/image.jpg \
--return_predictions
echo -e "\n=== Example Output ==="
echo '
GPU available: True (cuda), used: True
TPU available: False, using: 0 TPU cores
IPU available: False, using: 0 IPUs
HPU available: False, using: 0 HPUs
[2024-01-01 12:00:00][INFO][anomalib][predict]: Loading model from ./results/my_dataset/weights/model.ckpt
[2024-01-01 12:00:01][INFO][anomalib][predict]: Prediction started
[2024-01-01 12:00:02][INFO][anomalib][predict]: Predictions saved to ./results/my_dataset/predictions'
echo -e "\nNote: Replace paths according to your setup."
echo "The predictions will be saved in the results directory by default unless --return_predictions is used."
Torch Inference
OpenVINO Inference
Gradio Inference
Hyper-Parameter Optimization#
Anomalib supports hyper-parameter optimization using wandb and comet.ml. Here we show an example of hyper-parameter optimization using both comet and wandb.
# To perform hpo using wandb sweep
anomalib hpo --backend WANDB --sweep_config tools/hpo/configs/wandb.yaml
# To perform hpo using comet.ml sweep
anomalib hpo --backend COMET --sweep_config tools/hpo/configs/comet.yaml
# To be enabled in v1.1
Experiment Management#
Anomalib is integrated with various libraries for experiment tracking such as comet, tensorboard, and wandb through lighting loggers.
To run a training experiment with experiment tracking, you will need the following configuration file:
By using the configuration file above, you can run the experiment with the following command:
Benchmarking#
Anomalib provides a benchmarking tool to evaluate the performance of the anomaly detection models on a given dataset. The benchmarking tool can be used to evaluate the performance of the models on a given dataset, or to compare the performance of multiple models on a given dataset.
Each model in anomalib is benchmarked on a set of datasets, and the results are available in src/anomalib/models/<model_name>README.md. For example, the MVTecAD AD results for the Patchcore model are available in the corresponding README.md file.
To run the benchmarking tool, run the following command:
anomalib benchmark --config tools/benchmarking/benchmark_params.yaml
Reference#
If you use this library and love it, use this to cite it:
@inproceedings{akcay2022anomalib,
title={Anomalib: A deep learning library for anomaly detection},
author={
Akcay, Samet and
Ameln, Dick and
Vaidya, Ashwin and
Lakshmanan, Barath
and Ahuja, Nilesh
and Genc, Utku
},
booktitle={2022 IEEE International Conference on Image Processing (ICIP)},
pages={1706--1710},
year={2022},
organization={IEEE}
}