# Memorizing Normality to Detect Anomaly: Memory-augmented Deep Autoencoder for Unsupervised Anomaly Detection

Memory-augmented autoencoders stop reconstructing anomalies, so anomalies stand out more

Dong Gong, Lingqiao Liu, Vuong Le, Budhaditya Saha, Moussa Reda Mansour, Svetha Venkatesh and 1 more · arXiv · 2019-4-4

- **Problem** Autoencoders trained on normal data are expected to reconstruct anomalies poorly, but they often generalize so well that they also rebuild anomalies, hiding them. This makes reconstruction error an unreliable detection signal.
- **Method** MemAE adds a memory of normal prototypes between the encoder and decoder. The encoding queries the memory, and the decoder rebuilds the input only from retrieved memory items, using sparse addressing with hard shrinkage and an entropy loss.
- **Results** MemAE reached an AUC of 0.9751 on one-class MNIST, against 0.9619 for the plain autoencoder. It also reached 0.941 on UCSD-Ped2.

## Why reconstruction error can mislead

The usual recipe trains an autoencoder on normal data only and treats a high reconstruction error on a test input as a sign that the input is abnormal. This rests on the expectation that normal inputs, being close to the training data, are rebuilt more faithfully than abnormal ones.

The expectation does not always hold. An encoder and decoder that generalize well can rebuild inputs they never saw during training, including anomalies. Anomalies that share local structure with normal data, or a decoder that is too capable, can both lead to good reconstructions of abnormal inputs. The authors observe this behaviour in their own experiments as well as in earlier work.

## Memory as a bank of normal prototypes

MemAE does not pass the encoding straight to the decoder. The encoding is used as a query against a memory, and the decoder receives a combination of the memory items that the query retrieves. The encoder therefore acts as a query generator, and the decoder only sees content drawn from what the memory holds.

The memory is a matrix \\(M\\in\\mathbb{R}^{N\\times C}\\) with \\(N\\) rows, each a memory item \\(m\_i\\) of dimension \\(C\\) that matches the encoding. For a query \\(z\\), the addressing weights come from a softmax over cosine similarities, \\(w\_i=\\frac{\\exp(d(z,m\_i))}{\\sum\_{j=1}^{N}\\exp(d(z,m\_j))}\\), with \\(d(z,m\_i)=\\frac{z\\,m\_i^{T}}{\\\|z\\\|\\,\\\|m\_i\\\|}\\).

The readout is the weighted sum \\(\\hat z = wM=\\sum\_{i=1}^{N} w\_i m\_i\\), and the decoder reconstructs \\(\\hat x\\) from \\(\\hat z\\).

The reason for this design is the bottleneck on what the decoder can produce. When each reconstruction must come from a few stored normal items, the decoder cannot easily build an abnormal input from its own detail. Training fills the memory with the most representative normal patterns, so reconstructions tend to look normal even when the input does not.

Setting \\(\\hat z = z\\) recovers the standard autoencoder, so the memory is the only difference between the two models.

## Keeping the addressing sparse

A dense weight vector can still combine many small contributions into a close reconstruction of an anomaly, so sparsity is enforced on the weights. The hard shrinkage operator sets each weight to zero unless it exceeds a threshold \\(\\lambda\\), and the surviving weights are renormalized with the \\(\\ell\_1\\) norm. The threshold is set in the interval \\(\[1/N, 3/N\]\\), which the authors report gives desirable results.

The discontinuous cut has no useful gradient, so the authors replace it with a ReLU-based form, \\(\\hat w\_i=\\frac{\\max(w\_i-\\lambda,0)\\,w\_i}{\|w\_i-\\lambda\|+\\epsilon}\\), where \\(\\epsilon\\) is a very small positive scalar. This keeps the operation differentiable, so the memory and the encoder can be trained through it.

A second sparsity term is an entropy loss on the addressing weights, \\(E(\\hat w)=-\\sum\_i \\hat w\_i\\log \\hat w\_i\\), which is added to the reconstruction loss. The authors also note that the sparse addressing gives the sparse weights in one forward pass, where sparse coding methods need iterative updates.

## Training and scoring at test time

During training the encoder, the decoder and the memory contents are all updated by backpropagation to lower the combined loss. Only memory items with non-zero addressing weights receive gradients in a given pass. Training uses the Adam optimizer with a learning rate of 0.0001 for MemAE and its variants.

At test time the memory is fixed. The reconstruction is built from the normal items that lie closest to the encoding of the test input. The anomaly criterion is the squared l2 reconstruction error \\(e=\\\|x-\\hat x\\\|\_2^2\\) on the test input.

For video, the reconstruction error of a cuboid is assigned to its centre frame, and the errors are normalized to the range \[0, 1\]. The per-frame normality score is \\(p\_u = 1-\\frac{e\_u-\\min\_u e\_u}{\\max\_u e\_u-\\min\_u e\_u}\\), so values near 0 indicate frames that are more likely abnormal.

## One-class results on MNIST and CIFAR-10

Each dataset yields 10 one-class problems: one class is normal and the rest are anomalies, with about 30% anomalies in the test set. Normal samples are split 2:1 into training and test sets, and 10% of the original training data is kept for validation. The MNIST encoder uses three convolutional layers, and the CIFAR-10 model uses wider layers, with memory sizes of 100 for MNIST and 500 for CIFAR-10.

Baselines include OC-SVM, KDE, a variational autoencoder, PixCNN and DSEBM, plus the plain AE and MemAE-nonSpar, all given similar model capacity. Performance is the AUC averaged over the 10 sampled datasets.

On MNIST, MemAE reached 0.9751 and MemAE-nonSpar 0.9725, against 0.9619 for the plain AE. The variational autoencoder reached 0.9643 on MNIST, close to the AE, and the authors attribute its strength to the simple digit structure. KDE reached 0.8116 and PixCNN 0.6141 on MNIST.

On CIFAR-10 every method scores lower than on MNIST. MemAE reached 0.6088, MemAE-nonSpar 0.6058 and the plain AE 0.5706. The authors attribute the drop to the more complex content of CIFAR-10 and the larger intra-class variance in several classes.

## What the memory slots store on MNIST

The memory was trained on digit 9 treated as normal, and a single randomly chosen slot was decoded on its own. The decoded slot is blurry and noisy, because reconstructions normally combine several addressed items. Even so, different slots capture different prototypical versions of the digit 9.

In the example trained on the digit 5, an input of digit 9 is reconstructed as a 5 with a shape similar to the input. The authors explain that the memory returns the most similar normal patterns, so the abnormal digit does not pass through unchanged. The plain AE tends to learn representations more locally, so it can rebuild an abnormal sample well.

## Video anomaly detection on three benchmarks

Experiments use UCSD-Ped2, CUHK Avenue and ShanghaiTech. ShanghaiTech has more than 270,000 training frames and more than 42,000 test frames, of which about 17,000 are abnormal, across 13 scenes. The encoder and decoder use 3D convolutions over a cuboid of 16 stacked grayscale frames. Each memory slot holds the features of one spatial position in the feature map, and the memory has \\(N=2000\\) items of dimension 256.

On UCSD-Ped2, MemAE reached 0.941 against 0.917 for the AE and 0.929 for MemAE-nonSpar. On CUHK Avenue it reached 0.833 against 0.810 for the AE, and on ShanghaiTech 0.712 against 0.697. Frame-Pred scored higher than MemAE on all three, with 0.954, 0.849 and 0.728, and it uses optical flow and adversarial training. The authors describe MemAE as comparable to that method, and note that their aim is a general reconstruction model rather than the highest score in one application.

On an abnormal UCSD-Ped2 frame, the MemAE error map highlights the moving vehicle and bicycle on the sidewalk, while the AE reconstructs them and produces scattered errors.

MemAE processes one UCSD-Ped2 frame in 0.0262 seconds, about 38 fps, on an NVIDIA GeForce 1080 Ti. The timings of other methods are quoted from the work that proposed them and were measured on a faster graphics card than the one used here.

A memory size study on UCSD-Ped2 varies \\(N\\) from 500 to 3000. Once the memory is large enough, the authors report that MemAE gives plausible results robustly.

## KDDCUP cybersecurity results

The data is KDDCUP99 10 percent from the UCI repository, with 80% of the samples labelled attack treated as normal. Each sample is a 120-dimensional vector, encoded and decoded by fully connected layers, with a memory of \\(N=50\\) items of size 3. Half of the data is used for training and the rest for testing, and results are averaged over 20 runs with precision, recall and F1.

MemAE reached an F1 of 0.9641, with precision 0.9627 and recall 0.9655. The plain AE reached an F1 of 0.9342, and DAGMM 0.9369. The authors attribute the gain to the memory explicitly storing behaviour patterns of the attack samples.

## Which sparsity components matter

The two sparsity components are the hard shrinkage and the entropy loss, and each is removed in turn while the other stays in place. Removing either component lowers the score, so each contributes to this result.

The authors explain that without shrinkage the model cannot directly encourage sparsity at test time, which can leave noisy, dense weights. They attribute the value of the entropy loss to the early stage of training, when the addressing weights are still poorly optimized.

The authors argue that this penalty lacks the memory mechanism that pushes reconstruction errors up on anomalies, which explains why it stays below MemAE.

## Limits of the evidence

The video comparison is not a matched test against the strongest methods, since Frame-Pred uses optical flow and adversarial training that MemAE does not. The authors state that their study is orthogonal to that line of work and could be combined with it.

CIFAR-10 remains hard, with MemAE at 0.6088 AUC on average. The memory-size robustness and the sparsity ablation are measured only on UCSD-Ped2. Memory sizes are chosen per dataset: 100 for MNIST, 500 for CIFAR-10, 2000 for the video data and 50 for KDDCUP.

Running time comparisons with other methods rely on timings from another source on a faster card. The authors leave open whether the addressing weights themselves can be used for anomaly detection.

## Paper info

- **Authors**: Dong Gong, Lingqiao Liu, Vuong Le, Budhaditya Saha, Moussa Reda Mansour, Svetha Venkatesh, Anton van den Hengel
- **Venue**: arXiv · Preprint
- **First published**: 2019-4-4
- **Added**: 2026-11-12
- **Updated**: 2019-8-6
- **Version**: v2
- **arXiv**: 1904.02639
- **Category**: cs.CV
- **Original paper terms**: [arXiv non-exclusive 1.0](https://arxiv.org/licenses/nonexclusive-distrib/1.0/)
- **What we show**: Paper info and commentary

[Original paper ↗](https://arxiv.org/abs/1904.02639v2) · [PDF ↗](https://arxiv.org/pdf/1904.02639v2)

AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.

## Quote from the paper

Dong Gong, Lingqiao Liu, Vuong Le, Budhaditya Saha, Moussa Reda Mansour, Svetha Venkatesh, Anton van den Hengel (2019). Memorizing Normality to Detect Anomaly: Memory-augmented Deep Autoencoder for Unsupervised Anomaly Detection. arXiv:1904.02639v2. https://arxiv.org/abs/1904.02639v2

**BibTeX**

```
@misc{gong2019memorizing,
  title = {{Memorizing Normality to Detect Anomaly: Memory-augmented Deep Autoencoder for Unsupervised Anomaly Detection}},
  author = {Dong Gong and Lingqiao Liu and Vuong Le and Budhaditya Saha and Moussa Reda Mansour and Svetha Venkatesh and Anton van den Hengel},
  year = {2019},
  eprint = {1904.02639},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/1904.02639v2}
}
```

## Other paper commentary

- [LLNet: A Deep Autoencoder Approach to Natural Low-light Image Enhancement](https://refivu.com/en/papers/1b58b4f0-48b5-40db-be28-ecd8cf270c6f-llnet-a-deep-autoencoder-approach-to-natural-low.md)
- [MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer](https://refivu.com/en/papers/c76255ba-9c87-4edc-80cc-28d59c4ccfc5-mobilevit-light-weight-general-purpose-and-mobile-friendly.md)
- [FairMOT: On the Fairness of Detection and Re-Identification in Multiple Object Tracking](https://refivu.com/en/papers/081a3a22-90c6-4c70-a7df-d2e70b35ad22-fairmot-on-the-fairness-of-detection-and-re.md)
- [Is Space-Time Attention All You Need for Video Understanding?](https://refivu.com/en/papers/b6bd7278-3728-4d96-9fe0-5f483de3f3bd-is-space-time-attention-all-you-need-for.md)
- [Return of Frustratingly Easy Domain Adaptation](https://refivu.com/en/papers/0a776e2c-6337-4850-9be1-86de976005d2-return-of-frustratingly-easy-domain-adaptation.md)
- [Celeb-DF: A Large-scale Challenging Dataset for DeepFake Forensics](https://refivu.com/en/papers/127fcad1-737e-4bb9-b7b5-7c87f1ab7614-celeb-df-a-large-scale-challenging-dataset-for.md)
- [Speech Commands: A Dataset for Limited-Vocabulary Speech Recognition](https://refivu.com/en/papers/4809d645-7dd0-42ce-ba15-4c5208cfa877-speech-commands-a-dataset-for-limited-vocabulary-speech.md)
- [RePaint: Inpainting using Denoising Diffusion Probabilistic Models](https://refivu.com/en/papers/3c0a622f-efc1-4d6c-bb30-bd253079ac9a-repaint-inpainting-using-denoising-diffusion-probabilistic.md)
- [Hypergraph Neural Networks](https://refivu.com/en/papers/cf9d7d35-b5ef-4472-b64e-4c332f808ace-hypergraph-neural-networks.md)
- [RotatE: Knowledge Graph Embedding by Relational Rotation in Complex Space](https://refivu.com/en/papers/6cf7532c-a2b4-4553-a534-0482af8548e2-rotate-knowledge-graph-embedding-by-relational-rotation-in.md)
- [Deep Ordinal Regression Network for Monocular Depth Estimation](https://refivu.com/en/papers/e525192f-9651-4698-8525-b6cda281195b-deep-ordinal-regression-network-for-monocular-depth.md)

## Terms in this paper

- [MNIST](https://refivu.com/en/terms/28b9bb66d1c6-mnist)
- [AUC](https://refivu.com/en/terms/017a335bbf0e-auc)
- [cosine similarity](https://refivu.com/en/terms/3baa01a8760d-cosine-similarity)
- [anomaly detection](https://refivu.com/en/terms/77099eee12c1-anomaly-detection)
- [Reconstruction error](https://refivu.com/en/terms/becbd6e37730-reconstruction-error)
- [ShanghaiTech](https://refivu.com/en/terms/6d848d98315b-shanghaitech)

---

AI-written text can contain mistakes. [Refivu](https://refivu.com/en/papers/b6435fab-e010-4a4f-aeb8-b125ca06e94a-memorizing-normality-to-detect-anomaly-memory-augmented-deep)
