Anomaly Detection by Context Contrasting

Alain Ryser, Thomas M. Sutter, Alexander Marx, Julia E Vogt · Submission to ICLR 2025 · Rejected

TL;DR

Existing self-supervised anomaly detection methods often rely on simulating artificial anomalies (like image rotations) or leveraging massive pretraining datasets—assumptions that fail in high-stakes domains where anomalies are unpredictable. $\text{CON}_2$ (Context Contrasting) learns structured, dual-perspective representations of normal data by contrasting different contexts (e.g., flipped or inverted views) while strictly aligning their internal content structure. When evaluated at test time, anomalous samples violate these learned invariances and are reliably flagged without ever needing synthetic outliers during training.

What Problem Does This Paper Address?

In high-stakes visual inspection settings like medical diagnostics or industrial monitoring, the vast majority of available data is "normal" (e.g., scans from healthy patients). Detecting anomalies is fundamentally an unsupervised or one-class problem because potential abnormalities can stem from countless rare diseases or novel defects that cannot be anticipated in advance.

Recent state-of-the-art anomaly detection frameworks often construct heuristic synthetic anomalies (such as rotated images) or rely on outlier exposure via foundation models like CLIP. However, foundation models often struggle on specialized data distributions, and synthetic anomalies rarely resemble real-world anomalies. The authors ask: Can we build a discriminative representation space by modeling the invariances and structure of normal data alone, without making any assumptions about what anomalies look like?

Methods

The core of $\text{CON}_2$ is learning context-specific yet content-aligned representations:

  1. Context Augmentations: The method identifies transformations $t_C$ that fulfill two properties:
  2. Distinctiveness: The augmented data distribution must not naturally overlap with the normal data (e.g., inverted colors or vertical flips produce images that are clearly unnatural in that context).
  3. Alignment: Relationships between samples must be preserved ($d(x, x') \approx d(t_C(x), t_C(x'))$).
  4. The $\text{CON}_2$ Objective: The model trains an encoder $g_\theta$ with two parallel projection heads and a joint loss: $$\mathcal{L}_{\text{Con}_2} = \mathcal{L}_{\text{Context}} + \alpha \mathcal{L}_{\text{Content}}$$
  5. Context Contrasting ($\mathcal{L}_{\text{Context}}$): Pushes original and context-augmented samples into two tightly separated representation clusters using supervised contrastive learning.
  6. Content Alignment ($\mathcal{L}_{\text{Content}}$): Uses instance discrimination across clusters so that representations of the same underlying sample match across contexts, creating mirror-like internal geometries in both clusters.
  7. $\alpha$ is annealed linearly from $0$ to $1$ during training to first establish context clusters before refining cross-cluster alignment.
  8. Anomaly Scoring:
  9. $S_{\text{NND}}$: A non-parametric cosine nearest-neighbor distance against the training set representations under test-time augmentations.
  10. $S_{\text{LH}}$: A lightweight, memory-efficient parametric alternative that models normalized embeddings within each cluster as a multivariate Gaussian and uses negative log-likelihood as the anomaly score.

Datasets

The authors evaluated $\text{CON}_2$ across specialized medical and standard natural image benchmarks:

  • Medical Imaging: Chest X-ray Pneumonia detection (Kermany et al., 2018) and Melanoma skin cancer detection (Javid, 2022).
  • Natural Image Benchmarks (One-Class Classification): CIFAR-10, CIFAR-100 (20 superclasses), ImageNet30, Dogs vs. Cats, and Muffin vs. Chihuahua.

Key Insights and Ideas

  • Normality Invariance Over Outlier Simulation: Instead of forcing the model to separate normal samples from artificial pseudo-anomalies, $\text{CON}_2$ forces the model to understand the internal manifold structure of normal images. Anomalies fail to project symmetrically across context clusters.
  • Context Violations Matter: If an augmentation violates distinctiveness, the model fails. For example, vertically flipping a chest X-ray works well because anatomical orientation is fixed. However, flipping a melanoma lesion harms performance (dropping AUROC from 94.1% to 93.4%) because skin lesions have no canonical orientation. In contrast, color inversion or histogram equalization satisfy distinctiveness for skin lesions.
  • Foundation Models Aren't Always Enough: While CLIP-AD excels on common objects (e.g., 99.9% AUROC on ImageNet30), it lags significantly behind in specialized domains (71.2% on Pneumonia and 77.2% on Melanoma), where in-domain self-supervised representations from $\text{CON}_2$ clearly dominate.

Key Results

  • Medical Domain: On Pneumonia detection, $\text{CON}_2$ (Equalize) achieved 93.9% AUROC ($S_{\text{NND}}$) and 93.0% ($S_{\text{LH}}$), substantially outperforming baselines like CSI (73.9%), UniCon-HA (86.4%), and zero-shot CLIP-AD (71.2%). On Melanoma, $\text{CON}_2$ reached 94.5% AUROC, exceeding CSI (92.3%) and SSD (79.0%).
  • Natural Image Benchmarks: $\text{CON}_2$ (Flip) achieved an average AUROC of 95.3% on CIFAR-10 and 90.8% on CIFAR-100, matching or outperforming contrastive baselines like CSI (94.6% and 90.2%) while demonstrating lower variance across classes.
  • Compute Efficiency: The parametric likelihood score $S_{\text{LH}}$ delivers performance within $0.5$–$1.0\%$ AUROC of the nearest-neighbor approach without needing to store training-set embeddings in memory.

Limitations and Future Work

  • Domain-Specific Augmentation Choice: The framework requires selecting an appropriate context augmentation that strictly satisfies distinctiveness and alignment for the target distribution; picking an unsuitable augmentation hurts detection quality.
  • Diminishing Returns on Multiple Contexts: Ablations revealed that expanding beyond two contexts (e.g., combinations of 3–8 augmentations) increased memory consumption without improving detection performance, especially for challenging classes.
  • Modality Scope: Experiments were strictly conducted on 2D images. Extending context contrasting to 3D volumetric scans, time-series, or tabular data remains an open research direction.

Summary updated

Abstract

Anomaly detection focuses on identifying samples that deviate from the norm. When working with high-dimensional data such as images, a crucial requirement for detecting anomalous patterns is learning lower-dimensional representations that capture concepts of normality. Recent advances in self-supervised learning have shown great promise in this regard. However, many successful self-supervised anomaly detection methods assume prior knowledge about anomalies to create synthetic outliers during training. Yet, in real-world applications, we often do not know what to expect from unseen data, and we can solely leverage knowledge about normal data. In this work, we propose Con$_2$, which learns representations through context augmentations that allow us to observe samples from two distinct perspectives while keeping the invariances of normal data. Con$_2$ learns rich representations of context-augmented samples by clustering them according to their context while simultaneously aligning their positions across clusters. At test time, representations of anomalies that do not adhere to the invariances of normal data then deviate from their respective context cluster. Learning representations in such a way thus allows us to detect anomalies without making assumptions about anomalous data.
BibTeX
@misc{ryser2024anomaly,
  author = {Alain Ryser and Thomas M. Sutter and Alexander Marx and Julia E Vogt},
  title = {{Anomaly Detection by Context Contrasting}},
  year = {2024},
  eprint = {2405.18848},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2405.18848},
}

Loading related content...

Figure