File size: 23,568 Bytes
a01ef8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3405d28d",
   "metadata": {},
   "source": [
    "# Image Anomaly Detection  with PyTorch using <br>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=<PATH_TO_MODEL_FILE>, 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",
    "<b>IMPORTANT:</b> 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=<PATH_TO_CHECKPOINTS_FILE>,\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=<PATH_TO_CHECKPOINTS_FILE>,\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
}