# Deep metric learning using Triplet network

Triplet networks learn distance comparisons that beat Siamese networks

Hoffer, Elad, Ailon, Nir · arXiv · 2014-12-20

- **Problem** Deep networks learn distances only as a by-product of classification. Siamese networks learn an explicit metric from pairs, but their features classify poorly and their similarity depends on context.
- **Method** Triplet networks use three shared-weight copies of one embedding network. They take an anchor, a same-class sample and a different-class sample, and train so the same-class sample ends up closer to the anchor.
- **Results** On MNIST, the triplet network reached 99.54±0.08% accuracy against 97.9±0.1% for the Siamese network. It reached 87.1% on Cifar10 without data augmentation.

## Why learn the metric directly

Deep networks are usually trained to classify, and the distance structure of their features is a by-product of that objective rather than a training target. The authors also note that what intermediate layers encode, and how they separate the factors of variation in the data, remains an open question.

Siamese networks are the existing models that do learn a metric explicitly. They pass a pair of inputs through the same network and apply a contrastive loss, which pulls pairs of the same kind together and pushes other pairs apart in the induced distance. The authors report that features from these models classify worse than those from other deep models, and that a Siamese model depends on context: whether two items count as similar changes with the set of items being compared against.

The triplet network replaces pair labels with comparisons. For an anchor x, a sample x+ of the same class and a sample x- of a different class, the training target is that x+ ends up closer to x than x- does. Wang et al. (2014) used a similar construction for ranking in image retrieval. The present work studies the triplet architecture more broadly and evaluates it on classification.

## Triplet architecture and training objective

These two distances form a two-element vector that is passed to the final comparison. Nothing is compared against a fixed threshold, so each triplet is judged only through the two distances it produces.

Training is posed as a two-class problem: given the anchor, decide which of x+ and x- belongs to the anchor's class. The authors interpret closeness as sharing a label, though they note that the same setup could learn a general metric embedding from other closeness labels. A SoftMax over the two distances turns them into a ratio. The positive output is \\(d\_{+}=\\dfrac{e^{\\\|Net(x)-Net(x\_{+})\\\|\_2}}{e^{\\\|Net(x)-Net(x\_{+})\\\|\_2}+e^{\\\|Net(x)-Net(x\_{-})\\\|\_2}}\\), and \\(d\_{-}\\) is the complementary term with the two exponents swapped.

The authors note that this loss tends to zero when the ratio of the distance to x+ over the distance to x- tends to zero, which is the wanted behaviour. Because all three inputs share one set of weights, backpropagation updates the network from all three samples in the same step.

## Datasets, sampling and embedding networks

Four datasets were used. Cifar10 has 60000 color images of 32x32 pixels in 10 classes, with 50000 for training and 10000 for test. MNIST has 60000 gray-scale 28x28 digit images with a separate test set of 10000. SVHN contains 600000 color 32x32 house-number digit images. STL10 has 10 object classes, 5000 training images and 96x96 images.

Each training instance is a uniformly sampled set of three images, two from the same class and one from a different class. Each epoch uses 640000 such instances, drawn at random, and a fixed set of 64000 instances is used for testing, where every test triplet is built from images excluded from training.

For Cifar10 and SVHN the embedding network has three convolutional layers, each followed by 2x2 max-pooling, and a fourth convolutional layer, with a ReLU between consecutive layers. Its filter sizes are {5,3,3,2} and its feature map dimensions are {3,64,128,256,128}, so the final embedding has 128 dimensions. The fully connected classification layer that usually follows is removed, since only the feature embedding is needed.

The STL10 network is the same except for stride 3 in the first layer, and the MNIST network uses smaller feature maps, {1,32,64,128}.

Training used SGD with an initial learning rate of 0.5 and a decay regime, momentum 0.9, and dropout with p = 0.5. Training ran for 10 to 30 epochs, until the error over the triplet comparisons stopped falling. The networks were implemented in Torch7.

## Classification on four datasets

After training, the embedding network extracts features from the full dataset. A simple one-layer network is trained on the training-set representations for the full 10-class task, and accuracy is measured on the test set.

On Cifar10 the model reached 87.1% and on SVHN 95.37%, both without data augmentation. The best known non-augmented results listed by the authors for these datasets are 90.22% and 98.18%, so these two results are below them.

A linear SVM or a KNN classifier on the same embeddings gave results within 0.5% of the main classifier. The authors conjecture that augmentation, such as translations, mirroring and noising, would give gains similar to those in earlier work. This was not tested here.

## TripletNet against the Siamese Network

The Siamese baseline used the same embedding network, but its loss was a contrastive loss over a pair of samples rather than the three-sample objective. Its features were classified with a linear model similar to the one used for TripletNet.

On MNIST, TripletNet reached 99.54±0.08% accuracy, against 97.9±0.1% for the Siamese Network, so the Siamese features gave the lower accuracy on this dataset. This is the only dataset for which the comparison produced a number.

For Cifar10, SVHN and STL10 the authors could not obtain a meaningful Siamese result. They suspect this is linked to the context dependence of similarity, which they leave to future work.

## What the embedding looks like

The embeddings of the test images were projected onto their top two principal directions with PCA, for Cifar10, MNIST and SVHN. In these two-dimensional plots the authors see clusters that follow semantic content, which they take as evidence that the embedding places images by their content. The plots are a visual check and carry no accuracy.

The authors also observed that about 25% of the values of the embedded representation are non-zero. They argue that this sparsity is helpful for later classification, both computationally and in accuracy, because each class is described by only a few non-zero elements.

## Limitations

All reported numbers are without data augmentation or whitening, and only global normalization was used. The effect of augmentation on the triplet embeddings was not measured.

The Siamese comparison is complete only for MNIST. On the other three datasets the authors could not produce a meaningful Siamese result, so the triplet and Siamese models were not compared there. The context explanation for this gap is a conjecture that was left unverified.

## Use without class labels

Training needs only the fact that two of the three samples share a class, not the names of those classes. The authors propose that this could help when clear labels are unavailable or do not make sense, such as with hierarchical labels.

The authors propose spatial information as a source of comparisons: patches that are spatially near in one image are treated as similar. They also propose temporal information, where consecutive video frames count as the same object and distant frames do not. Crowd-sourced comparisons are a further source, since humans give comparative judgements well.

Tamuz et al. (2011) took a different approach to this setting. None of these settings was tested in the paper.

## Paper info

- **Authors**: Hoffer, Elad, Ailon, Nir
- **Venue**: arXiv · Preprint
- **First published**: 2014-12-20
- **Added**: 2026-11-12
- **Updated**: 2018-12-4
- **Version**: v4
- **arXiv**: 1412.6622
- **Category**: cs.LG · cs.CV · stat.ML
- **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/1412.6622v4) · [PDF ↗](https://arxiv.org/pdf/1412.6622v4)

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

Hoffer, Elad, Ailon, Nir (2014). Deep metric learning using Triplet network. arXiv:1412.6622v4. https://arxiv.org/abs/1412.6622v4

**BibTeX**

```
@misc{elad2014deep,
  title = {{Deep metric learning using Triplet network}},
  author = {Hoffer, Elad and Ailon, Nir},
  year = {2014},
  eprint = {1412.6622},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/1412.6622v4}
}
```

## Related papers

- [Understanding deep learning requires rethinking generalization](https://refivu.com/en/papers/cb138997-32a3-4005-82f2-6597e2492ff8-understanding-deep-learning-requires-rethinking.md)
- [A Survey of Convolutional Neural Networks: Analysis, Applications, and Prospects](https://refivu.com/en/papers/070c8ac2-628a-4354-98cb-c9aeae701850-a-survey-of-convolutional-neural-networks-analysis.md)
- [VoxCeleb: a large-scale speaker identification dataset](https://refivu.com/en/papers/4f6bddda-2d26-4b56-93a3-d11745f2af0d-voxceleb-a-large-scale-speaker-identification-dataset.md)
- [Network In Network](https://refivu.com/en/papers/27c629ee-aa61-4496-8fca-b1dbef86d705-network-in-network.md)
- [A Survey on Deep Learning in Medical Image Analysis](https://refivu.com/en/papers/4d173b56-9ea6-4644-98f2-af1794e63965-a-survey-on-deep-learning-in-medical-image.md)
- [Deep Learning-Enabled Semantic Communication Systems with Task-Unaware Transmitter and Dynamic Data](https://refivu.com/en/papers/ebc873df-6d28-4b2d-ac6c-575f5c818afc-deep-learning-enabled-semantic-communication-systems-with.md)

## Other paper commentary

- [Autoformer: Decomposition Transformers with Auto-Correlation for Long-Term Series Forecasting](https://refivu.com/en/papers/d52df827-0d8c-42c3-97e1-3063d2cc1256-autoformer-decomposition-transformers-with-auto-correlation.md)
- [DeepSurv: Personalized Treatment Recommender System Using A Cox Proportional Hazards Deep Neural Network](https://refivu.com/en/papers/e56bf111-97b6-4d99-b702-a3e324f609b2-deepsurv-personalized-treatment-recommender-system-using-a.md)
- [BinaryConnect: Training Deep Neural Networks with binary weights during propagations](https://refivu.com/en/papers/50c59bf6-7b51-443a-b99a-d2bbc087f3e9-binaryconnect-training-deep-neural-networks-with-binary.md)
- [Deep Networks with Stochastic Depth](https://refivu.com/en/papers/a740a8af-8c09-4c4a-92ca-ab98a84c56cf-deep-networks-with-stochastic-depth.md)
- [Deep Transfer Learning with Joint Adaptation Networks](https://refivu.com/en/papers/a47a8c83-de4b-469b-a9c2-9df2e72bbd27-deep-transfer-learning-with-joint-adaptation-networks.md)
- [A Structured Self-attentive Sentence Embedding](https://refivu.com/en/papers/a8cbdabb-c63d-415b-8edf-e85be94428b8-a-structured-self-attentive-sentence-embedding.md)
- [Targeted Backdoor Attacks on Deep Learning Systems Using Data Poisoning](https://refivu.com/en/papers/4dc3fc3a-5207-430d-b5ed-3cc95d077c11-targeted-backdoor-attacks-on-deep-learning-systems-using.md)
- [M3-Embedding: Multi-Linguality, Multi-Functionality, Multi-Granularity Text Embeddings Through Self-Knowledge Distillation](https://refivu.com/en/papers/c3b40084-e91f-4769-ab5c-b3256a5b92f7-m3-embedding-multi-linguality-multi-functionality-multi.md)
- [Graph Convolutional Networks for Text Classification](https://refivu.com/en/papers/3f1e8027-a608-4e71-87f0-2bdbf0fd5a7f-graph-convolutional-networks-for-text-classification.md)
- [Open3D: A Modern Library for 3D Data Processing](https://refivu.com/en/papers/d0e7cf62-d439-416d-a785-974f817c8a48-open3d-a-modern-library-for-3d-data-processing.md)
- [PCT: Point cloud transformer](https://refivu.com/en/papers/54b01448-d153-4635-92bf-22ab3866d1ae-pct-point-cloud-transformer.md)
- [Learning Deep CNN Denoiser Prior for Image Restoration](https://refivu.com/en/papers/e6af5c0e-57ae-4b96-acf1-3a40058beb53-learning-deep-cnn-denoiser-prior-for-image-restoration.md)

## Terms in this paper

- [Accuracy](https://refivu.com/en/terms/1995c0cd6282-accuracy)
- [MNIST](https://refivu.com/en/terms/28b9bb66d1c6-mnist)
- [dropout](https://refivu.com/en/terms/db73f75bbdd3-dropout)
- [ReLU](https://refivu.com/en/terms/7b22f5612f6c-relu)
- [SVHN](https://refivu.com/en/terms/c24d35c2e4d0-svhn)
- [CIFAR10](https://refivu.com/en/terms/19bd6ffb1901-cifar10)
- [SGD](https://refivu.com/en/terms/96a2d83e44ca-sgd)
- [contrastive loss](https://refivu.com/en/terms/53c787c4cf0e-contrastive-loss)
- [MSE](https://refivu.com/en/terms/aaced1b84616-mse)
- [PCA](https://refivu.com/en/terms/2f4628e32ef5-pca)
- [Momentum](https://refivu.com/en/terms/8ca5cdb0ae22-momentum)
- [SoftMax function](https://refivu.com/en/terms/ce0db7dbb3f0-softmax-function)
- [convolutional network](https://refivu.com/en/terms/ed07a2b625c6-convolutional-network)
- [Siamese network](https://refivu.com/en/terms/3d037e233c2c-siamese-network)
- [STL10](https://refivu.com/en/terms/98f2f4dd095f-stl10)

---

AI-written text can contain mistakes. [Refivu](https://refivu.com/en/papers/f6dd7198-0b7a-4f6a-a88a-eb7bbe1ff7ee-deep-metric-learning-using-triplet-network)
