HomeVideos

AI Anomaly Detection with PaDiM: A Complete Tutorial

Now Playing

AI Anomaly Detection with PaDiM: A Complete Tutorial

Transcript

541 segments

0:00

In this video, we will have a look at

0:02

how to use different AI methods for

0:05

anomaly detection. We will mainly focus

0:08

on a padding method.

0:10

We'll first see how to detect an anomaly

0:13

by creating a heat map based on the

0:15

Mahalanobis distance.

0:18

Then, we will see how padding works by

0:20

extracting channels from a pre-trained

0:23

CNN.

0:25

Next, we will have a look at some Python

0:27

code for anomaly detection by using the

0:30

anomaly package. And finally, try to

0:33

understand how the image and pixel area

0:36

under the curve is calculated.

0:39

In this video, I will use the MVTec

0:42

dataset that works as a benchmark for

0:45

different anomaly detection methods with

0:48

the focus on industrial applications.

0:52

We'll here focus only on the images of

0:54

capsules.

0:56

For example, suppose that this image

0:59

shows a capsule with good quality from

1:02

the production.

1:04

Whereas, this image shows a capsule with

1:07

bad quality.

1:09

Anomaly localization means that we

1:12

determine where in the image the

1:14

deviation occurs.

1:17

While anomaly detection means that we

1:19

have identified a capsule that deviates

1:23

from the normal case.

1:25

One way we could automatically identify

1:28

bad quality capsules is to train a

1:31

neural network based on images including

1:34

good and bad quality, so that it learns

1:37

to classify such images.

1:40

The problem is that we do not know what

1:42

kind of defect we might observe in the

1:45

future.

1:46

If the following error appears in a

1:49

production which the network has not

1:51

been trained on, the network will not

1:54

know how to classify this image.

1:57

A better alternative is therefore to use

2:00

a so-called one-class model that is

2:03

trained only on normal data so that it

2:06

learns the distribution of capsules with

2:09

good quality. This is called

2:11

unsupervised anomaly detection.

2:14

Once such a model has been trained, it

2:17

can be used to compute an anomaly score

2:20

of new images, which tells how much the

2:23

capsule deviates from the normal.

2:27

A color image consists of three

2:29

channels, one red, one green, and one

2:33

blue channel.

2:34

If you put these channels on top of each

2:37

other, where the three colors are mixed,

2:40

we'll get this image.

2:43

An image consists of pixels, and this

2:46

particular image consists of 1,000 *

2:50

1,000 pixels.

2:53

Each pixel has three values that tell

2:56

the intensity of the red, green, and

2:59

blue channels. These pixel values

3:02

usually span between 0 and 255.

3:06

Let's simplify so that the image

3:08

consists of only 20 pixels.

3:12

A white color in the image is

3:15

represented by high intensity values in

3:18

the red, green, and blue channels.

3:21

A black color is associated with low

3:24

values in the three channels.

3:27

While an orange color is represented by

3:30

a high value in the red channel, but

3:33

relatively low values in the green and

3:35

blue channels.

3:37

Suppose that we have a defect in the

3:39

capsule here.

3:42

Since the color changes from orange to

3:44

white at this location, there will be a

3:47

change in the value of the following

3:49

pixels.

3:51

The pixel values in the blue channel

3:54

will increase to 255,

3:57

which is true also for the green

3:59

channel.

4:00

The values in the red channel will not

4:02

deviate that much because the values in

4:05

the red channel were already high.

4:08

By studying the pixel values, we have

4:11

identified an anomaly in the image.

4:14

Let's say that we will make a scatter

4:16

plot of the given pixel of many images

4:20

with good quality capsules. For example,

4:23

a value of 80 in the green channel and a

4:26

value of 68 in the blue channel will

4:29

result in the following point.

4:32

If you take another image of the same

4:35

pixel location, it may have a value of

4:38

105 in the green channel and a value of

4:41

102 in the blue channel.

4:44

So, this plot shows the distribution of

4:47

values from the blue and green channels

4:50

at the given pixel in the 219 training

4:53

images from capsules with good quality

4:57

in the MVTec data set.

4:59

High intensity values likely come from

5:02

capsules where the pixel includes some

5:06

of the white text, whereas low intensity

5:08

values likely come from images where

5:11

this pixel has an orange color.

5:14

Let's calculate the average intensity of

5:17

the green and blue channels in this

5:19

pixel

5:20

based on the 219 images in the training

5:23

data set.

5:26

Then, we calculate the covariance matrix

5:29

where this value shows how much spread

5:32

there is between the images in this

5:34

pixel in the green channel.

5:37

And this is how much spread there is in

5:39

the blue channel.

5:41

And these values show how much the two

5:43

channels spread together.

5:46

The mean and the covariance matrix of

5:49

the green and blue channels in this

5:51

pixel from the images with capsules of

5:54

good quality can now be used for anomaly

5:57

detection.

5:59

Training a basic anomaly detection model

6:02

simply means that we compute the mean

6:04

and the variance of pixels in the images

6:08

with capsules of good quality.

6:11

Once the model has been trained,

6:14

we can use a new image of a capsule to

6:17

determine if it deviates from the normal

6:19

good quality capsules. We therefore like

6:22

to know if the green and blue channel in

6:25

the given pixel deviates from the values

6:28

of the images with good quality.

6:31

The green and blue values in this pixel

6:34

are 110 and 100.

6:37

Since these pixel values can be seen as

6:40

the distribution of the images with

6:42

capsules of good quality,

6:45

this pixel does not deviate from the

6:48

normality because it's within the

6:50

ellipse.

6:52

To check if this value in this pixel is

6:55

within the cloud of pixel values from

6:57

the images from good quality, we can

7:00

compute the Mahalanobis distance where

7:03

we plug in its coordinates,

7:06

the mean,

7:08

and the inverse of the covariance

7:10

matrix.

7:12

If we do the math, we see that this

7:14

pixel value deviates about 1.6

7:17

Mahalanobis distances from the mean.

7:21

In contrast, this new image has some

7:25

dark pink color in this pixel because

7:28

the pixel value in the green channel is

7:31

here only 50.

7:33

The Mahalanobis distance between this

7:35

point and the mean is 29, which

7:39

indicates that the pixel in this image

7:42

deviates a lot from the corresponding

7:44

pixels in the normal images.

7:47

This calculation can be extended to

7:49

include all three color channels, so

7:52

that we compute the Mahalanobis distance

7:55

in the three-dimensional space.

7:58

Note that if we instead would use the

8:00

Euclidean distance, the distance from

8:03

the center to the two points would be

8:06

about the same. This explains why we use

8:09

the Mahalanobis distance instead of the

8:11

Euclidean distance.

8:13

If you compute the Mahalanobis distance

8:16

between all pixels of the three channels

8:19

in this test image, then we can generate

8:22

the following heat map.

8:25

For example, a blue color means that

8:27

there is a relatively short Mahalanobis

8:30

distance between the following pixel of

8:33

the test image and the average of the

8:36

pixel values in the training images with

8:39

good quality.

8:41

Here we have detected an anomaly because

8:44

the pixel values in this region deviates

8:47

a lot from the training images.

8:50

The Mahalanobis distance in some of

8:52

these pixels are greater than 1,000.

8:57

This is how we can use the Mahalanobis

8:59

distance for anomaly detection. The main

9:02

drawback of this method is that it is

9:05

highly sensitive to colors in the

9:08

pixels.

9:10

For example, the Mahalanobis distance

9:13

will not be able to identify the

9:15

following imprinting error because the

9:17

color in these pixels will be quite

9:20

similar to the colors in the training

9:22

data.

9:23

It is also highly sensitive to the exact

9:26

position of the capsule.

9:30

In addition, it will not identify this

9:32

change in shape because the color in the

9:35

pixels is quite similar to the capsules

9:38

of good quality.

9:40

Although it identifies this area because

9:43

the image has an orange color where the

9:46

white background is visible in the

9:48

training images.

9:51

Note that any dust in the background is

9:54

also indicated in the anomaly map.

9:58

We now have a look at the PaDiM method

10:00

that was published in 2020.

10:04

It actually works very similar to the

10:06

Mahalanobis method.

10:08

During training, one computes the mean

10:11

and the covariance matrix in every

10:13

position in the images with the good

10:16

quality capsules.

10:18

Then one computes the Mahalanobis

10:20

distance between every position in the

10:23

test image and the average of the

10:25

corresponding positions in the training

10:28

data

10:29

to create this heat map.

10:31

The main difference in the PaDiM method

10:34

is that the Mahalanobis distance is not

10:37

computed based on the pixel values in

10:40

the image.

10:42

Instead, it is calculated based on

10:44

channels in the convolutional layers of

10:47

a pre-trained CNN network.

10:50

What you see here is the classic VGG16

10:53

network

10:55

that was trained on the ImageNet

10:57

dataset.

10:59

When VGG16 was trained on the ImageNet

11:02

dataset, it learned how to classify the

11:04

1,000 categories in this dataset such as

11:08

cats, dogs, and cars.

11:11

The early layers in this network have

11:14

learned to identify simple patterns,

11:16

edges, and color contrasts.

11:20

If you plug in this image in this

11:22

network,

11:24

the network will incorrectly predict

11:26

this medical capsule as a rubber eraser

11:29

with 50% probability. This incorrect

11:33

prediction is likely due to the fact

11:35

that the network has not been trained on

11:37

such type of objects.

11:40

Anyway, we'll not use the network to

11:42

predict, so we do not need to include

11:45

this part of the network.

11:47

So, to train our padding model, we plug

11:50

in the training images into the

11:52

pre-trained network based on the weights

11:55

that were optimized on ImageNet data

11:58

set, which means that we do not train

12:00

this network. We just use it to compute

12:03

the feature maps.

12:05

For example, we may extract the first

12:07

four layers from the network,

12:10

which contain the image features of one

12:13

image in the training data set. One

12:16

simple way to upsample a matrix is to

12:19

use the nearest neighbor method,

12:22

where we simply assign the empty

12:24

elements with the value of the closest

12:27

original value.

12:34

Another method is to use the bilinear

12:37

method, which gives a smoother gradient.

12:41

So, once we have doubled the size of

12:43

these feature maps,

12:46

all four layers will have the same size.

12:50

Note that layers three and four have 128

12:54

channels,

12:56

and that layers one and two have 64

12:58

channels each.

13:00

In total, we therefore have 384

13:03

channels.

13:05

In comparison to the previous

13:06

Mahalanobis distance method, where we

13:09

only had three channels,

13:12

we may have several hundred channels,

13:15

depending on which network we use and

13:17

how many layers we extract.

13:20

Since it would be too computationally

13:22

expensive to have that many channels to

13:24

compute the Mahalanobis distance in,

13:27

One method they proposed in the paper

13:31

was to randomly select 100 channels and

13:34

compute the Mahalanobis distance on

13:36

these.

13:38

One of the models they proposed in the

13:40

paper was to use 100 random channels

13:43

from ResNet 18.

13:46

Note that we do not train this network.

13:49

We just use it for feature extraction of

13:52

every image in the training data set.

13:55

So, to train our model, we plug in the

13:58

training images with good quality

14:00

capsules.

14:03

Then, we extract the computed feature

14:05

maps from each image and compute the

14:08

mean and covariance matrix of every

14:10

element in the feature maps for all

14:13

training images.

14:15

The training part therefore only

14:17

involves estimating the normal

14:19

distribution of the values in the

14:22

elements in the channels.

14:25

Once we have trained the model, we can

14:28

plug in a test image and compute the

14:30

Mahalanobis distance for every element

14:33

in the channels.

14:35

They'll produce an anomaly map.

14:38

If the test image deviates from the

14:40

training images with good quality

14:43

capsules, we have identified an anomaly.

14:47

We'll now see how to perform anomaly

14:50

detection by using the Python package

14:53

Anomalyb.

14:55

We first need to download some images,

14:58

and we will here use the MVTec data set.

15:02

In this example, we will only use the

15:04

capsule data set.

15:06

Once you click on this link, you should

15:08

see that the data is being downloaded.

15:13

After you have unzipped the downloaded

15:15

file, you should place the folder

15:18

capsule in an appropriate place on your

15:20

computer. I here place this folder on

15:23

the C AIMVTech.

15:27

In the train folder, we have 219 images

15:31

that show capsules of good quality.

15:34

These are the images that we will train

15:36

the model on.

15:38

The test folder shows different

15:40

categories of bad quality capsules.

15:44

For example, if you look into this

15:46

folder,

15:47

we'll find images that show capsules

15:50

with some defect.

15:52

Note that the test data set also

15:54

includes a folder with images of good

15:56

quality capsules.

15:59

These images are used to compute how

16:01

well the model can discriminate between

16:03

good and bad quality.

16:06

In the folder ground truth,

16:09

you will find the ground truth images

16:11

where an expert has labeled the defects.

16:15

This white region in a masked image

16:19

identifies the defect in this capsule.

16:23

You may install Anomalyb like this.

16:27

After installing Anomalyb, we can import

16:30

the following libraries.

16:33

And define the folder where we have the

16:35

capsule folder.

16:38

We here say that we like to train only

16:40

on the category capsule.

16:43

Next, we define the type of model we

16:45

like to use. We will here use PaDiM,

16:48

which is very fast to train.

16:52

You may also try other models such as

16:55

the PatchCore model.

16:58

This line sets up everything before the

17:00

training.

17:02

Here is where we train the model based

17:04

on the training data set.

17:08

Whereas this line is used to see how

17:10

well the model performs based on the

17:13

test data set and the ground truth

17:15

masks.

17:18

If you run this code, you will get the

17:20

following table. But, note that the

17:22

method includes random components. So,

17:25

you will probably not get the exact same

17:27

values as shown here.

17:30

After you run the code, you should be

17:33

able to see a folder called results in

17:36

your current Python working directory,

17:39

where you should be able to find the

17:41

resulting images

17:43

and your trained model.

17:47

We previously saw that the pixel area

17:49

under the curve was about 0.98.

17:53

We'll now see how such a value is

17:55

calculated.

17:57

This shows the pixel ROC curve for the

18:00

following image in the test data set.

18:03

The area below this curve is about

18:06

0.987.

18:10

To generate this ROC curve, we first

18:13

create an anomaly map of the image in

18:15

the test data set.

18:18

Note that pixels in anomaly map are

18:21

feature map elements.

18:24

From this anomaly map, we compute the

18:26

predicted mask based on a certain

18:29

cutoff.

18:32

The values in the anomaly map have been

18:34

normalized by the maximum Mahalanobis

18:37

distance observed in all maps in the

18:40

test data set. The values in these

18:43

anomaly maps can therefore not be

18:45

greater than one.

18:47

The dark blue color corresponds to

18:50

values around 0.3.

18:53

Whereas green or yellow color correspond

18:56

to values around 0.6.

18:59

And dark red color to values close to

19:02

one.

19:04

So, if you for example use a cutoff

19:06

value of 0.75,

19:08

we can create this predicted mask,

19:11

which can be compared to the ground

19:13

truth mask.

19:15

This means that regions in the anomaly

19:17

map that are greater than 0.75

19:21

will result in a yellow color in the

19:23

predicted mask.

19:26

Whereas values that are less than 0.75

19:29

will get a purple color.

19:32

Now, regions with the yellow color in

19:34

the predicted mask that also have a

19:37

yellow color in a ground truth mask will

19:40

be defined as true positives.

19:43

Whereas elements that have a yellow

19:45

color in the predicted mask but not in a

19:48

ground truth mask will be defined as

19:51

false positives.

19:53

If both elements have a purple color the

19:57

elements are defined as true negatives.

20:01

And if the ground truth has a yellow

20:03

color whereas the predicted mask has a

20:06

purple color

20:07

those elements are defined as false

20:10

negatives.

20:12

The true and false positive rates are

20:15

then calculated based on all pixels for

20:18

a given cutoff.

20:21

For a cutoff of 0.75,

20:23

we get a true positive rate of about

20:26

0.89

20:28

and a false positive rate of about 0.02.

20:33

If we reduce the cutoff to 0.4

20:36

we get the true positive rate of one but

20:39

an increased false positive rate.

20:42

Because the predicted mask has yellow

20:45

color in the corresponding yellow color

20:47

in the ground truth which results in

20:50

almost no false negatives.

20:53

But the predicted mask has a lot of

20:55

yellow color that is not included in the

20:57

ground truth which results in many false

21:00

positives.

21:03

In comparison, a higher cutoff value

21:06

will result in very low false positive

21:08

rate because there are almost no false

21:11

positives,

21:13

but quite many false negatives, which

21:15

will result in a low true positive rate.

21:20

The corresponding F1 score is calculated

21:23

like this.

21:27

The image area under the curve is

21:29

calculated based on good and bad images

21:32

in the test data set.

21:34

Remember that we had one folder in the

21:37

test data set with images showing good

21:40

quality capsules.

21:42

One way to calculate a single score

21:45

for an image is to compute the maximum

21:48

value from the anomaly map.

21:51

For example, this is the maximum value

21:54

in the anomaly map for an image in the

21:56

test data set with a good quality,

21:59

whereas this is the maximum anomaly

22:01

value for an image in the test data set

22:04

that has been defined as bad quality. We

22:07

can see that bad quality capsules

22:10

generally have a higher maximum value

22:13

than capsules with good quality.

22:17

If we use a cut off of about 0.7, we'll

22:20

get a true positive rate of about 0.2

22:23

and a false positive rate of zero

22:26

because we have no false positives with

22:28

this high cut off.

22:30

If we reduce the cut off to 0.5, we'll

22:33

now get a true positive rate of about

22:35

0.7 and a false positive rate of about

22:39

0.1.

22:42

With a cut off of about 0.4, we have a

22:45

false positive rate of 0.4 and a true

22:48

positive rate of one because we have no

22:51

false negatives with such a low cut off.

22:54

We'll now see how to create the

22:56

following images in AnomalyLib.

22:59

We first import the following packages

23:04

and use the predicted function to

23:06

compute the anomaly maps and the

23:08

predicted masks based on all images in

23:12

the test data set.

23:14

The results are stored in different

23:16

batches and we will here have a look at

23:18

the images in the first batch.

23:21

From this batch, we can take an

23:23

arbitrary image

23:26

and save the path to that image

23:30

and create an array of this image.

23:32

Then we do the same for the ground truth

23:34

image.

23:36

Then we extract the tensor that includes

23:39

the values from the anomaly map

23:43

and the predicted mask.

23:45

Finally, we will plot the original

23:47

image,

23:48

the anomaly map,

23:51

the predicted mask,

23:53

and the ground truth mask.

23:56

Note that there is some dust in this

23:58

image,

24:00

which explains where we identify an

24:02

anomaly here.

24:04

Also note that you should be able to

24:06

find a similar figure in the fuller

24:09

results in your current Python working

24:11

directory, which is automatically

24:14

generated once you have trained and

24:16

tested your model.

24:18

This was the end of this basic video

24:20

about anomaly detection. Thanks for

24:22

watching.

Interactive Summary

This video provides an introduction to unsupervised anomaly detection, specifically focusing on industrial applications using the MVTec dataset. It covers the core concept of using Mahalanobis distance to measure how much new data deviates from a model trained solely on 'normal' (good quality) data. The tutorial transitions from a basic pixel-based Mahalanobis approach to the more robust PaDiM method, which utilizes feature maps from pre-trained convolutional neural networks (CNNs) to overcome limitations related to color and object alignment. Finally, the video demonstrates a practical implementation using the AnomalyLib Python package, detailing how to evaluate performance through ROC curves, pixel-level classification, and anomaly map generation.

Suggested questions

4 ready-made prompts