Bayesian Autoencoder Anomaly Detection

Machine Learning
Introduced by
Kingma, D. P. & Welling, M.; applied to anomaly detection by An & Cho
Year
2014–2015
Type
Probabilistic generative model for unsupervised anomaly detection
Family
Machine learning

What does it do?

Bayesian Autoencoder Anomaly Detection uses a Variational Autoencoder (VAE), a probabilistic generative model trained only on normal data, to score new inputs by how poorly the learned model explains them.

The encoder maps each input to a distribution over a latent code rather than to a single point, and the anomaly score is the negative expected log-likelihood of the input under the decoder. The Bayesian element is approximate variational inference over the latent variable, not a posterior distribution over the network weights.

The intuition behind the method

A standard autoencoder compresses and reconstructs its training data, so inputs unlike the training set tend to reconstruct poorly and score as anomalous. A Variational Autoencoder differs because the encoder outputs a Gaussian distribution over the latent code for each input, and the training objective (the ELBO) penalises the KL divergence between that distribution and a standard normal prior. At scoring time, the expected negative log-likelihood under the approximate posterior is estimated by drawing several latent samples. Because the score is an average of log-likelihoods rather than of probabilities, it measures how improbable an input is under the model, and the spread of values across samples indicates how stable that estimate is.

History

Kingma and Welling (2014) introduced the Variational Autoencoder, combining neural network encoders and decoders with variational inference and the reparameterisation trick. An and Cho (2015) applied the VAE to anomaly detection and used reconstruction probability as the anomaly score.

When to use it

Choose this method when a large set of unlabelled normal data is available, confirmed anomaly labels are scarce or absent, and the inputs are high-dimensional and non-linear, such as images, sensor arrays or wide multichannel data. It is also a reasonable choice when per-input variability in the score is useful for downstream review. Do not use it when the training set is small, because a deep generative model needs enough normal examples to learn the normal distribution. Avoid it when the data are low-dimensional with approximately linear structure, where simpler statistical methods are easier to interpret; when inference must run under tight latency without accelerator hardware; or when labelled anomalies are plentiful enough for supervised classification. Its performance relative to Isolation Forest or One-Class SVM depends on the data, so compare the candidates on your own data.

Limitations and considerations

  • A substantial set of normal training examples is needed; scarce or heterogeneous normal data weakens the learned distribution.
  • Training is computationally heavy, and accelerator hardware is usually needed for large inputs such as images.
  • Results depend on architecture, latent dimension and the weighting of the KL term. The objective shown has unit weight on the KL term, but many implementations add a weight, which shifts the trade-off between reconstruction quality and latent regularity.
  • Posterior collapse, in which the encoder ignores the input, can leave reconstructions uninformative and scores nearly uniform across inputs.
  • The score does not identify which features make a specific input anomalous; explaining an individual flag needs post-hoc analysis.

Source conditions do not replace independent scientific review or validation by an analysis engine.

Strengths

  • Training is fully unsupervised: only normal examples are needed, with no anomaly labels.
  • The encoder can model non-linear structure in high-dimensional inputs, where linear or kernel-based detectors may not capture the region occupied by normal data.
  • Each score is tied to a latent posterior, so the spread of values across posterior samples gives a per-input indication of score variability. This is an indicator, not a validated calibration of the score.
  • The KL term encourages latent codes to follow a standard normal prior. This can help in inspecting the latent structure, but it does not by itself define a normality boundary.

Applications

  • Industrial defect detection in manufacturing using visual inspection data.
  • Medical imaging anomaly detection (e.g., detecting lesions in MRI scans trained on healthy subjects only).
  • Network intrusion detection where normal traffic patterns are abundant, provided categorical and mixed-type traffic features are encoded or modelled with a suitable decoder likelihood.
  • Financial fraud detection when labelled fraud cases are unavailable or quickly outdated, with the same caveat for categorical transaction features.
  • Predictive maintenance via sensor-array anomaly detection on industrial machinery.
  • Scientific data quality control, flagging unusual observations in experimental datasets.

How it works

How it works

1

An encoder network maps each input x to the mean and variance of a Gaussian approximate posterior over the latent variable z. The output is a distribution rather than a single code, so one input can correspond to a range of latent values.

Formula
q_{\phi}(z|x) = \mathcal{N}(\mu_{\phi}(x),\,\sigma^{2}_{\phi}(x))
2

Latent codes are drawn with the reparameterisation trick: noise from a standard normal is scaled by the posterior standard deviation and added to the posterior mean. Writing the sample this way keeps it differentiable, so the network can be trained by gradient-based backpropagation.

Formula
z = \mu_{\phi}(x) + \epsilon\,\sigma_{\phi}(x),\quad \epsilon \sim \mathcal{N}(0,I)
3

A decoder network defines p(x|z), the distribution of inputs given a latent code. Trained on normal data, it learns to generate inputs that resemble the normal class. The likelihood family must be chosen in advance: a Gaussian decoder is the usual choice for continuous inputs, while Bernoulli or categorical decoders suit binary or categorical inputs.

Formula
p_{\theta}(x|z)
4

Training maximises the evidence lower bound: the expected log-likelihood of the reconstructions minus the KL divergence between the approximate posterior and the prior p(z). Only normal, in-distribution data is used, so the learned distribution describes normal inputs.

Formula
\mathcal{L} = \mathbb{E}_{q}[\log p_{\theta}(x|z)] - D_{\mathrm{KL}}(q_{\phi}(z|x)\|p(z))
5

At scoring time the anomaly score is the negative expected log-likelihood of the input, estimated by averaging log p(x|z) over latent samples drawn from the encoder. Inputs that the decoder explains poorly receive high scores. Because the expectation is taken in log space, it is not the same as averaging probabilities. Scores are comparable across inputs only when the same decoder family and input scaling are used throughout.

Formula
s(x) = -\mathbb{E}_{z \sim q_{\phi}(z|x)}[\log p_{\theta}(x|z)]

Common pitfalls

  • Training on a contaminated dataset that includes anomalies in the 'normal' class, causing the model to learn anomalous patterns as normal.
  • Choosing the anomaly-score threshold arbitrarily rather than using a held-out set of known normal examples.
  • Ignoring posterior collapse during training, which can make reconstruction error uniformly uninformative.
  • Comparing raw reconstruction errors across datasets with different input scales without normalisation.
  • Evaluating with accuracy alone on highly imbalanced test sets instead of using AUROC or average precision.

Frequently asked questions

How does this differ from a standard (deterministic) autoencoder for anomaly detection?

A standard autoencoder maps each input to a fixed latent code and scores anomalies by reconstruction error. A variational autoencoder maps each input to a distribution over latent codes and scores anomalies by the negative expected log-likelihood under the decoder. The probabilistic formulation adds a latent posterior for each input, at the cost of more complex training.

What latent dimension should I choose?

The latent dimension should be large enough to represent the structure of normal data but not so large that the model reconstructs nearly everything, including anomalies. Choose it by checking reconstruction quality on a held-out set of normal samples, and compare candidate sizes rather than applying a fixed rule of thumb.

Do I need GPU hardware to run this method?

Tabular data of moderate width can be trained on a CPU, though training will be slower. Image and high-dimensional sensor data usually need an accelerator. Scoring is typically faster than training.

How do I set the anomaly threshold?

The threshold is not learned during training. Use a held-out set of confirmed normal samples and select the score percentile (e.g., 95th or 99th) that gives an acceptable false-positive rate in your domain. Avoid choosing the threshold on the same data used to evaluate final performance.

Can this method work when some anomalies appear in the training set?

Minor contamination is often tolerated because the model is optimised on the majority class. However, heavy contamination shifts what the model learns as 'normal' and should be minimised by cleaning training data as thoroughly as possible.

Related methods

Sources

  1. Kingma, D. P. & Welling, M. (2014). Auto-Encoding Variational Bayes. Proceedings of the 2nd International Conference on Learning Representations (ICLR 2014).

    Open publication reference
  2. An, J. & Cho, S. (2015). Variational Autoencoder based Anomaly Detection using Reconstruction Probability. ICDM Workshop on Data Mining in Networks.

    Open publication reference