AI Logic

Loss Functions

Contrastive Loss

Updated:

Graph of Contrastive Loss. The horizontal axis is the distance D_W between the two outputs and the vertical axis is the loss, overlaying the loss for dissimilar pairs, ½{max(0, m − D_W)}² (solid line), and the loss for similar pairs, ½D_W² (dashed line). In this example with margin m = 1.25, the dissimilar-pair loss is ½m² ≈ 0.78 at distance 0 and becomes 0 for distances of m or more. A legend is on the right

Background and overview

Contrastive Loss is a loss function that learns a mapping from pairs of data points and "similar or dissimilar" labels, placing similar pairs close together and dissimilar pairs far apart. Hadsell, Chopra, and LeCun (2006) proposed it as part of DrLIM, a dimensionality reduction method that maps high-dimensional data to a low-dimensional space.

A pair (X⃗1, X⃗2)(\vec{X}_1,\ \vec{X}_2) is passed through the same network GWG_W, and the output distance is DW=∥GW(X⃗1)−GW(X⃗2)∥2D_W = \lVert G_W(\vec{X}_1) - G_W(\vec{X}_2) \rVert_2. The label YY is 00 for a similar pair and 11 for a dissimilar pair. The loss is

L(W,Y,X⃗1,X⃗2)=(1−Y) 12(DW)2+Y 12{max⁡(0, m−DW)}2L(W, Y, \vec{X}_1, \vec{X}_2) = (1 - Y)\,\frac{1}{2} (D_W)^2 + Y\,\frac{1}{2} \bigl\{ \max(0,\ m - D_W) \bigr\}^2

where m>0m > 0 is the margin. As the figure at the top shows, similar pairs (dashed line) incur a loss until their distance reaches 0, while dissimilar pairs (solid line) incur a loss only when their distance is less than mm.

The paper points out two weaknesses in earlier dimensionality reduction methods. First, they assume that a meaningful distance can be computed in the input space. Second, they do not provide a function that maps new data not used in training. DrLIM, which uses Contrastive Loss, learns only from neighborhood relations, that is, which data points are similar to which, and the trained network maps new data directly. The neighborhood relations may come from information unrelated to input distances, such as prior knowledge, manual labels, or closeness in capture time.

Theory (how the loss is computed)

The paper's algorithm trains in the following steps.

  1. For each training sample, use prior knowledge to decide the set of samples that are "similar" to it.
  2. Pair each sample with every other sample, labeling the pair Y=0Y = 0 if the other sample is in the similar set and Y=1Y = 1 otherwise. The number of pairs can be up to the square of the number of samples.
  3. Pass the two samples of a pair through two identical networks that share weights (a Siamese network) and compute the output distance DWD_W.
  4. Depending on YY, use 12DW2\frac{1}{2}D_W^2 as the loss for a similar pair and 12{max⁡(0, m−DW)}2\frac{1}{2}\{\max(0,\ m - D_W)\}^2 for a dissimilar pair.
  5. Update the weights WW with stochastic gradient descent. The gradients from the two networks are summed and applied to the shared weights.

For example, with m=1m = 1, a similar pair at distance 0.50.5 has loss 12×0.52=0.125\frac{1}{2} \times 0.5^2 = 0.125. A dissimilar pair at distance 0.40.4 has loss 12×(1−0.4)2=0.18\frac{1}{2} \times (1 - 0.4)^2 = 0.18, and at distance 1.51.5 it is outside the margin, so the loss is 0.

The gradients with respect to the weights WW are

∂LS∂W=DW∂DW∂W,∂LD∂W={−(m−DW)∂DW∂W(DW<m)0(DW≥m)\frac{\partial L_S}{\partial W} = D_W \frac{\partial D_W}{\partial W}, \qquad \frac{\partial L_D}{\partial W} = \begin{cases} -(m - D_W) \dfrac{\partial D_W}{\partial W} & (D_W < m) \\ 0 & (D_W \ge m) \end{cases}

LSL_S is the loss for similar pairs and LDL_D the loss for dissimilar pairs. Similar pairs are pulled together by a force proportional to their distance; dissimilar pairs are pushed apart more strongly the closer they are, and the force vanishes once the distance reaches mm.

The dissimilar-pair loss is the square of the same max⁡(0, ⋅ )\max(0,\ \cdot\,) form as the hinge loss. Pairs that are already far enough apart produce no gradient, so learning focuses only on "dissimilar pairs that are too close."

Why the dissimilar-pair term is needed

The key point of Contrastive Loss is that a term that only pulls similar pairs together breaks learning. If only the distance DWD_W of similar pairs is minimized, the network GWG_W can output the same value for every input, making every distance 0 and the loss 0. Nothing can then be distinguished (a collapsed solution). The paper states that the contrastive term, which pushes dissimilar pairs apart, is essential.

The paper explains this loss with an analogy to springs.

  • Similar pairs are connected by springs with rest length 0: If they are apart at all, they attract each other with a force proportional to the distance (gradient DW∂DW∂WD_W \frac{\partial D_W}{\partial W}).
  • Dissimilar pairs are connected by push-only springs with rest length mm: If the distance is shorter than mm, they push apart, with the force largest at distance 0. Stretched beyond mm, no force pulls them back.

Each point is connected to its similar points by attracting springs and to its dissimilar points by pushing springs. Moving closer to one similar point can mean moving away from another, and the configuration settles where all spring forces balance. The paper explains that this keeps the points from clumping in one place and spreads them evenly over the output space.

The margin mm exists because dissimilar pairs do not need to be pushed infinitely far apart; "once far enough, stop caring." Limiting the reach of the pushing force to a radius mm means the large majority of dissimilar pairs that are already apart no longer affect learning.

Experimental results

The paper's experiments show the effect not with accuracy numbers but with plots of the learned low-dimensional configurations. The main settings and results are as follows.

ExperimentData and pair constructionNetwork GWG_W and outputResult
MNIST 4s and 9s3,000 images each of 4 and 9. Each image's 5 nearest neighbors in pixel distance form similar pairs; all others are dissimilar pairs (30,000 similar pairs, about 18 million dissimilar pairs)Convolutional network, 2-DTest images were laid out evenly on the 2-D plane, mainly along the slant of the digits
Horizontally shifted MNISTAdd the images above shifted by −6, −3, 3, and 6 pixels (30,000 images in total). Each image and its shifted versions also form similar pairsSame as aboveThe shifted versions clustered in nearly the same place, giving a configuration invariant to shifts. LLE, given the same neighborhood relations, split by shift
NORB airplane images972 images of one airplane at 18 azimuths × 9 elevations × 6 lightings (660 for training, 312 for testing). Images adjacent in azimuth or elevation, regardless of lighting, form similar pairs (10,989 similar pairs, 206,481 dissimilar pairs)2 fully connected layers (20 hidden units, 3 outputs), 3-DA cylinder formed, with the circumference corresponding to azimuth and the height to elevation, completely unaffected by lighting. LLE's configuration split by lighting

In the third experiment, although only local relations (adjacent images) were given, the learned 3-D configuration reproduces the global structure of the camera positions. It is an example of how building the prior knowledge "similar even under different lighting" into the choice of similar pairs yields a mapping invariant to lighting.

The experiments in this paper are qualitative, showing the learned configurations as plots; there are no numerical comparisons such as classification accuracy. The comparison with other dimensionality reduction methods is also mainly a visual comparison with LLE.

Practical considerations

The direction of the label YY may be reversed between the paper and implementations. The Hadsell et al. paper uses Y=0Y = 0 for similar pairs and Y=1Y = 1 for dissimilar pairs. Some implementations and libraries use 1 for similar pairs. Getting the direction wrong makes the model push similar pairs apart and pull dissimilar pairs together, so always check the convention of the implementation you use.

Keep the following points in mind as well.

  • Dissimilar pairs vastly outnumber similar ones: In the MNIST experiment there were about 18 million dissimilar pairs against 30,000 similar pairs. Using all of them is computationally expensive and tends to bias learning toward dissimilar pairs, so a common remedy is to balance the numbers of similar and dissimilar pairs in each mini-batch.
  • Set the margin mm to match the scale of output distances: Without output normalization, the scale of the distances changes with the scale of the outputs. If mm is too small, dissimilar pairs are ignored almost immediately; if too large, the pushing force never goes away.
  • PyTorch has no class that implements the paper's formula as is: It takes only a few lines to write. Passing distances to nn.HingeEmbeddingLoss gives a closely related, non-squared loss: DWD_W for similar pairs and max⁡(0, m−DW)\max(0,\ m - D_W) for dissimilar pairs (with labels 1 for similar pairs and −1 for dissimilar pairs).
  • The same name may refer to a different loss: In contrastive self-supervised learning (SimCLR and others), softmax-based losses that pick one positive pair out of many negatives (NT-Xent, InfoNCE, and others) are also called "contrastive loss." The loss in this article is the Hadsell et al. form, decided per pair by the distance and the margin.

Comparison with other methods

The table compares Contrastive Loss with related losses that learn distances, from the same viewpoints.

Loss functionData used per termRequirement for similar dataRequirement for dissimilar dataMain uses
Contrastive LossTwo samples (a pair) and a similar/dissimilar labelPull together to distance 0Push apart to distance mmDimensionality reduction, deciding whether two inputs are the same
Triplet LossThree samples (anchor, positive, negative)Closer than the negative by α\alpha is enoughFarther than the positive by α\alpha is enoughFace verification, image retrieval
Hinge lossOne sample and its class label (±1\pm 1)— (requires a margin on the classification score)—SVMs, binary classification

Rules of thumb for choosing:

  • If the only labels are "similar or dissimilar" for pairs, use Contrastive Loss: It learns from pairwise relations alone, with no need to assemble data of the same kind into triplets.
  • If data of the same kind should not collapse to a single point, consider Triplet Loss: The FaceNet paper states that a pairwise loss aiming at distance 0 tries to collapse all faces of one person to a single point, whereas Triplet Loss enforces only relative distances, so faces of the same person can spread out.
  • Either way, how pairs or triplets are chosen strongly affects the result: With only easy combinations whose loss is already 0, learning does not progress.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

# Eq. (4) of Hadsell et al. (2006). Labels as in the paper: Y = 0 for similar pairs, Y = 1 for dissimilar pairs
def contrastive_loss(out1, out2, y, margin=1.0):
    d = F.pairwise_distance(out1, out2)                 # D_W: Euclidean distance
    loss_similar = 0.5 * d.pow(2)                       # L_S = ½ D_W²
    loss_dissimilar = 0.5 * F.relu(margin - d).pow(2)   # L_D = ½ {max(0, m − D_W)}²
    return ((1 - y) * loss_similar + y * loss_dissimilar).mean()

# numerical example from the text (m = 1)
o1 = torch.tensor([[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]])
o2 = torch.tensor([[0.5, 0.0], [0.4, 0.0], [1.5, 0.0]])
y = torch.tensor([0.0, 1.0, 1.0])                       # similar, dissimilar, dissimilar
d = F.pairwise_distance(o1, o2)
print(((1 - y) * 0.5 * d ** 2 + y * 0.5 * F.relu(1.0 - d) ** 2))   # (0.125, 0.18, 0.0)

# Siamese network: pass two inputs through networks with the same weights
G = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 128), nn.ReLU(), nn.Linear(128, 2))   # map to 2-D
x1 = torch.randn(64, 1, 28, 28)
x2 = torch.randn(64, 1, 28, 28)
pair_label = torch.randint(0, 2, (64,)).float()         # 0: similar, 1: dissimilar
loss = contrastive_loss(G(x1), G(x2), pair_label, margin=1.0)
loss.backward()                                         # gradients from both inputs are summed into the shared weights

# Reference: passing distances to nn.HingeEmbeddingLoss gives a closely related, non-squared loss
# (labels 1: similar, −1: dissimilar; D for similar pairs, max(0, margin − D) for dissimilar pairs)
dist = F.pairwise_distance(G(x1), G(x2))
hinge_label = 1 - 2 * pair_label                         # 0 → 1, 1 → −1
loss2 = nn.HingeEmbeddingLoss(margin=1.0)(dist, hinge_label)

FAQ

Q. Can the model be trained with similar pairs only?
A.

No. If only the distances of similar pairs are reduced, the loss becomes 0 as soon as the network outputs the same value for every input (collapse). The term that pushes dissimilar pairs apart to distance mm keeps the outputs from clumping in one place and spreads them out.

Q. What value should the margin m be?
A.

There is no fixed value; set it to match the scale of output distances. Without a constraint on the output scale, the scale of distances changes too, so normalizing the outputs before choosing mm makes it easier to handle. Tune it on validation data while looking at the distribution of distances of dissimilar pairs.

Q. Is it the same as the loss used in contrastive learning such as SimCLR?
A.

The idea (comparing what to pull together with what to push apart) is shared, but the formulas differ. The loss in this article is decided per pair by the distance and the margin. Losses such as NT-Xent, used by SimCLR, take a softmax form that picks the correct pair out of many negatives.

References

  1. R. Hadsell, S. Chopra, and Y. LeCun, "Dimensionality Reduction by Learning an Invariant Mapping," CVPR, 2006.
  2. F. Schroff, D. Kalenichenko, and J. Philbin, "FaceNet: A Unified Embedding for Face Recognition and Clustering," CVPR, 2015.
  3. PyTorch Documentation, "torch.nn.HingeEmbeddingLoss."