Contrastive Loss: Formula, Margin and Free Calculator

Contrastive loss trains a network to place similar items close together and dissimilar items at least a margin apart in an embedding space. This page gives the formula, a calculator that works from a distance or from two vectors, a worked example with real numbers, and a comparison with triplet loss.

What is contrastive loss?

It is a loss on pairs of inputs. A network \( f \) turns each input into an embedding vector, and the loss looks at the Euclidean distance between the two embeddings:

\[ D = \lVert f(x_1) – f(x_2) \rVert_2 \]

Each pair carries a label \( y \): \( y = 1 \) if the two items are similar (same person, same class) and \( y = 0 \) if they are not. With a margin \( m > 0 \), the loss for one pair is:

\[ L(D, y) = y \cdot \tfrac{1}{2} D^2 \;+\; (1 – y) \cdot \tfrac{1}{2} \max(0,\, m – D)^2 \]

Read it as two rules. A similar pair is penalised for any distance at all, so the network pulls it together. A dissimilar pair is penalised only while it sits closer than \( m \); once \( D \ge m \), its loss is exactly 0 and it stops pushing on the weights. The margin stops the network from wasting effort pushing apart pairs that are already well separated.

The formula comes from Hadsell, Chopra and LeCun, Dimensionality Reduction by Learning an Invariant Mapping (CVPR 2006); see the Siamese network overview on Wikipedia. Note one difference: the paper labels similar pairs \( Y = 0 \) and dissimilar pairs \( Y = 1 \). Many tutorials and libraries flip this, as this page does. The maths is the same; only the label meaning changes, so always check which convention your code uses.

contrastive loss chart

Contrastive loss calculator

Enter a distance directly, or paste two embedding vectors and let the calculator find the Euclidean distance. Choose whether the pair is similar or dissimilar and set the margin.

L = —Press the button to see the working.
Distance D—
Branch used—
Gradient dL/dD—
Inside margin?—
similar pair (y = 1)dissimilar pair (y = 0)your pair
Example loaded. Press Calculate.

Worked example with real numbers

Take two 2-dimensional embeddings, \( a = (1, 2) \) and \( b = (1.6, 2.8) \), and a margin \( m = 1.5 \). These are the calculator's defaults.

Step 1: the distance. The differences are 0.6 and 0.8, so

\[ D = \sqrt{0.6^2 + 0.8^2} = \sqrt{0.36 + 0.64} = \sqrt{1} = 1 \]

This is the L2 vector norm of \( a - b \).

Step 2a: if the pair is similar (\( y = 1 \)). Only the first term is active: \( L = \tfrac12 \times 1^2 = 0.5 \). The gradient with respect to \( D \) is \( D = 1 \), so the network is told to shrink the distance.

Step 2b: if the pair is dissimilar (\( y = 0 \)). Only the second term is active: \( L = \tfrac12 \times \max(0,\, 1.5 - 1)^2 = \tfrac12 \times 0.25 = 0.125 \). The pair is inside the margin, so it still costs something, and the gradient \( -(m - D) = -0.5 \) says "increase the distance".

Step 3: after some training. Suppose the dissimilar pair has moved to \( D = 1.8 \). Now \( m - D = -0.3 \), the max clips it to 0, and the loss is 0. Press "Dissimilar pair beyond the margin" in the calculator to check this.

The same distance therefore gives a loss of 0.5 or 0.125 depending only on the label. That is the core idea: the label decides whether distance is good or bad.

When to use it, and when not to

Use contrastive loss when what you need is a distance that means something, rather than a fixed set of class scores:

  • Verification: "are these two signatures, faces or fingerprints from the same source?" A Siamese network (two copies of one network with shared weights) produces the two embeddings; see Siamese neural network on Wikipedia.
  • Open sets: new people or products appear after training. You compare embeddings instead of retraining a classifier.
  • Retrieval and search: find nearest items with k-nearest neighbours in the learned space, as in recommender systems.
  • Only pair labels are available: you know which items match but have no class names.

Avoid it when you have a fixed, small set of classes and plenty of labelled data: ordinary cross-entropy loss is simpler and usually works well. It is also a poor fit if you cannot build sensible pairs, because the number of possible pairs grows with the square of the dataset size and most random dissimilar pairs are already beyond the margin, giving zero loss and no learning signal.

Contrastive loss vs triplet loss

The closest alternative is triplet loss, which compares an anchor with one positive and one negative at the same time instead of looking at one pair.

Pairwise contrastiveTriplet
Input unitPair \( (x_1, x_2) \) plus labelAnchor, positive, negative
Formula\( y\tfrac12 D^2 + (1-y)\tfrac12\max(0, m-D)^2 \)\( \max(0,\, D_{ap} - D_{an} + m) \)
What the margin meansAbsolute: negatives must be at least \( m \) awayRelative: negative must be \( m \) further than the positive
Similar pairsPulled all the way towards distance 0Only need to be closer than the negative
Data neededPair labelsTriplets (often mined from class labels)
Typical useVerification, dimensionality reductionFace recognition, ranking

Triplet loss is more flexible because it only cares about relative order, which suits ranking. The pairwise version is easier to set up and reason about. Both are close relatives of hinge loss, since they use the same \( \max(0, \cdot) \) clipping. For an overview of other objectives, see the loss functions guide.

Common mistakes

  • Mixing up the label convention. The original paper uses \( Y = 0 \) for similar pairs. If your code uses the opposite, the network pushes matching pairs apart. Check one similar pair by hand.
  • Using squared distance in the margin term. The second term is \( \max(0, m - D)^2 \) with \( D \) the plain distance, not \( D^2 \). Swapping them changes what the margin means.
  • A margin that does not fit the scale. If embeddings are L2-normalised, distances lie between 0 and 2, so a margin of 5 means every dissimilar pair is always penalised. Pick \( m \) relative to the typical distances you see.
  • NaN gradients at zero distance. The derivative of \( \sqrt{s} \) blows up at \( s = 0 \), which happens for identical embeddings. Add a small epsilon inside the square root.
  • Too many easy negatives. Random dissimilar pairs are usually far apart and contribute nothing. Balance positives and negatives, and sample harder negatives, much as you would with imbalanced datasets.
  • Confusing it with cosine similarity. This loss uses Euclidean distance. If you prefer angles, the cosine similarity calculator shows a different measure that needs a different loss.

Training itself is standard: the loss is differentiable almost everywhere, so backpropagation and gradient descent work as usual.

Frequently asked questions

What does the margin do?

It sets how far apart dissimilar pairs must be before they stop adding loss. Pairs at distance \( D \ge m \) cost nothing, so the network can focus on pairs that are still too close. There is no universal default; it depends on the scale of your embeddings.

Why is there a factor of one half?

Hadsell et al. include \( \tfrac12 \) so that the derivative of \( \tfrac12 D^2 \) is simply \( D \). Some implementations drop it. That scales the loss by 2 but does not change where the minimum is.

Is this the same as the loss in SimCLR?

No. SimCLR and similar self-supervised methods use a softmax-based loss over many negatives at once, often called InfoNCE or NT-Xent. It is sometimes also called a contrastive loss, but the formula is different from the pairwise margin version on this page.

Can the loss be negative?

No. Both terms are a half times a squared quantity, so each pair contributes 0 or more. The minimum of 0 is reached when similar pairs sit at distance 0 and dissimilar pairs are at least the margin apart.

How do I compute it for a batch?

Compute the loss for every pair with the formula above and take the mean. That is what most implementations return by default.

Scroll to Top