F AST A DAPTIVE A NOMALY D ETECTION
Anonymous authors
Paper under double-blind review
A BSTRACT
The ability to detect anomaly has long been recognized as an inherent human ability, yet to date, practical AI solutions to mimic such capability have been lacking.
This lack of progress can be attributed to several factors.
To begin with, the distribution of “abnormalities” is intractable.
Anything outside of a given normal population is by deﬁnition an anomaly.
This explains why a large volume of work in this area has been dedicated to modeling the normal distribution of a given task followed by detecting deviations from it.
This direction is however unsatisfying as it would require modeling the normal distribution of every task that comes along, which includes tedious data collection.
In this paper, we report our work aiming to handle these issues.
To deal with the intractability of abnormal distribution, we leverage Energy Based Model (EBM).
EBMs learn to associates low energies to correct values and higher energies to incorrect values.
As its core, the EBM employs Langevin Dynamics (LD) in generating these incorrect samples based on an iterative optimization procedure, alleviating the intractable problem of modeling the world of anomalies.
Then, in order to avoid training an anomaly detector for every task, we utilize an adaptive sparse coding layer.
Our intention is to design a plug and play feature that can be used to quickly update what is normal during inference time.
Lastly, to avoid tedious data collection, this mentioned update of the sparse coding layer needs to be achievable with just a few shots.
Here, we employ a meta learning scheme that simulates such a few shot setting during training.
We support our ﬁndings with strong empirical evidence.
I NTRODUCTION
Anomaly detection is an important area of study in the ﬁeld of artiﬁcial intelligence.
It has found utility in computer vision applications such as industrial inspection (Bergmann et al., 2019) and video surveillance (Liu et al., 2018;
Zhao et al., 2011; Nguyen & Meunier, 2019), in the context of abuse prevention such as misinformation, fraud and network intrusion detection (Zhang et al., 2019; Bolton & Hand, 2002; Mukherjee et al., 1994), and others such as system health monitoring and fault detection (Bao et al., 2019; Purarjomandlangrudi et al., 2014).
In this paper, we propose an approach for detecting anomaly in images, where we have carefully designed steps to handle some of the bigger issues that have prevented the deployment of image anomaly detection in the real-world.
Image anomaly detection can generally be deﬁned as the identiﬁcation of abnormalities in a given image.
An exact deﬁnition of abnormality in this case is elusive because abnormality can be derived from any unknown distribution outside of a normal population.
Many studies have hence focused on modeling the normal population instead of learning irregularities, where the goal is to capture the shared concept among all of the normal data as one or several reference models.
This process usually will require investing signiﬁcant efforts in curating a large enough set of normal samples for each task , after which anomaly is detected as deviations from the reference model(s) (An & Cho, 2015; Xu et al., 2018).
Recent work from (Sheynin et al., 2021) provides algorithms that utilize only a few normal samples to train models from scratch.
However, the models still have to be provisioned for each new task, which requires considerable human efforts and expertise, and thus lack the fast deployment criterion that is often time critical for real-world applications.
In view of these challenges, our goals for this work are threefold.
We are interested in designing an anomaly detection system that is capable of: (G1) modeling the normal population while at the same time has a principled approach towards modeling the abnormalities; (G2) quickly adapting to a new task at inference time; and (G3) requiring only a few normal shots to update itself to the new task at hand.
For (G1), we introduce the class of Energy Based Model (EBM), which is an important family of generative models (Zhao et al., 2016; Du & Mordatch, 2019; Xie et al., 2016).
EBMs have been shown to demonstrate superior capability on modeling data density and localizing anomaly (Genc et al., 2021).
For our purpose, the EBM we adopted learn to assign low energy to normal samples but high energy to abnormal samples.
More importantly, the abnormal samples are generated with a procedure known as Langevin Dynamics (LD) (Welling & Teh, 2011), which, in its original form, starts with a noise image (see App.
Fig C) and gradually samples from the distribution along the direction of lower energy.
This lends itself gracefully to utilizing the generated intermediate samples as negative/abnormal.
The LD procedure is then coupled with a contrastive divergence loss (Hinton, 2002) that aims to maximize the energy differences between the normal and abnormal samples.
To achieve (G2), we propose an adaptive sparse coding layer that is attached to the deep feature extractor in the EBM.
The deep features are projected into a set of feature vectors along the spatial axes, after which each vector is forwarded to the sparse coding layer, where the dictionary is constructed with the features of a few normal samples of the given task.
In essence, the input representation has been decomposed into a linear combination of normal features with the sparsity constraint imposed.
The ﬁnal energy score is measured by the distance between the original and the reconstructed features (after the sparse coding layer).
Under this scheme, the dictionary for a particular task is not obtained by learning, but instead is constructed by the feature representations of a few normal samples during inference.
As a result, this simple “plug-and-play” trick allows the model to be adapted to novel tasks promptly without re-training.
Further, we expect that the dictionary, which is formed by normal features, will not be able to explain the abnormal samples well, causing relatively high reconstruction error that lends itself for subsequent detection.
As a bonus, a backward pass from the reconstruction error to the image is also additionally useful for localizing the abnormal regions.
Towards (G3), we utilize meta learning (Vilalta & Drissi, 2002; Finn et al., 2017) to simulate the scenario of being given a new task with a few normal shots to update the dictionary, followed by training the EBM.
This is accomplished by episodic training, where in each episode the model is adapted to a held back task that is given a few normal samples.
To accelerate the EBM training, we introduce “learning from inpainting”, a simple yet effective strategy for synthesizing hard abnormal samples quicker by starting the LD procedure with a synthesized image that is simply a normal sample with a noise patch injected as opposed to a noise image that is traditionally what is used.
We show the proposed framework is able to efﬁciently adapt to a novel task (e.g., a new object category or scenes from a new camera) with a few normal samples on both industrial inspection and video surveillance tasks.
We provide both qualitative and quantitative results to demonstrate that our method outperforms other adaptive frameworks and is comparable to methods that rely on large amount of normal samples.
B ACKGROUNDS
We brieﬂy introduce two key ingredients of the proposed method: EBMs and sparse coding.
Energy-based Model In EBMs
, the goal is to learn an energy function E θ ( x ) : R d → R which parametrizes the data density p θ ( x ) as:
[Equation]
where θ is the parameter of the energy function and Z θ = (cid:82) x exp( − E θ ( x )) is the partition function.
Approximating the true data distribution p data ( x ) is equivalent to minimizing the expected negative log-likelihood function over the data distribution, deﬁned by the loss function:
[Equation]
As the computation of L ML involves an intractable term Z θ , the common practice is to represent the gradient of L ML as,
[Equation]
This objective is commonly referred to as the contrastive divergence (Hinton, 2002), which decreases the energy of positive data samples x + from the true distribution (normal samples in our use case) and increases the energy of negative samples x − from the model p θ (synthesized abnormal samples).
In practice, the synthesized negative samples are achieved through Langevin dynamics (Welling &
Teh, 2011), which samples along the direction of decreasing energy score, typically starting from a given noise image:
[Equation]
where β is the step size.
The synthesizing ability of EBMs enables generating abnormal samples to help in learning a more accurate data density, and is often touted as the one of the advantages of using an EBM.
Sparse coding.
Approximating a signal z ∈ R d with the sparse linear combination over a dictionary
D ∈ R d × k can be expressed as:
[Equation]
where α is the sparse coefﬁcients, with its sparsity ( l 1 norm) and λ is the weight of the sparsity constraint.
D α is a sparse approximation to the original signal z .
In practice, ﬁnding the dictionary atoms and the sparse coefﬁcients is usually formulated as an optimization problem.
In this paper, we adopt Iterative Soft Thresholding Continuation (ISTC)
(Jiao et al., 2017) to convert this optimization problem into linear operations with a non-linear shrinkage function, which allows sparse coding to be seamlessly integrated into the deep neural networks.
To compute a sparse coefﬁcient α , ISTC performs iterations of gradient steps on reconstruction ||
z − D
α
|| 2 and a proximal projection step to increase coefﬁcient sparsity.
Formally, initializing the coefﬁcients at the ﬁrst step α 0 with all zeros, each step of ISTC reﬁnes the sparse code with descending values of λ from λ max to λ (cid:63) : each step of ISTC is expressed as:
[Equation]
where σ ( · , · ) here is a shrinkage function that truncates small values (lower than λ ) of the coefﬁcients to 0 to enforce sparsity, and can be easily implemented by a customized ReLU activation function:
[Equation]
P ROPOSED M ETHOD
The objective of our proposed method, when given an input image or video frame, is to output an anomaly score indicating how likely this input deviates from the normal, and additionally, a pixel map grounding abnormal regions.
In this section, we describe the proposed fast adaptive anomaly detection framework in details.
In Section 3.1, we introduce the adaptive EBM which consists of a deep feature extractor followed by an adaptive sparse coding layer.
From there, we further show that utilizing larger receptive ﬁeld in the sparse coding could improve training robustness (Section 3.1.1), and applying smoothed shrinkage functions could help speed up convergence (Section 3.1.2).
In Section 3.2, we describe the episodic training regime on various anomaly detection tasks that mimics few-shot adaptation in the meta-testing stage while learning common knowledge across tasks.
Finally, Instead of synthesizing negative samples (anomaly) directly from noise, we introduce a simple but effective “learning from inpainting” operation to accelerate the training in Section 3.3.
3. A DAPTIVE E NERGY - BASED M ODEL
An EBM is a form of generative model and it is widely used for modeling data density and sampling.
While there has been recent work (Genc et al., 2021) applying EBM to anomaly detection, it still requires re-training for each new task.
To efﬁciently adapt the EBM to novel tasks, we introduce an adaptive sparse coding layer which is conditioned on the dictionary constructed by the features of normal samples.
Speciﬁcally, as illustrated in Fig 1, given an input image, x ∈ R 3 × h × w , we ﬁrst obtain the corresponding feature z ∈ R d × h (cid:48) × w (cid:48) from the deep feature extractor Ψ with parameters θ , so that z = Ψ ( x ; θ ) .
All feature vectors along spatial axes of z are then sparsely decomposed through the sparse coding layer over a task-speciﬁc dictionary D ∈ R d × Kh (cid:48) w (cid:48) , which contains the features of K normal samples of the current task as shown in the Fig 1(a).
Each feature vector
[Figure]
Sparse coding (b)
[Figure] [Figure]
d×h′×w′
K× …
Reshape d×Kh !
w′
[Equation]
In effect, Eqn. 8 depicts a conditional EBM, which is conditioned on the task-speciﬁc D formed by normal features.
In the following sections, we will discuss how to make the training of this adaptive structure more robust.
S PARSE C ODING WITH R ECEPTIVE F IELD .
As discussed in Section 3.1, the input feature z is represented as h (cid:48) × w (cid:48) of d -dim feature vectors and they are treated independently while passing through the sparse coding layer.
The region of the input image that affects one feature vector is determined by the receptive ﬁeld of the feature extractor.
The trade-off is that a small receptive ﬁeld may not capture enough contextual information, while applying a large receptive ﬁeld would make feature maps spatially coarse and make it hard to spot small anomaly regions.
To solve this dilemma, instead of carefully tuning the receptive ﬁeld of each layer of the feature extractor, we introduce a simple yet effective technique of applying the receptive ﬁeld on the sparse coding layer.
Speciﬁcally, as Fig 2 shows, rather than performing sparse coding to each individual d-dim feature vectors, we apply it on d × l × l volumes centered around each feature vector, where l is the receptive ﬁeld.
This is equivalent to applying a l × l , sliding window on spatial axes of the feature map and can be easily implemented by image to column ( Im2Col ) operation.
Then we ﬂatten the feature volumes into dl 2 -dim vectors and adjust the shape of the dictionary accordingly.
In this way, we are able to capture contextual information without needing to carefully tune the architecture of the feature extractor and we show in the later experiments that this technique improves the robustness of the network on different types of objects.
3.1. S HRINKAGE F UNCTION
The effectiveness of training the EBM for localizing anomaly regions heavily depends on the gradient propagation from later to earlier layers.
It is shown in (Du et al., 2021) that smooth activation functions like Swish Ramachandran et al.
(2017) could be beneﬁcial here.
Notably, the gradients of
[Figure] [Figure]
the dictionary D are determined by the sparse coding coefﬁcients α as shown in Eqn. 6.
However, the sparsity constraint of α would turn off the gradient computation of many elements in D and this could be detrimental during the early stage of the training.
To alleviate the sparse gradient issue, we replace the RELU-like shrinkage function in Eqn.
7 with its smoothed counterparts by introducing the Sigmoid based shrinkage functions (SigShrink).
The SigShink is originally proposed for non-parametric signal estimation in Atto et al.
(2008), and can be deﬁned as:
[Equation]
where τ is the hyperparameter of smoothness.
We present visualizations of the hard shrinkage function Eqn. 7 and SigShrink with different values of τ in Fig 3.
Comparing to the hard shrinkage function which truncates small values into zeros, the SigShrink with a large τ can sharply force small values to near-zeros.
Therefore, the SigShrink will guarantee non-zero gradients everywhere.
3. E PISODIC T RAINING
To train the proposed adaptive EBM, we perform episodic training that is widely adopted by metalearning based few-shot learning tasks Finn et al.
; Snell et al.
Following the terminology of few-shot learning, in each training episode, the model is adapted and tested with a task sampled from the underlying task distribution.
Speciﬁcally, the model is adapted to a support set of the given task, then a query set with ground truth labels is applied to evaluate the adaptation, which is used to update the model parameters accordingly.
As shown in Fig 4, the support set contains K normal samples { x k } Kk =1 of the current task, where K is usually a small number.
The feature representations z k = Ψ ( x k ; θ ) of these normal samples are plugged into the dictionary D i ∈ R d × Kh (cid:48) w (cid:48) corresponding to the i -th task during the i -th episode to adapt the dictionary to the normal samples of the task.
After that, the adapted model is measured by a query set consisting of M normal samples { ˆ x m } Mm =1 and M abnormal samples { ˆ x (cid:48) m } Mm =1 .
Note that there is no actual abnormal samples given during training, instead, they are iteratively sampled from the EBM and we will discuss the initialization and sampling of these synthetic samples in details in Section 3.3.
Recall that the training of EBM with contrastive divergence described in Eqn.
3 requires the estimation of energy scores of both positive samples from the true data distribution and negative samples sampled from the model distribution.
The positive energy can be estimated empirically with normal samples from the query set.
The negative energy can be estimated by performing the MCMC-based (Markov Chain Monte
Carlo) sampling technique (Neal et al., 2011; Welling & Teh, 2011), typically Langevin Dynamics as described in Eqn. 4.
Denoting the output of Langevin dynamics (sampled abnormal samples) with the initialization ˆ x (cid:48)
m as LD (ˆ x (cid:48) m ) , we now have the empirical estimation of the contrastive divergence of the i -th episode as:
[Equation]
With the energy score equivalent to the feature reconstruction error in Eqn. 8, minimizing L cd encourages normal features to be well-reconstructed by a sparse linear combination of dictionary atoms while the features from abnormal samples tend to produce relatively higher reconstruction errors so that they can be easily spotted.
𝑒𝑝𝑖𝑠𝑜𝑑𝑒 i … 𝑒𝑝𝑖𝑠𝑜𝑑𝑒 n
[Figure]
𝑒𝑝𝑖𝑠𝑜𝑑𝑒 n-
[Figure]
3. S YNTHESIZING N EGATIVE S AMPLES
Typical EBM training with contrastive divergence conducts negative sampling from the modeled density using techniques such as Langevin Dynamics, which applies gradient descent to a noise initialization (App.
Fig C) with small step size and large number of steps Du & Mordatch (2019).
Such negative sampling steps can be costly and we argue that it is unnecessary in our case.
Instead, we introduce a new strategy of “learning by inpainting”.
Starting from a positive query sample ˆ x m , we synthesize the corresponding negative sample ˆ x (cid:48) m by randomly placing a small uniform noise patch on the image.
The Langevin Dynamics procedure is then initialized with the resulting image instead of a noise image.
As the Langevin Dynamics proceeds, synthesized abnormal samples LD (ˆ x (cid:48) m ) are inpainted along the direction of “normal”, ˆ x m , and we introduce the following reconstruction loss:
[Equation]
The gradient map from L rec reveals anomaly regions, which helps with localization.
We show in
Fig 4(a) that, starting from a synthesized abnormal sample, only 5 steps of Langevin dynamic would be sufﬁcient to make it visually close to the corresponding normal sample during training, serving as “hard negatives” that further facilitates the learning.
The ﬁnal loss of the episodic training is simply:
[Equation]
(12) where η 0 and η 1 are hyperparameters balancing two loss terms.
R ELATED W ORK 4. A NOMALY D ETECTION
Sparse coding.
Early efforts on adopting sparse coding in anomaly detection are based on optimization (with L1 penalty)
(Lu et al., 2013; Zhao et al., 2011).
Recent advances on iterative sparse thresholding algorithms (Daubechies et al., 2004; Jiao et al., 2017) allow seamless integration of online sparse coding with deep neural networks, and (Luo et al., 2017) formulates the sparse coding as stack RNNs for video anomaly detection.
Generative models.
Generative models are widely utilized in anomaly detection due to the capability in modeling the density of desired data distribution.
Early efforts on variational autoencoders (VAE) based methods (An & Cho, 2015; Xu et al., 2018) are arguably having hard time calibrating uncertainties in novel samples (Nalisnick et al., 2018), accurately localizing abnormal regions through reconstruction errors (Dehaene et al., 2020).
Recent efforts have explored variant generative architectures like energy-based models (EBM) (Genc et al., 2021), GANs (Sheynin et al., 2021), and combining VAE with EBM (Dehaene et al., 2020).
Various methods also exploit intra-image structures (Cohen & Hoshen, 2020; Bergmann et al., 2018), cross-frame consistency (Lu et al., 2019), and motion-appearance consistency in videos (Nguyen & Meunier, 2019) while detecting anomaly. [Figure] [Figure] [Table]
[Figure]
[Table] [Figure] [Table] [Figure]
[Table]
4. F EW - SHOT L EARNING
Few-shot learning is extensively explored in classiﬁcation tasks.
Proposed methods are based on optimization (Finn et al., 2017; Rusu et al., 2019; Finn et al., 2018; Yoon et al., 2018;
Larochelle, 2016), learning metric (Snell et al., 2017; Vinyals et al., 2016) and parameter prediction (Gordon et al., 2018; Qiao et al., 2018; Gidaris & Komodakis, 2019).
These technologies are further applied in other tasks like image generation (Clouˆatre & Demers, 2019; Liu et al., 2019) and out-ofdistribution detection (Sehwag et al., 2021).
E XPERIMENTS
In this section, we conduct evaluation on the industrial inspection task with the benchmark MVTecAD dataset Bergmann et al.
(Section 5.1).
Even though our proposed framework is imagebased, we further demonstrate it’s efﬁcacy on the video anomaly detection task in Section 5.2.
In
Section 5.3, we show ablations and insights relating to the adaptive sparse coding components.
We also show additional ablations on robustness to pose variations (e.g. rotation) while applying fewshot adaptation (App. B.1) and comparing with naive background subtraction to detect anomaly (App. B.2).We provide implementation details in App. A.
I NDUSTRIAL I NSPECTION
The goal of this anomaly detection task is to predict whether a manufactured component contains any defects.
The MVTec-AD dataset includes 15 categories of object.
To demonstrate the fast adaptation capability of the proposed method, we adopt a leave-one-out training strategy.
Speciﬁcally, samples of each target category are reserved for testing only, and the episodic training is performed on the remaining categories.
During the training stage, the model will not see any samples from the target category.
During testing, we ﬁrst adapt the model to the target category with 10 randomly selected
[Figure]
[Table]
normal samples , then measure the performance with the entire testing set.
We run the test 5 times, each time the model is adapted to random sets of 10 normal samples from the target category.
The ﬁnal result is the average of the 5 runs.
Following common practice (Bergmann et al., 2019; Liu et al., 2020), we report the performance of pixel-wise anomaly localization with AUC-ROC and mIoU (mean intersection over union).
IoU is the area of overlap between the predicted map and the ground truth divided by the area of union between these two.
To the best of our knowledge, no existing methods feature fast adaptation like ours.
We ﬁrst show the performance of fully supervised methods, which train each category with normal samples from scratch, as the “upper-bounds”.
Speciﬁcally, (Bergmann et al., 2018; 2019) trains auto-encoders (AE) on massive number of normal samples and measure the reconstruction errors during the inference; AnoGAN (Schlegl et al., 2017) adopts a generative adversarial network (GAN) to learn a manifold of normal; VE-VAE (Liu et al., 2020) presents a visually explainable variational autoencode through gradient-based attention.
Furthermore, we create a strong baseline by applying model-agnostic meta-learning (Finn et al., 2017) on an AE (denoted as MAML-AE, detailed in App.
Sec. A.3).
Numerical results of pixel-wise anomaly localization are in Table 1.
Note that all results of our methods are obtained without any data augmentation .
Our proposed method outperforms MAML-AE by a large margin and is competitive with the “upper-bounds”.
We show the localized anomaly regions from our method in Fig 5.
Additional visualizations are in the App.
Fig A.
5. V IDEO S URVEILLANCE
In video anomaly detection, a common goal is to detect abnormal events captured by surveillance cameras (e.g., a motorcycle on the sidewalk).
A model trained on videos from one camera might not generalize well on other cameras due to different locations / mounting heights / lightning conditions, and it is not feasible to train one model for every new camera in practice.
The ability to quickly adapt to new scenes is a signiﬁcant contribution to the task of video surveillance.
We are only aware of the work in (Lu et al., 2020)
(r-GAN) that has such adaptation capability.
Speciﬁcally, the model adapts to a new scene using gradient descent with several beginning frames of a query video, after which a GAN is applied to generate future frames.
Anomaly is then detected via the discrepancy between predicted future frames and the original frames.
We follow the same evaluation regime as r-GAN by training with normal samples in all 13 scenes from SH-Tech Liu et al.
and testing on UCSD Pedestrian 1, UCSD Pedestrian 2 (Mahadevan et al., 2010), and
CUHK Avenue Lu et al.
Note that since our method is image-based, it predicts the video frames independently without leveraging any temporal information as in r-GAN.
[Figure]
[Figure]
[Table]
We report both mIoU ( [Figure]
[Table]
In each episode we adapt our model with a support set containing a few normal frames randomly sampled from the target scenes.
In Table we compare our method against r-GAN pre-trained on
SH-Tech only (r-GAN Pre-train), ﬁne-tuned on target datasets (r-GAN Fine-tune), and with one step gradient descent with meta-learning (r-GAN MAML).
We also show the performance of MAML-AE as a baseline for image-based meta-learning method.
In the last section of Table 2, we present intradataset results as well by training with 6 scenes of SH-Tech and testing on remaining 7.
We follow common evaluation protocol and measure the frame-level AUC-ROC.
Without leveraging temporal information and performing re-training (gradient descent), our method achieves comparable results to r-GAN MAML and outperforms image-based meta-learning method by a large margin.
5. A BLATION S TUDIES
Sparse coding receptive ﬁelds.
To evaluate the effectiveness of using large receptive ﬁelds in the sparse coding layer, we conduct additional experiments on the MVTec-AD dataset, and selectrepresentative categories with different levels of difﬁculties to present the comparisons with l =and l = 3 (Sec. 3.1.1) in Table 3.
Sparse coding with large receptive ﬁeld clearly beneﬁts more complex structural objects (hazelnut, cable, and capsule), while the improvements are limited for the texture objects (leather and grid), where contextual regularization is intuitively less important.
Shrinkage functions.
To show the beneﬁts of smooth shrinkage function, we plot the loss curves of models trained with smooth SigShrink (Eqn. 9) and non-smooth RELU-like shrinkage (Eqn. 7) functions in Fig 7.
The model with smooth shrinkage function converges notably faster in the early training stage and achieves lower loss.
Sparsity constraint.
As discussed in Section 3.1, we impose sparsity constraint to the feature decomposition in the adaptive sparse coding layer, in order to prevent abnormal features from being well-approximated by the linear combinations of normal features, so that the reconstruction errors are effective for detecting anomaly.
To validate this, we conduct experiments by removing the shrinkage function σ in the sparse coding stage (Eqn. 6).
We show comparison in Table 4 with mIoU, AUC-ROC, and the difference of averaged reconstruction errors between abnormal and normal samples.
Without sparsity, the performance drops dramatically, and reconstruction errors of normal and abnormal samples become closer.
C ONCLUSION
In this paper, we introduced a novel framework for anomaly detection and localization that allows fast adaptation to new tasks.
We formulated our model as an energy based model with an adaptive sparse coding layer, of which the dictionary is directly formed by normal features of a target task.
We adopted episodic meta-learning to extract common knowledge across tasks, which has the effect of enabling few shots adaptation.
We further introduced smooth shrinkage functions, sparse coding with large receptive ﬁelds, and learning by inpainting to improve and accelerate the EBM training.
It’s worthy to note that when evaluating our method’s performance on industrial inspection and video anomaly detection, our method is comparable and even boasts better performance than methods trained with a large amount of normal samples.
Through this work, we hope to have made a signiﬁcant contribution to the important problem of anomaly detection by shedding light on our ﬁndings that anomaly detection can indeed be generalized to new tasks.
A PPENDIX A I MPLEMENTATION D ETAILS
We adopt a residual network (ResNet) He et al.
(2016) based feature extractor, with ELU as the activation function.
Following (Du et al., 2021)
[Table]
we adopt Group Normalization for better stability of the network.
The detailed network construction is shown in Table A
[Table]
A. I NDUSTRIAL I NSPECTION
We adopt the “leave-one-out” training strategy for obtaining the results on each of the categories of
MVTec-AD.
All experiments are performed with the same settings and hyperparameters.
We resize all images to 128 × 128 , and do not perform any data augmentation.
We adopt a simple reducedsized ResNet as the feature extractor as shown in Table A.
Following (Du et al., 2021), we adopt group normalization (denoted as GroupNorm) instead of batch normalization, and use Exponential
Linear Unit (ELU) as the activation function.
We empirically observed that using Tanh as the ﬁnal activation function can remarkably improve the numerical stability of the sparse coding stage as the magnitude of the feature values is effectively bounded by the ﬁnal activation function.
We adopt Adam as the optimizer, with a consistent learning rate of 1e-4.
We do not apply any net regularization methods like dropout or weight decay in training.
The weights of reconstruction ηand contrastive divergence η 1 are set to 1.0 and 0.25, respectively.
Each training batch contains 4 randomly sampled training tasks with 10 query ( M = 10 ) for each task.
All training can be conducted on a single NVIDIA Tesla A100 GPU.
We perform 8 steps of sparse coding in the adaptive sparse coding layer, with an initial λ max = 0 .and
a ﬁnal λ (cid:63) = 0 .
We perform 5 steps of Langevin dynamics with a step size of β = 1 .to synthesize negative samples, which we show in the examples of Figure 4 and Figure C to be sufﬁcient for producing hard negative samples.
A. V IDEO A NOMALY D ETECTION
We resize each frame to 240 × 320 .
No data augmentation is performed.
All other hyperparameters equal to those applied in industrial inspection experiments.
A. MAML-AE
We adopt a full-convolutional auto-encoder network to construct the MAML-AE.
A 10 layer ResNet (He et al., 2016) as the encoder, and consecutive transpose-convolutional layers with batch normal- ization and RELU activation function as the decoder to recover the feature resolution.
The hyperparameters of the episodic training of MAML AE are exactly the same with those of our methods.
We perform 5 steps of gradient descent as the inner-loop adaption.
We directly use the energy score in (Eqn.
8) as the anomaly score.
When evaluating AUC-ROC and mIoU, we obtain the normalized energy score for each sample by directly performing an uniformed normalization to the scores of all samples in test set.
A. I NITIALIZING N EGATIVE S AMPLE
In the synthesis of negative samples, we randomly place at most three random patches to each normal image.
Each patch is created by one of the following:
• Random uniform: A random patch with the values of each pixel sampled from a uniform distribution.
The minimum and maximum values of the uniform distribution is equal to those of the pixel values of the images.
• Random consistent: A random patch with consistent pixel values sampled from a uniform distribution.
The minimum and maximum values of the uniform distribution is equal to those of the pixel values of the images.
• Random copy-paste
A random patch randomly cropped from the same image.
• Random blurring: Applying Gaussian blurring to a random patch of the normal image.
Denoting U ( a, b ) as an uniform distribution with minimum and maximum values of a and b , respectively, the relative size of the random patch w.r.t.
the original image is randomly sampled from
U (0 . 0025 , 0 . 025) , and the aspect ratio is randomly sampled from U (0 . 01 , 100 . 0) .
See Fig.
B for illustrations of synthesized negative samples and the corresponding generative sequences of Langevin dynamics.
B A DDITIONAL ABLATIONS B. R OBUSTNESS TO P OSE V ARIATIONS
To validate the robustness of our method to pose variations, we perform additional experiments with pose variations and provide the quantitative comparisons in Table
B. We report results by performing random ± 90 o rotation to samples during testing stage when adapting the trained model to novel categories.
We observe that the textures categories (leather and grid) are robust to any pose variations in both the query and support samples.
For the hazelnut category, where there are intrinsically signiﬁcant pose variations across samples, performing any new rotations does not inﬂuence the results.
On the other hand, for the pill category, where all samples are aligned horizontally (see examples in Appendix, Figure A), performing rotation to only query samples results in performance drop.
Performing rotation to both query and support samples help to recover the performance.
The above results suggest the robustness of our methods under the condition of sufﬁcient sample diversity in the support set.
[Table]
Image differencing and its variances are an intuitive approach for detecting image anomaly.
We perform image differencing and background subtraction on the industrial inspection and video anomaly detection task, respectively, and report performance in Table C.
Our method demonstrates clear advantages.
[Table]
B
[Table]
While it is a common practice among machine learning practitioners to assume clean training data
[Table] this may not be true in real world applications. In this section [Table]
we evaluate the robustness of our method against contaminated training data by inserting certain amount of abnormal samples.
As shown in Table D
[Table]
we progressively contaminate the normal training data by increasing the amount of abnormal data from 1% to 10% .
Our proposed method is in general robust to data contamination, where contamination under 5 % only decreases the performance slightly.
The network is still able to perform decently in the extreme case of 10% contamination.
[Table]
B. L EVERAGING T EMPORAL I NFORMATION
An EBM is agnostic to the underlying backbone network architecture, therefore it is straightforward to incorporate temporal information into the image-based anomaly detection framework described in
Section 5.2.
We replace the 2D convolutions in the ﬁrst four layers with 3D convolutions, and have the model accepts a 5-frame input instead.
Without heavy tuning, we report 5-shot performance on both ’1 frame’ (original, without temporal) and ’5 frames’ (with temporal) in Table
E.
The results show that when temporal information is added, it leads to further improvements.
[Table]
C Q UALITATIVE R ESULTS
We present in Figure 1 additional anomaly localization results of categories with different anomalies in the MVTec-AD dataset.
D A DDITIONAL F IGURES
Common practice of sampling from EBMs is computationally costly, requiring as many as 50 steps of Langevin Dynamics when initialized with full noise, instead of a synthesized negative sample as shown in Fig.
B. Some examples are provided in Fig.
C.
Input
GT
Prediction
Input
GT
Prediction
Input
GT
Prediction
[Figure]