GAN-based anomaly detection

Also known as: AnoGAN · GANomaly

On this page 7

GAN-based anomaly detection is a family of anomaly detection methods that train a generative adversarial network (GAN) only on normal data and then flag new samples that the trained model cannot reproduce or does not recognize as realistic. The approach is mostly unsupervised or semi-supervised: it needs plenty of normal examples but few or no labeled anomalies, which matches many industrial, medical and security settings.

Well-known representatives include AnoGAN, introduced in 2017 for retinal imaging, its faster successor f-AnoGAN, the BiGAN-based EGBAD and ALAD models, and GANomaly, which compares latent codes instead of pixels. In artificial intelligence practice, these methods sit beside autoencoder anomaly detection and newer feature-embedding methods such as PatchCore, and they are valued mainly for high-dimensional data such as images, sensor streams and multivariate time series.

How a GAN learns the normal data distribution

A GAN consists of two networks trained against each other. The generator maps random latent vectors to synthetic samples, and the discriminator learns to tell real samples from generated ones. When training converges, the generator has approximated the distribution of normal data, and the discriminator has learned features that describe what normal samples look like.

Anomaly detection exploits this learned model of normality. Because the network has never seen anomalies during training, an abnormal input either cannot be mapped to a good latent code or produces a poor reconstruction, and the discriminator responds to it differently. These differences are combined into a numeric anomaly score, which is compared with a threshold to decide whether a sample is anomalous.

SignalWhat it measuresUsed by
Residual lossPixel or value difference to reconstructionAnoGAN, f-AnoGAN
Discrimination lossDistance in discriminator feature spaceAnoGAN, EGBAD
Latent differenceGap between two encoded latent vectorsGANomaly
Discriminator outputEstimated probability that input is realSimple baseline variants
Cycle consistency errorMismatch after encode and decode cycleALAD
Signals used to build a GAN anomaly score

Main GAN anomaly detection architectures

The architectures differ mainly in how they find the latent code of a test sample. The original AnoGAN has no encoder, so it searches the latent space with gradient descent for every test image, often for hundreds of iterations. Later designs add an encoder that produces the latent code in a single forward pass, which makes inference fast enough for production.

ModelKey ideaInference cost
AnoGANIterative latent search per test sampleHigh, many optimization steps
f-AnoGANEncoder trained after the GANLow, one forward pass
EGBADBiGAN learns encoder jointlyLow, one forward pass
GANomalyEncoder, decoder, encoder; compare latentsLow, one forward pass
Skip-GANomalyU-Net generator with skip connectionsLow, better detail recovery
TadGANRecurrent GAN for time seriesModerate, sequence windows
Representative GAN-based detectors

GANomaly illustrates the encoder approach. An input image is encoded to a latent vector, decoded into a reconstruction and encoded again. For normal images the two latent vectors are close; for anomalies the second encoding diverges, and that distance serves as the score. Adversarial and contextual losses during training keep reconstructions sharp.

Comparison with other anomaly detection methods

GAN-based detectors are one option among several deep anomaly detection approaches, and they are rarely the default choice today. Their main advantage over plain autoencoders is that the adversarial loss yields sharper reconstructions, which reduces false alarms caused by blurry outputs. Their main disadvantage is unstable and expensive training.

MethodStrengthWeakness
GAN-based detectionModels complex, high-dimensional normalityUnstable training, mode collapse
Autoencoder detectionSimple, stable trainingBlurry reconstructions, generalizes to anomalies
Deep SVDDCompact one-class objectiveRisk of collapse to trivial solution
PatchCoreStrong image results, no generatorMemory bank grows with data
Isolation forestFast on tabular dataWeak on raw images and signals
GAN-based detection against related approaches

On industrial image benchmarks such as MVTec AD, methods built on pretrained feature embeddings, for example PaDiM and PatchCore, generally outperform GAN-based models in both detection accuracy and anomaly localization. GAN approaches remain relevant where pretrained features do not fit, such as unusual sensor modalities, and where synthetic normal samples are useful in their own right.

Training and deployment considerations

Reliable GAN detectors depend on clean normal training data, careful stabilization and a well-chosen threshold. Even a small contamination rate of anomalies in the training set teaches the generator to reproduce defects, which lowers recall.

  • Use stabilization techniques such as spectral normalization, feature matching or Wasserstein losses to avoid mode collapse.
  • Monitor reconstructions visually, because generator loss alone is a poor indicator of detection quality.
  • Set the threshold on a held-out validation set using a target false positive rate.
  • Combine scores, for example residual and discrimination loss, with a tuned weighting factor.
  • Retrain or recalibrate when the normal data distribution drifts over time.

Limitations and common failure modes

GAN-based anomaly detection has well-documented weaknesses that practitioners should test for before deployment. Several of them stem directly from adversarial training itself.

SymptomLikely causeRemedy
Anomalies reconstructed wellGenerator too expressiveRestrict capacity, compare latents
Many false alarmsMode collapse misses normal variantsStabilize training, add diversity
Scores drift between runsUnstable adversarial trainingAverage several seeds or models
Slow inferenceIterative latent searchSwitch to an encoder-based model
Poor localizationGlobal score onlyUse pixel-wise residual maps
Typical failure modes and remedies

A frequent misconception is that a realistic-looking reconstruction proves the model works. A generator that reproduces every input, including defects, is useless for detection, so evaluation must always use held-out anomalous examples and metrics such as AUROC or precision at a fixed alert budget.

Understanding it simply

Imagine an art student who copies thousands of normal photos of the same product. After long practice, the student can draw a normal product from memory. Now show the student a new photo and ask for a copy.

If the product is normal, the copy looks almost identical. If the product has a scratch or a dent, the student cannot draw it well. The copy and the photo differ. That difference signals a problem. A GAN does the same with two networks: one draws, and one checks whether the drawing looks real.

Applied in practice

A manufacturer of printed circuit boards inspects about 20,000 boards per day with a camera at the end of its assembly line. Defects such as missing components or solder bridges are rare, and many defect types have never been photographed, so a supervised classifier cannot be trained. The quality team instead trains a GANomaly-style model on 15,000 images of boards approved by human inspectors.

During operation, each new image receives an anomaly score in a few milliseconds, and the threshold is set so that roughly 2 percent of boards go to manual review. Pixel-wise residual maps show inspectors where to look. After a pilot phase, the team found that the model caught most previously unseen defect types, while false alarms concentrated on boards with unusual lighting, which led to better illumination control and a retrained model.