Env-Aware Anomaly Detection: Ignore Style Changes, Stay True to Content!
Abstract
We introduce a formalization and benchmark for the unsupervised anomaly detection task in the distribution-shift scenario.
Our work builds upon the iWildCam dataset, and, to the best of our knowledge, we are the first to propose such an approach for visual data.
We empirically validate that environment-aware methods perform better in such cases when compared with the basic Empirical Risk Minimization (ERM).
We next propose an extension for generating positive samples for contrastive methods that considers the environment labels when training, improving the ERM baseline score by 8.7%.
Introduction and related work
Identifying and following novelty [31] is an intriguing human ability that could trigger scientific discoveries [21].
Machine learning models that can mimic this behavior and detect novelty when facing unfamiliar situations are vital for fields like video surveillance [15], intrusion detection in cybersecurity [22], manufacturing inspection [30], and many others [40].
Anomaly Detection ( AD ) is an umbrella term [48] for methods whose goal is to identify samples that deviate from an assumed notion of normality.
Normals and anomalies are supposed to come from different distributions.
But how and up to what limit do they differ?
Defining what changes constitute anomalies and what changes should be ignored is essential.
Deep learning methods proved their representation power in multiple fields [13, 36, 37, 10, 16, 11, 7, 47] and were assumed to become invariant to irrelevant aspects under the big data regime.
Yet, recent works proved that these representations are susceptible to unwanted biases [4] and prone to finding shortcuts [14], relying on spurious features while failing to capture relevant aspects of the data.
Consequently, those models exhibit poor performance when dealing with slightly different, out-of-distribution (OOD) settings, where spurious features are no longer informative.
Avoiding spurious correlations is a challenging problem, impossible to solve in the in-distribution (ID) training setup [42].
Recent works [33, 34, 18, 24, 27, 12, 2, 49] tackle this problem by using an informative process that splits the dataset into multiple environments, extracting additional information.
Except for AnoShift [12], which focuses on network traffic data, all those benchmarks and approaches address supervised scenarios.
We follow the same line to enable robust AD and exploit the multi-environments approach in unsupervised anomaly detection from visual data.
Moreover, we formalize the notion of anomaly under the distribution shift paradigm.
To summarize, our main contributions are the following:
• We propose a benchmark for unsupervised anomaly detection in images, focusing on realworld cases, where the input distribution is different in sub-groups of data.
We formally emphasize the differences between anomaly detection and classical (supervised) distribution shift analysis.
• We validate that shallow AD methods can benefit from working on top of embeddings pretrained using environment-aware methods (like Fish, IRM, LISA).
We prove consistent improvements over ERM pretraining over a wide range of AD methods.
• We introduce a way of adjusting the contrastive methods to be aware of multiple environments, making them more robust in out-of-distribution setups.
Empirical validation over MoCo v3, shows an 8.7% increase in ROC-AUC w.r.t.
ERM, on iWildsCam dataset, in the anomaly detection setup.
Generalization facets for Anomaly Detection
Latent factorization of the data It is useful to formalize the data samples x as being determined by two latent factors: Content and Style [32, 46].
The Content should determine the task at hand, i.e., it should be the cause of the desired target.
At the same time, the Style could represent unrelated features spuriously correlated with the target.
Inferring these latent factors is an extremely difficult problem, seen as a goal of representation learning [32].
It is impossible in the unsupervised setting without additional inductive biases, or other information [17, 29] and it is outside our scope.
Instead, we start from a weaker assumption, that we have data in which only the Style is changed.
We aim to use this factorization in AD to highlight directions toward building methods that are robust to irrelevant changes (involving Style) while capable of detecting relevant changes (involving Content).
Environments We call domains or environments [18, 2] sub-groups of the data, each with a different distribution, but all respecting some common basic rules.
Namely, the Content is shared, but Style or relations involving Style change.
Examples of domains include pictures taken indoor vs. outdoor [51], or in different locations [5], real photos vs sketches [25], or images of animals with changing associations in each environments [26].
Our goal is to be robust to the Style differences between different environments while identifying the Content changes as anomalies.
2.1 Out-of-distribution regimes
When dealing with real-world data, the test distributions usually differ from the training ones, encountering changes in Style or/and Content.
We provide next an in-depth characterization of possible scenarios for AD in those regimes, linking them to common methods that work in each category for supervised tasks.
For explicit examples and details, see Appendix A.2.
A ID setting The default paradigm in Machine Learning, both in supervised and unsupervised learning.
Although this is the default paradigm, the usual assumption that train and test data come from the same distribution is very strong and almost never true for real-world datasets [9, 45, 12, 27, 18]. B. Style OOD
Most works that develop methods robust to some (i.e. Style) distribution changes reside in this category [43, 2, 19, 49].
Environments have differences based on Style, but have the same Content and the goal is to learn representations that are invariant across environments.
C. Content OOD
The assumption here is that environments contain changes in distribution that are always relevant (i.e. changes in Content) for the task and should be noticed.
Methods in this category must detect such changes while optionally performing another basic task.
Anomaly, novelty, or OOD detection methods work in this regime [48]. D. Style and Content OOD
Here, environments bring changes in both Content and Style.
We argue that this is the most realistic setting and it is mainly unaddressed in the anomaly detection literature.
An ideal anomaly detection method will only detect Content anomalies, while being robust to Style changes.
Our main analyses and experiments are performed in this setting, showing the blind spots of current approaches and possible ways forward.
We formalize and detail the distribution shifting scenarios in Appendix A.2.
To the best of our knowledge, we are the first to cover this topic for anomaly detection in particular and for unsupervised learning in general.
R a n d o m
E R M
F i s h
I R M
L I S A
E A - M o C o
M o C o
P r e t r a i n e d
M o C o
P r e t r a i n e d
R e s N e t         env-aware unsup
IsoForest INNE
LODA
OCSVM PCA
LOF
KNN KDE
ROC-AUC for multiple Anomaly Detection methods (iWildCam)
R a n d o m
E R M
F i s h
I R M
L I S A
E A - M o C o
M o C o
P r e t r a i n e d
M o C o
P r e t r a i n e d
R e s N e t         env-aware unsup
MEAN AD
Mean ROC-AUC over Anomaly Detection methods (iWildCam)
2.2 Our approach
We are interested in detecting anomalies in the most realistic scenario, D. Style and Content OOD , where both the Style and the Content can change between environments, and our goal is to detect
Content changes, while learning to be robust to Style changes.
Generally, AD methods work on top of pretrained embeddings.
We first show how to adapt envs-aware methods [2, 43, 49] to an unsupervised AD task (using a non-AD task for pretraining).
Next, we introduce our self-supervised environment-aware method: EA-MoCo, for pretraining the AD embeddings.
Proposed setup We propose a pretraining approach for learning env-aware embeddings that takes advantage of the env information in some way or another.
Current methods are using the environment labels in training, to build env-invariance.
Similarly to them, but unlike other AD methods, we use envs in the pretraining phase to learn better representations for the downstream task (anomaly detection in our case).
We empirically prove (Sec. 3) that learning embeddings robust to domain changes (Style) in the pretraining phase improves the overall performance of the downstream AD task.
For a better understanding of the setup, we present a visual representation in Fig.
Supervised non-AD pretraining First, we adapt already existing env-aware solutions for supervised learning ( e .
g .
IRM [2]) to anomaly detection.
For creating the supervised task needed for these methods, one can use additional labels found in the dataset or can create pretext tasks.
In particular, we divide the dataset samples into 3 sets: 2 normal classes and 1 anomalous.
We use the normal ones for modeling a binary classification task.
Please note that the task is supervised to predict one of the two normal classes, not directly supervised for the Anomaly Detection task.
This way, we do not need or use anomaly labels.
We train the env-aware method on this binary classification task to learn embeddings and apply AD methods on top of those learned embeddings.
Fully unsupervised pretraining To overcome the need for supervision, we propose EA-MoCo , an env-aware contrastive learning approach.
Briefly, we train an diffusion based autoencoder [38] over all training envs, and based on the learned representations, we compute distances between all samples.
Next, we define the contrastive learning objective by selecting pairs of samples from different randomly sampled domains which are close to each other, considering our previously defined distances. See Fig.
2 and Appendix A.3 for details.
We employ AD methods on top of our supervised and unsupervised embeddings, proving large improvements when using the env information in pretraining (Sec. 3)
Experimental results
iWildCam dataset Ideally, for testing the robustness of an algorithm in our setup, we would need a dataset with multiple environments annotations, but also with anomalies.
Since there is none tackling
[Table]
t
[Table]
m
[Table]
both aspects [Table] we chose to start with a multi-environment dataset, on top of which we define the Content anomalies in a standard way, as classes unseen at training time [48, 39].
iWildCam [5] is a dataset used for studying robustness at distribution shifts, containing images from various camera traps placed in the wild, exhibiting drastic distribution shifts in image Style ( e .
g .
illumination, background, vegetation).
We present in Appendix A.4 the details for building the AD setup on top of the dataset.
3.1 Environment-aware algorithms in pretraining
We learn image embeddings in several ways, comparing the downstream performance of the AD methods applied in an unsupervised manner on top of them.
As backbone, we use ResNet-18 [16].
a)
Empirical Risk Minimization (ERM [20]) is the main baseline, which we compare against several env-aware methods: b) Fish [43], c) Invariant Risk Minimization (IRM [2]), and d) LISA
As shown in Tab. 1, LISA proves to be the best out of the supervised algos.
Also see that in general, all embeddings learned from env-aware algorithms perform better in the downstream task: content OOD detection (anomaly).
We also pretrained the embeddings using a contrastive, unsupervised solution ( e) MoCo v3 [8]), which proved to be a strong baseline.
Since we noticed before that env-aware capabilities improve the robustness, we add them on top of the contrastive method, as detailed in
Sec. 2.2.
On average, our Env-Aware MoCo perform best, as seen in Fig.
3 and Tab. 1.
3.2 AD methods
For detecting anomalies, we feed the embeddings to a variety of anomaly detectors, covering most of the AD types.
As a) ensemble-based methods, we test IsolationForest [28], INNE [3] and
LODA [35].
For b) linear models , we test the classics: OCSVM [41] and PCA [44].
The delegates for c) proximity-based are LOF [6] and KNN [1], while for d) probabilistic detectors we have
KDE [23].
We use pyod [50] implementations and validated the dataset-related hyper-parameters ( e .
g .
number of trees, neighbours, bins, gamma, standardization).
We detail in Appendix A.1 and will make the code publicly available.
Conclusions
This work tackles the unsupervised anomaly detection task in the Style distribution shift scenario.
First, we formally analyze the task in connection to existing frameworks.
Next, we prove that employing env-aware pretraining methods can boost the performance of shallow AD methods in this setup.
Finally, we propose an env-aware contrastive method, with up to 8.7% improvement on iWildsCam AD setup, over the ERM baseline. Acknowledgments
We thank Razvan Pascanu for guiding us on how to better formalize the problem
A Appendix A.1 AD methods hyper-parameters
We chose for each method (loaded from pyOD library [50]) the proper hyper-parameters for iWildCam, by maximizing the score for the basic (ERM) setup.
Those are the following: "IsoForest":iforest.
IForest(behaviour="new")␣without_scaler "INNE":inne.
INNE(n_estimators=51)␣without_scaler "LODA":loda.
LODA(n_bins=25,␣n_random_cuts=100)␣with_scaler "OCSVM":ocsvm.
OneClassSVM(gamma="auto")␣with_scaler "PCA":pca.
PCA(standardization=
False,␣whiten=
True)␣with_scaler "LOF5":neighbors.
LocalOutlierFactor(n_neighbors=5,␣novelty=
True,
[Table]
A.2 Set-up formalization details
We showcase the different set-ups in which machine learning algorithms are used at present, with respect to the different types of changes these algorithms are designed to capture.
In addition, we proposed a new set-up that, to our knowledge, has never been addressed before, all to be observed in
Tab. 2.
A.3 Env-Aware MoCo algorithm: EA-MoCo
We summarize our proposed env-aware method of anomaly detection in distribution shift scenarios in an easy-to-follow algorithm.
We use only one positive sample per anchor, chosen from a different, X e a samples from x i _ e a - input sample i , from env a e 1 , e 2 , ...
e t - train envs e t +1 , e t +2 , ...
e t + k - test envs
Results: 1) style-robust embeddings X SR ; 2) anomalies prediction Y AD
Step 1.
Compute distances between all samples 1: X AEe 1 .. e t ← train _ autoencoder ( X e 1 ..e t ) // train an autoencoder over all training envs 2: dist i _ e a ,j _ e b ← l 2( x AEi _ e a , x AEj _ e b ) , ∀ x i _ e a ̸ = x j _ e b , a, b ∈ 1 , t // use embeddings for distances //
Step 2.
Contrastive approach based on envs - Moco v 3: x + ← arg min ∀ x j _ eb ∈ X eb ,e a ̸ = e b dist ( x i _ e a , x j _ e b ) // closest, from another domain 4: x − ← { x j _ e a | j ∼ batch i } // usual negative samples, the rest of the batch 5: x SRi _ e a ← train _ contrastive ( x i _ e a , x − , x + ) //SR =
Style-Robust; train similar to MoCov //
Step 3. Downstream task (anomaly detection) 6: ω ∗ ← AD ( X SRe 1 ...e t ) ; // Train AD on the new Style-Robust embeddings 7: Y ADe t +1 ..
e t + k ← ω ∗ X SRe t +1 ..
e t + k ) //
Apply AD on the testset random environment, at the smallest distance defined by the previously trained autoencoder (over all envs), as described in Alg.
We do not further augment the positive sample.
A.4 iWildCam
For building the anomaly detection setup from the existing classification setup in iWildCam, we group the classes in 3 buckets (two for normality - with class label < 125 - and one with the rest, being used as anomalies).
We keep only the domains present in each bucket, with sufficient samples each.
Samples belonging to the normal classes are used in pretraining and AD training.
The test set contains both normal and abnormal samples, but only from envs unseen at training time (out-of-distribution from the Style point of view).
We will make the split publicly available.