Contrastive Loss: Pull Together, Push Apart

Loss FunctionsMedium+20 XP+15

Contrastive Loss: Pull Together, Push Apart

Contrastive loss trains an embedding space rather than a classifier. It takes pairs and pulls similar ones together while pushing dissimilar ones apart — but only up to a point.

For a pair at embedding distance d, with y = 1 meaning similar and y = 0 meaning dissimilar:

1loss = y * d² + (1 - y) * max(0, margin - d)²

Task: write contrastive_loss(distances, labels, margin) returning the mean loss, rounded to 4 decimal places.

  • Similar pairs pay d² — the cost grows without limit the further apart they drift.
  • Dissimilar pairs pay only while they're closer than margin. Once past it they cost nothing.

Without the margin, the loss would reward pushing dissimilar pairs infinitely far apart and the embedding would just explode. Capping it at a fixed radius says "far enough is far enough", which is what keeps the space bounded and the geometry meaningful.

Examples

distances = [0.5, 2.0]
labels = [1, 0]
margin = 1.0
returns 0.125
distances = [0.0, 3.0]
labels = [1, 0]
margin = 2.0
returns 0.0

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run