{ "cells": [ { "cell_type": "markdown", "id": "3405d28d", "metadata": {}, "source": [ "# Image Anomaly Detection with PyTorch using
Intel® Transfer Learning Tool\n", "\n", "This notebook demonstrates anomaly detection using the Intel Transfer Learning Toolkit. It performs defect analysis with the MVTec dataset using PyTorch. The workflow uses a pretrained ResNet50 v1.5 model from torchvision." ] }, { "cell_type": "markdown", "id": "1d61b7ac", "metadata": {}, "source": [ "## 1. Import dependencies and setup parameters\n", "\n", "This notebook assumes that you have already followed the instructions to setup a PyTorch environment with all the dependencies required to run the notebook." ] }, { "cell_type": "code", "execution_count": null, "id": "a0bf9fd0", "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import os\n", "import pandas as pd\n", "import PIL.Image as Image\n", "import torch, torchvision\n", "from torchvision.transforms.functional import InterpolationMode\n", "import requests\n", "from io import BytesIO\n", "\n", "# tlt imports\n", "from tlt.datasets import dataset_factory\n", "from tlt.models import model_factory\n", "from tlt.utils.file_utils import download_and_extract_tar_file, download_file\n", "\n", "# Specify a directory for the dataset to be downloaded\n", "dataset_dir = os.environ[\"DATASET_DIR\"] if \"DATASET_DIR\" in os.environ else \\\n", " os.path.join(os.environ[\"HOME\"], \"dataset\")\n", " \n", "# Specify a directory for output\n", "output_dir = os.environ[\"OUTPUT_DIR\"] if \"OUTPUT_DIR\" in os.environ else \\\n", " os.path.join(os.environ[\"HOME\"], \"output\")\n", "\n", "print(\"Dataset directory:\", dataset_dir)\n", "print(\"Output directory:\", output_dir)" ] }, { "cell_type": "markdown", "id": "8f1fc78c", "metadata": {}, "source": [ "## 2. Get or load the model\n", "\n", "In this step, we use the model factory to get the desired model. The `get_model` function returns a pretrained model object from a public model hub, while the `load_model` function loads a pretrained model from a checkpoint on your local disk or in memory.\n", "\n", "Here we are getting the pretrained `resnet50` model from Torchvision:" ] }, { "cell_type": "code", "execution_count": null, "id": "ad4aeafd", "metadata": {}, "outputs": [], "source": [ "model = model_factory.get_model(model_name=\"resnet50\", framework=\"pytorch\", use_case='anomaly_detection')" ] }, { "cell_type": "markdown", "id": "9d087ee7", "metadata": {}, "source": [ "To load a previously trained model from a file, use this:\n", "```\n", "model = model_factory.load_model(model_name=\"resnet50\", model=, framework=\"pytorch\", \n", " use_case='anomaly_detection')\n", "```" ] }, { "cell_type": "markdown", "id": "dabd4183", "metadata": {}, "source": [ "## 3. Get the dataset" ] }, { "cell_type": "markdown", "id": "2d314ba0", "metadata": {}, "source": [ "To use [MVTec](https://www.mvtec.com/company/research/datasets/mvtec-ad) or your own image dataset for anomaly detection, your image files (`.jpg` or `.png`) should be arranged in one of two ways. \n", "\n", "### Method 1: Category Folders\n", "\n", "Arrange them in folders in the root dataset directory like this:\n", "\n", "```\n", "hazelnut\n", " └── crack\n", " └── cut\n", " └── good\n", " └── hole\n", " └── print\n", "```\n", "\n", "IMPORTANT: There must be a subfolder named `good` and at least one other folder of defective examples. It does not matter what the names of the other folders are or how many there, as long as there is at least one. This would also be an acceptable Method 1 layout:\n", "\n", "```\n", "toothbrush\n", " └── defective\n", " └── good\n", "```\n", "\n", "TLT will encode all of the non-good images as \"bad\" and use the \"good\" images in the training set and a mix of good and bad images in the validation set.\n", "\n", "### Method 2: Train & Test Folders with Category Subfolders\n", "\n", "Arrange them in folders in the root dataset directory like this:\n", "\n", "```\n", "hazelnut\n", " └── train\n", " └── good\n", " └── test\n", " └── crack\n", " └── cut\n", " └── good\n", " └── hole\n", " └── print\n", "```\n", "\n", "When using this layout, TLT will use the exact defined split for train and validation subsets unless you use the `shuffle_split` method to re-shuffle and split up the \"good\" images with certain percentages. " ] }, { "cell_type": "code", "execution_count": null, "id": "64b24c5b-9b48-4041-a6a2-7c438ca3a0c5", "metadata": {}, "outputs": [], "source": [ "img_dir = os.path.join(dataset_dir, 'hazelnut')" ] }, { "cell_type": "code", "execution_count": null, "id": "357f3dfd", "metadata": {}, "outputs": [], "source": [ "# Select the subdirectory in dataset_dir to use\n", "dataset = dataset_factory.load_dataset(img_dir,\n", " use_case='image_anomaly_detection', \n", " framework=\"pytorch\")\n", "\n", "print(dataset._dataset)\n", "print(\"Class names:\", str(dataset.class_names))\n", "print(\"Defect names:\", dataset.defect_names)" ] }, { "cell_type": "markdown", "id": "2200ef4e", "metadata": {}, "source": [ "Note: The defects argument can be used to filter the validation set to use only a subset of defect types. For example:\n", "```\n", "dataset = dataset_factory.load_dataset(img_dir, \n", " use_case='image_anomaly_detection', \n", " framework=\"pytorch\",\n", " defects=['crack', 'hole'])\n", "```" ] }, { "cell_type": "markdown", "id": "99f23249", "metadata": {}, "source": [ "## 4. Prepare the dataset\n", "Once you have your dataset, use the following cells to split and preprocess the data. We split them into training and test subsets, then resize the images to match the selected model, and then batch the images. Pass in optional arguments to customize the [Resize](https://pytorch.org/vision/main/generated/torchvision.transforms.Resize.html) or [Normalize](https://pytorch.org/vision/main/generated/torchvision.transforms.Normalize.html) transforms.\n", "Data augmentation can be applied to the training set by specifying the augmentations to be applied in the `add_aug` parameter. Supported augmentations are given below:\n", "1. hflip - RandomHorizontalFlip\n", "2. rotate - RandomRotate" ] }, { "cell_type": "code", "execution_count": null, "id": "dd91fbcf", "metadata": {}, "outputs": [], "source": [ "# If using Method 1 layout, split the dataset into training and test subsets.\n", "if dataset._validation_type is None:\n", " dataset.shuffle_split(train_pct=.75, val_pct=0.0, test_pct=0.25)" ] }, { "cell_type": "markdown", "id": "4fbe27a3-1b1e-4add-9725-28bceb62c474", "metadata": {}, "source": [ "For __cutpaste__ feature extractor, cutpaste_type can be specified in the dataset.preprocess() method as follows. The option available are - _normal_, _scar_, _3way_ and _union_. Default is _normal_.\n", "```\n", "dataset.preprocess(224, batch_size=batch_size, interpolation=InterpolationMode.LANCZOS, cutpaste_type='normal')\n", "```" ] }, { "cell_type": "code", "execution_count": null, "id": "e7c95a70", "metadata": {}, "outputs": [], "source": [ "# Preprocess with an image size that matches the model, batch size 32, and the desired interpolation method\n", "batch_size = 64\n", "cutpaste_type = 'normal'\n", "dataset.preprocess(224, batch_size=batch_size, interpolation=InterpolationMode.LANCZOS, cutpaste_type=cutpaste_type)" ] }, { "cell_type": "markdown", "id": "3704772b", "metadata": {}, "source": [ "## 5. Visualize samples from the dataset\n", "\n", "We get a single batch from our training and test subsets and visualize the images as a sanity check." ] }, { "cell_type": "code", "execution_count": null, "id": "cd6782b0", "metadata": {}, "outputs": [], "source": [ "def plot_images(images, labels, sup_title, predictions=None):\n", " plt.figure(figsize=(18,14))\n", " plt.subplots_adjust(hspace=0.5)\n", " for n in range(min(batch_size, 30)):\n", " plt.subplot(6,5,n+1)\n", " inp = images[n]\n", " inp = inp.numpy().transpose((1, 2, 0))\n", " mean = np.array([0.485, 0.456, 0.406])\n", " std = np.array([0.229, 0.224, 0.225])\n", " inp = std * inp + mean\n", " inp = np.clip(inp, 0, 1)\n", " plt.imshow(inp)\n", " if predictions:\n", " correct_prediction = labels[n] == predictions[n]\n", " color = \"darkgreen\" if correct_prediction else \"crimson\"\n", " title = predictions[n] if correct_prediction else \"{}\".format(predictions[n])\n", " else:\n", " good_sample = labels[n] == 'good'\n", " color = \"darkgreen\" if labels[n] == 'good' else (\"crimson\" if labels[n] == 'bad' else \"black\")\n", " title = labels[n]\n", " plt.title(title, fontsize=14, color=color)\n", " plt.axis('off')\n", " _ = plt.suptitle(sup_title, fontsize=20)\n", " plt.show()" ] }, { "cell_type": "code", "execution_count": null, "id": "ffcd2071", "metadata": {}, "outputs": [], "source": [ "# Plot some images from the training set\n", "images, labels = dataset.get_batch()\n", "labels = [dataset.class_names[id] for id in labels]\n", "plot_images(images, labels, 'Training Samples')" ] }, { "cell_type": "code", "execution_count": null, "id": "d37b808f", "metadata": {}, "outputs": [], "source": [ "# Plot some images from the test set\n", "test_images, test_labels = dataset.get_batch(subset='test')\n", "test_labels = [dataset.class_names[id] for id in test_labels]\n", "plot_images(test_images, test_labels, 'Test Samples')" ] }, { "cell_type": "markdown", "id": "a49ec7b7", "metadata": {}, "source": [ "## 6. Training and Evaluation\n", "\n", "This step calls the model's train function with the dataset that was just prepared. The training function will get the torchvision feature extractor for the user's desired layer and extract features from the training set. The extracted features are used to perform a [principal component analysis](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html). The model's evaluate function returns the AUROC metric ([area under](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.auc.html) the [roc curve](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_curve.html)) calculated from the dataset's test subset." ] }, { "cell_type": "markdown", "id": "ab510f51", "metadata": {}, "source": [ "### Train Arguments\n", "\n", "#### Required\n", "- **dataset** (ImageAnomalyDetectionDataset, required): Dataset to use when training the model\n", "- **output_dir** (str): Path to a writeable directory\n", "\n", "#### Optional\n", "- **generate_checkpoints** (bool): Whether to save/preserve the best weights during SimSiam training (default: True)\n", "- **initial_checkpoints** (str): The path to a starting weights file\n", "- **layer_name** (str): The layer name whose output is desired for the extracted features\n", "- **pooling** (str): Pooling to be applied on the extracted layer ('avg' or 'max') (default: 'avg')\n", "- **kernel_size** (int): Kernel size in the pooling layer (default: 2)\n", "- **pca_threshold** (float): Threshold to apply to PCA model (default: 0.99)\n", "\n", "Note: refer to release documentation for an up-to-date list of train arguments and their current descriptions" ] }, { "cell_type": "code", "execution_count": null, "id": "8cd9420d", "metadata": {}, "outputs": [], "source": [ "# Examine the model's layers and decide which to use for feature extraction\n", "model.list_layers(verbose=False)\n", "layer = 'layer3'" ] }, { "cell_type": "markdown", "id": "b19be956-e3c6-4d9d-847d-779c1c35da38", "metadata": {}, "source": [ "## Feature Extraction\n", "There are three feature extractor options available within the `model.train()` function.\n", "1. __No fine-tuning__ - To use a pretrained ResNet50/ResNet18 model for feature extraction, simply call `model.load_pretrained_model()`\n", "2. [__SimSiam__](https://arxiv.org/abs/2011.10566) - A self-supervised neural network based on Siamese networks. It learns a meaningful representation of dataset without using any labels. If selected, SimSiam generates quality features that can help differentiate between regular and anomaly images in a given context. SimSiam produces two different augmented images from one underlying image. The end goal is to train the network to produce the same features for both images. It takes a ResNet model as the backbone and fine-tunes the model on the augmented dataset to get a better feature embedding. To use this feature extractor, download the SimSiam weights based on ResNet50 - https://dl.fbaipublicfiles.com/simsiam/models/100ep-256bs/pretrain/checkpoint_0099.pth.tar - set `initial_checkpoints` to the path of the downloaded checkpoints in the `model.train_simsiam()` function.\n", "3. [__Cut-paste__](https://arxiv.org/abs/2104.04015#) - A self-supervised method for Anomaly Detection and Localization that takes ResNet50/ ResNet18 model as backbone and fine-tune the model on custom dataset to get better feature embedding. data augmentation strategy that cuts an image patch and pastes at a random location of a large image. To use this feature extractor, call `model.train_cutpaste()` function.\n", "\n", "\n", "### Optional: The SimSiam TwoCropTransform\n", "To train a Simsiam model, it is required to apply a TwoCropTransform augmentation technique on the dataset used for training. You can preview this augmentation on a sample batch after preprocessing by using `get_batch(simsiam=True)` and then use them for simsiam training in `model.train_simsiam()`." ] }, { "cell_type": "code", "execution_count": null, "id": "6b49522f", "metadata": {}, "outputs": [], "source": [ "# Get a batch of training data with the simsiam transform applied to it\n", "simsiam_images, _ = dataset.get_batch(simsiam=True)\n", "\n", "# Plot the \"A\" samples showing the first set of augmented images\n", "plot_images(simsiam_images[0], ['{}A'.format(i) for i in range(batch_size)], 'SimSiam \"A\" Samples')" ] }, { "cell_type": "code", "execution_count": null, "id": "a5da06df", "metadata": {}, "outputs": [], "source": [ "# Now plot the \"B\" samples showing the second set of augmented images based on the same underlying originals\n", "plot_images(simsiam_images[1], ['{}B'.format(i) for i in range(batch_size)], 'SimSiam \"B\" Samples')" ] }, { "cell_type": "markdown", "id": "ace7d296-74d9-47c1-aeaf-386433bac411", "metadata": {}, "source": [ "### Optional: The Cut-paste Transforms\n", "To train a model with Cut-paste , it is required to apply one of the four augmentations - __CutPasteNormal, CutPasteScar, CutPaste3Way, CutPasteUnion__ on the dataset used for training. You can preview this augmentation on a sample batch after preprocessing by using `get_batch(cutpaste=True)` and then use them for cutpaste training in `model.train_cutpaste()`." ] }, { "cell_type": "code", "execution_count": null, "id": "21cbadd5-8387-4130-b5b4-e016d4ea4e5e", "metadata": {}, "outputs": [], "source": [ "# Get a batch of training data with the cutpaste transform applied to it\n", "cutpaste_images, _ = dataset.get_batch(cutpaste=True)\n", "\n", "# Plot the \"A\" samples showing the first set of augmented images\n", "plot_images(cutpaste_images[1], ['{}A'.format(i) for i in range(batch_size)], 'CutPaste \"A\" Samples')" ] }, { "cell_type": "code", "execution_count": null, "id": "750bc599-80e4-4e70-8aaf-5f63082b9198", "metadata": {}, "outputs": [], "source": [ "if cutpaste_type == '3way':\n", " # Now plot the \"B\" samples showing the second set of augmented images based on the same underlying originals\n", " plot_images(cutpaste_images[2], ['{}B'.format(i) for i in range(batch_size)], 'CutPaste \"B\" Samples')" ] }, { "cell_type": "markdown", "id": "73ecdb31-4105-40fa-a1b1-89c1a9b08108", "metadata": {}, "source": [ "To use a ResNet50 model for feature extraction, run the below command." ] }, { "cell_type": "code", "execution_count": null, "id": "5663a407-44d7-447d-aa75-a05ae8355716", "metadata": {}, "outputs": [], "source": [ "extract_model = model.load_pretrained_model()" ] }, { "cell_type": "markdown", "id": "275002cd-4708-4b19-a0bc-3e4a74af9ee2", "metadata": {}, "source": [ "There is no fine-tuning being demonstrated here, but you can use `simsiam` or `cutpaste` if desired.\n", "\n", "To use simsiam, pass the checkpoint file in `initial_checkpoints` to `model.train_simsiam()` as follows\n", "```\n", "components = model.train_simsiam(dataset, output_dir, epochs=2, feature_dim=1000,\n", " pred_dim=250, initial_checkpoints=,\n", " generate_checkpoints=False, precision='float32')\n", "```" ] }, { "cell_type": "code", "execution_count": null, "id": "392f7546-0ae5-4b6b-bba7-fbcf6220d0f0", "metadata": {}, "outputs": [], "source": [ "extract_model = model.train_simsiam(dataset, output_dir, epochs=2, feature_dim=1000, \n", " pred_dim=250, initial_checkpoints=None,\n", " generate_checkpoints=False, precision='float32')" ] }, { "cell_type": "markdown", "id": "bd5c4fb9-0f81-4753-b990-c9a721dc95e0", "metadata": {}, "source": [ "To use cutpaste, run `model.train_cutpaste` as given below. Optionally, to load a pretrained checkpoint pass the checkpoint file in `initial_checkpoints` to `model.train_cutpaste()` as follows.\n", "```\n", "components = model.train_cutpaste(dataset, output_dir, optim='sgd', epochs=2, freeze_resnet=20,\n", " head_layer=2, cutpaste_type='normal', initial_checkpoints=,\n", " generate_checkpoints=False, precision='float32')\n", "```" ] }, { "cell_type": "code", "execution_count": null, "id": "1b34e029-5235-4593-ab0b-12d27e672461", "metadata": {}, "outputs": [], "source": [ "extract_model = model.train_cutpaste(dataset, output_dir, optim='sgd', epochs=2, freeze_resnet=20, head_layer=2, cutpaste_type='normal',\n", " generate_checkpoints=False, precision='float32')" ] }, { "cell_type": "code", "execution_count": null, "id": "30fc18dd-7d78-4b77-b29b-8895e249cd34", "metadata": {}, "outputs": [], "source": [ "from tqdm import tqdm\n", "from tlt.models.image_anomaly_detection.pytorch_image_anomaly_detection_model import extract_features, pca, get_feature_extraction_model\n", "\n", "layer_name = layer\n", "pool = 'avg'\n", "kernel_size = 2\n", "dataset._dataset.transform = dataset._train_transform\n", "images, labels = dataset.get_batch()\n", "extract_model = get_feature_extraction_model(extract_model, layer_name)\n", "outputs_inner = extract_features(extract_model, images.to('cpu'), layer_name,\n", " pooling=[pool, kernel_size])\n", "data_mats_orig = torch.empty((outputs_inner.shape[1], len(dataset.train_subset))).to('cpu')\n", "\n", "# Feature extraction\n", "with torch.no_grad():\n", " data_idx = 0\n", " num_ims = 0\n", " for images, labels in tqdm(dataset._train_loader):\n", " images, labels = images.to('cpu'), labels.to('cpu')\n", " num_samples = len(labels)\n", " outputs = extract_features(extract_model, images, layer_name, pooling=[pool, kernel_size])\n", " oi = torch.squeeze(outputs)\n", " data_mats_orig[:, data_idx:data_idx + num_samples] = oi.transpose(1, 0)\n", " num_ims += 1\n", " data_idx += num_samples" ] }, { "cell_type": "code", "execution_count": null, "id": "030f5e0e-b7db-41e8-9a13-bcd16d9457c2", "metadata": {}, "outputs": [], "source": [ "# PCA\n", "pca_threshold = 0.99\n", "_pca_mats = pca(data_mats_orig, pca_threshold)" ] }, { "cell_type": "code", "execution_count": null, "id": "6f60192d", "metadata": {}, "outputs": [], "source": [ "threshold, auroc = model.evaluate(dataset, _pca_mats, use_test_set=True)" ] }, { "cell_type": "markdown", "id": "0a877f33", "metadata": {}, "source": [ "## 7. Export" ] }, { "cell_type": "code", "execution_count": null, "id": "abc054ff", "metadata": {}, "outputs": [], "source": [ "model.export(os.path.join(output_dir, 'anomaly'))" ] }, { "cell_type": "markdown", "id": "0947915a", "metadata": {}, "source": [ "## Dataset Citations\n", "\n", "Paul Bergmann, Kilian Batzner, Michael Fauser, David Sattlegger, Carsten Steger: The MVTec Anomaly Detection Dataset: A Comprehensive Real-World Dataset for Unsupervised Anomaly Detection; in: International Journal of Computer Vision 129(4):1038-1059, 2021, DOI: 10.1007/s11263-020-01400-4.\n", "\n", "Paul Bergmann, Michael Fauser, David Sattlegger, Carsten Steger: MVTec AD — A Comprehensive Real-World Dataset for Unsupervised Anomaly Detection; in: IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), 9584-9592, 2019, DOI: 10.1109/CVPR.2019.00982." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.13" } }, "nbformat": 4, "nbformat_minor": 5 }