Overview
ThePatchCore class is the core implementation of the PatchCore algorithm for industrial anomaly detection. It provides methods for loading models, training on normal data, and predicting anomalies in images.
Class Definition
torch.nn.Module.
The device (CPU or CUDA) on which to run the model.
Methods
load
Parameters
Pre-trained neural network backbone for feature extraction (e.g., ResNet, WideResNet).
List of layer names from which to extract features from the backbone.
Device on which to load the model.
Shape of input images (e.g.,
(3, 224, 224) for RGB images).Dimension to which features are projected before aggregation.
Target dimension for final feature embeddings.
Size of patches to extract from feature maps.
Stride for patch extraction from feature maps.
Number of nearest neighbors to use for anomaly scoring.
Sampler to use for subsampling features during training. Can be
IdentitySampler, GreedyCoresetSampler, or RandomSampler.Nearest neighbor search method for anomaly scoring.
Example
fit
DataLoader or iterable containing normal (non-anomalous) training images. Images should be dictionaries with an
"image" key or raw tensors.Example
The
fit method only requires normal (non-anomalous) images. PatchCore learns what “normal” looks like and detects deviations from this during inference.predict
Input image tensor or DataLoader. If a tensor, shape should be
[B, C, H, W]. If a DataLoader, images can be dictionaries with "image", "is_anomaly", and "mask" keys.Returns
List of anomaly scores for each image. Higher scores indicate higher likelihood of anomaly.
List of anomaly segmentation masks for each image. Values are normalized between 0 and 1.
Ground truth labels (only returned when using DataLoader with labeled data).
Ground truth masks (only returned when using DataLoader with labeled data).
Example
embed
Input images as tensor
[B, C, H, W] or DataLoader.Returns
Feature embeddings extracted from the images. Shape depends on the number of patches and target embedding dimension.
save_to_path
Directory path where the model will be saved.
Optional prefix to prepend to saved filenames.
Example
load_from_path
Directory path from which to load the model.
Device on which to load the model.
Nearest neighbor search method to use.
Optional prefix used when saving the model.
Example
PatchMaker Class
Internal utility class for patch extraction and scoring.Size of patches to extract.
Stride for patch extraction. If None, defaults to patchsize.
Methods
patchify
Input feature tensor with shape
[B, C, H, W].Whether to return spatial information about patches.
