# In Defense of the Triplet Loss for Person Re-Identification

Triplet loss with batch hard mining outperforms surrogate losses for person re-identification

Alexander Hermans, Lucas Beyer, Bastian Leibe · arXiv · 2017-3-22

- **Problem** Triplet loss training stalls without hard triplets, and offline mining is slow and unstable, so most researchers use classification or verification losses instead.
- **Method** Batch Hard builds batches of P identities with K images each, then pairs every anchor with its hardest positive and hardest negative inside the batch.
- **Results** TriNet, built on pretrained ResNet-50, reached 69.14 mAP and 84.92 rank-1 on Market-1501 single-query.

## Why the triplet loss was set aside

Person re-identification asks for an embedding in which images of the same person lie close together and images of different people lie far apart. Much of the recent person ReID literature instead trains a CNN with a classification loss, a verification loss, or both, and then fits a separate metric learning step on the resulting features.

The authors argue that both surrogate losses have costs: classification adds learnable parameters as the identity count grows, and verification networks must process each probe paired with every gallery image, which makes clustering and retrieval expensive.

The triplet loss avoids a separate metric step, but its training depends on which triplets are used. The number of possible triplets grows cubically with dataset size, and the network quickly learns to handle most triplets correctly, so most of them stop contributing to the gradient. Mining the informative triplets is therefore necessary, yet it is a separate pass that requires embedding a large part of the data with the latest network and computing pairwise distances, and mining only the hardest triplets selects outliers and can make training unstable.

## Batch Hard and its batch-level mining

In the classic setup, B triplets are chosen first and their images are stacked into a batch of 3B images, so most of the 3B images are used only once and the many other valid triplets among them are ignored. Batch Hard changes the batching: it draws P identities at random and K images of each identity, so a batch holds PK images, and every anchor in the batch is paired with the hardest positive and hardest negative found within that batch.

The loss for a batch X is written as follows, where x\_ij is the j-th image of the i-th identity in the batch and the hinge keeps only the terms with positive values. \\\[ L\_{BH}(\\theta;X)=\\sum\_{i=1}^{P}\\sum\_{a=1}^{K}\\Big\[m+\\max\_{p=1\\ldots K}D\\big(f\_\\theta(x\_{ia}),f\_\\theta(x\_{ip})\\big)-\\min\_{\\substack{j=1\\ldots P\\\\ j\\neq i}}\\min\_{n=1\\ldots K}D\\big(f\_\\theta(x\_{ia}),f\_\\theta(x\_{jn})\\big)\\Big\]\_+ \\\]

Because each batch produces PK terms rather than B, the number of loss terms per batch is about three times larger than in the classic scheme, and the selected triplets are moderate in the sense that they are the hardest only within a small subset of the data. Batch All uses every valid anchor-positive-negative combination inside the same PK batch, with a hinge over the difference of the anchor-positive and anchor-negative distances, and it is the variant used in earlier person ReID work.

The Lifted Embedding loss fills a batch with triplets but treats every pair except the anchor-positive pair as a negative, and it optimises a smooth bound of a hard-margin objective. The authors generalise it to PK batches by summing over all anchor-positive pairs, each paired with the sum over all negatives, which gives the loss LLG in their notation.

The distance D is the non-squared Euclidean distance. The squared version was more prone to collapse in initial runs, and squaring also makes the margin less interpretable as an absolute distance. No normalising layer is placed on the output, because it would hide problems such as slowly collapsing or exploding embeddings. The soft-margin version replaces the hinge with a softplus, which decays exponentially rather than cutting off, so that same-identity samples keep being pulled together, and the authors motivate it with tracklet-based training on MARS.

## Datasets, optimiser and architectures

Market-1501 contains 32 668 images of 1501 persons and is evaluated with single-query and multi-query protocols. MARS is built from tracklets grouped into identities, so its evaluation is tracklet-to-tracklet and inherently multi-query, and it contains 1 191 003 images. Results are reported as mAP and as CMC at rank-1 and rank-5, and CUHK03 is evaluated with the single-shot setup averaged over the provided splits.

Random crops and horizontal flips are applied during training, and images are resized before cropping so that the aspect ratio is kept.

TriNet discards the last layer of ResNet-50 and adds two fully connected layers, with 1024 units followed by batch normalisation and ReLU and then 128 units as the final embedding. It has 25.74 M parameters, and its batch uses P = 18 persons with K = 4 images each, a size of 72. LuNet is a network trained from scratch that follows ResNet-v2 with leaky ReLUs and max-pooling layers; it has 5.00 M parameters and uses batches of P = 32 persons with K = 4 images each.

## Choosing the triplet formulation on LuNet

To keep test data out of model selection, a 150-person validation set was drawn from the MARS training set and the remaining 475 persons were used for training. These runs use LuNet on images downscaled by a factor of two and no data augmentation, so they explore formulations rather than top performance. With randomly sampled triplets at margin 0.1, the vanilla triplet loss reached 40.80 mAP and 59.23 rank-1, and offline hard mining produced unstable results across margins, with one run at margin 0.1 marked as trapped in a bad local optimum.

Offline mining also raised training time from 7 h to 20 h in the authors' experiments, because it runs as a non-parallelisable step.

At margin 0.1, Batch Hard reached 65.09 mAP and 83.51 rank-1, while Batch All reached 59.43 mAP and 79.24 rank-1 under the same margin. When only the non-zero loss terms are averaged, Batch All rises to 63.29 mAP at margin 0.1, but Batch Hard still performed better in most margin settings in the table. The lifted loss with one positive pair per triplet reached 61.95 mAP at margin 0.1, and the authors' multi-positive generalisation reached 64.00 mAP at margin 0.1.

The best cell is the soft-margin Batch Hard loss, with 65.77 mAP and 84.69 rank-1, and the authors use this loss in all later triplet experiments. Each cell in the table is a single value on one validation split, and the paper does not report seeds or variance for these runs.

## Comparison with published person ReID results

On Market-1501 single-query, TriNet reached 69.14 mAP and 84.92 rank-1, and on MARS it reached 67.70 mAP and 79.80 rank-1. All these scores include test-time augmentation. Under the same table, the authors' LuNet trained from scratch reached 60.71 mAP and 81.38 rank-1 on Market-1501 single-query and 60.48 mAP on MARS.

The largest gap in the table is to another ResNet-50 model trained with triplets, DTL, which reports 41.5 mAP in its embedding setting; the authors could not identify the reasons for this gap because DTL does not describe all its training details. The authors also trained a ResNet-50 with a classification loss, which they call IDE (R) ours and which uses XQDA as a metric learning step.

It reached 58.06 mAP on Market-1501 single-query, and it needed Adadelta because the loss spikes disrupted Adam.

With re-ranking, TriNet reached 81.07 mAP and 86.67 rank-1 on Market-1501 single-query. On CUHK03 under the labeled protocol, TriNet reached 89.63 rank-1 and 99.01 rank-5, and under the detected protocol 87.58 rank-1.

With 500k extra distractor images, the triplet-based model is reported to outperform the classification-based model by 8.4% mAP. In the distractor table, TriNet's mAP falls from 69.14 at 19 732 gallery images to 53.63 at 519 732 gallery images.

## Input size and pretrained weights

The pretrained ResNet-50 is designed for larger inputs, so the authors used 256×128 images to keep the aspect ratio, which meant upscaling Market-1501 images. Retraining TriNet at 128×64 reduces its Market-1501 mAP from 69.14 to 62.52, and at 64×32 it reaches 47.42 mAP.

LuNet, which is designed for its input size, reaches 60.71 mAP at 128×64 and 57.18 mAP at 64×32, a drop of about 3% from the larger scale.

## Test-time augmentation and combining embeddings

At test time each image yields five crops and their horizontal flips, and the ten embeddings are averaged to form the final embedding. On Market-1501, TriNet rises from 65.48 mAP with the original image alone to 69.14 mAP with five crops and flips, and the authors report that the triplet-trained network gains about 3% mAP while the identification network gains about 2% mAP.

The authors combine embeddings by their mean because a convex combination stays within the convex hull of positive points, whereas max-pooling can produce embeddings closer to negatives.

## Training behaviour under triplet losses

A training that collapses in this first phase is stuck because the embeddings never pass each other, and the authors observed this only with weak networks or with offline hard mining.

With hard-triplet mining, a flat loss curve does not show that training has stopped improving, because the network keeps meeting new hard cases, so the authors recommend tracking the fraction of active triplets, the embedding norms and the pairwise distances.

## Limitations

The distance choice rests on initial experiments, since no side-by-side comparison of the squared and non-squared Euclidean distances is reported. The best triplet variant was selected for person ReID only, and the paper does not claim it is best for image retrieval or clustering.

The variant comparison runs on one validation split of MARS, with LuNet on downscaled images and without augmentation. The main experiments cover Market-1501, MARS and CUHK03, and the authors report that weak architectures and offline hard mining can collapse during training.

## Paper info

- **Authors**: Alexander Hermans, Lucas Beyer, Bastian Leibe
- **Venue**: arXiv · Preprint
- **First published**: 2017-3-22
- **Added**: 2026-11-12
- **Updated**: 2017-11-21
- **Version**: v4
- **arXiv**: 1703.07737
- **Category**: cs.CV · cs.NE
- **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/1703.07737v4) · [PDF ↗](https://arxiv.org/pdf/1703.07737v4)

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

Alexander Hermans, Lucas Beyer, Bastian Leibe (2017). In Defense of the Triplet Loss for Person Re-Identification. arXiv:1703.07737v4. https://arxiv.org/abs/1703.07737v4

**BibTeX**

```
@misc{hermans2017defense,
  title = {{In Defense of the Triplet Loss for Person Re-Identification}},
  author = {Alexander Hermans and Lucas Beyer and Bastian Leibe},
  year = {2017},
  eprint = {1703.07737},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/1703.07737v4}
}
```

## Other paper commentary

- [Accelerating the Super-Resolution Convolutional Neural Network](https://refivu.com/en/papers/36219c92-ee60-4179-a5b4-065fdb8a7ff4-accelerating-the-super-resolution-convolutional-neural.md)
- [A Closer Look at Spatiotemporal Convolutions for Action Recognition](https://refivu.com/en/papers/2986e935-85a4-4ed6-b429-74af2338096c-a-closer-look-at-spatiotemporal-convolutions-for-action.md)
- [An Overview of Multi-Task Learning in Deep Neural Networks](https://refivu.com/en/papers/ec3f88d3-e942-4848-9ca0-597d43563c84-an-overview-of-multi-task-learning-in-deep.md)
- [FitNets: Hints for Thin Deep Nets](https://refivu.com/en/papers/1b4f0402-c689-4b22-8439-31aa101ca0fc-fitnets-hints-for-thin-deep-nets.md)
- [Temporal Fusion Transformers for Interpretable Multi-horizon Time Series Forecasting](https://refivu.com/en/papers/cb8f01c7-c9ff-43ea-879b-8d0eb97a6e96-temporal-fusion-transformers-for-interpretable-multi-horizon.md)
- [On Calibration of Modern Neural Networks](https://refivu.com/en/papers/49c54409-e306-4419-a26c-4569bedfbd40-on-calibration-of-modern-neural-networks.md)
- [SuperPoint: Self-Supervised Interest Point Detection and Description](https://refivu.com/en/papers/d0aa9e04-3220-432a-8074-02191fd86615-superpoint-self-supervised-interest-point-detection-and.md)
- [Improved Baselines with Momentum Contrastive Learning](https://refivu.com/en/papers/b3c4bdf4-000b-4115-9c61-4869e9e62ccc-improved-baselines-with-momentum-contrastive-learning.md)
- [OverFeat: Integrated Recognition, Localization and Detection using Convolutional Networks](https://refivu.com/en/papers/a615b23b-cb60-4fff-95a7-0a3b82dc2d4e-overfeat-integrated-recognition-localization-and-detection.md)
- [DeepSDF: Learning Continuous Signed Distance Functions for Shape Representation](https://refivu.com/en/papers/b9c76a95-d60f-4b38-98c6-45cfaa2bcd30-deepsdf-learning-continuous-signed-distance-functions-for.md)
- [Understanding deep learning requires rethinking generalization](https://refivu.com/en/papers/cb138997-32a3-4005-82f2-6597e2492ff8-understanding-deep-learning-requires-rethinking.md)
- [Random Erasing Data Augmentation](https://refivu.com/en/papers/4dd86d04-2086-4796-aa90-74b9d083d0ee-random-erasing-data-augmentation.md)

## Terms in this paper

- [mAP](https://refivu.com/en/terms/477dad058d88-map)
- [Adam optimizer](https://refivu.com/en/terms/aff9e901333e-adam-optimizer)
- [ResNet-50](https://refivu.com/en/terms/eb2323a60a89-resnet-50)
- [Triplet loss](https://refivu.com/en/terms/6b3cf5362b16-triplet-loss)
- [CMC](https://refivu.com/en/terms/2a31ae3aa9ed-cmc)
- [CUHK03](https://refivu.com/en/terms/30f86c51a562-cuhk03)
- [Euclidean distance](https://refivu.com/en/terms/d709f3cd41c0-euclidean-distance)
- [MARS](https://refivu.com/en/terms/658588248723-mars)
- [person ReID](https://refivu.com/en/terms/c497b6259a45-person-reid)

---

AI-written text can contain mistakes. [Refivu](https://refivu.com/en/papers/9a193d31-bb38-4b07-8752-1bc32882197d-in-defense-of-the-triplet-loss-for-person)
