Mockbit/#90
MLhardLoss functions~10m

Triplet Margin Loss Implementation

Problem

Implement triplet margin loss using only NumPy. Given anchor, positive, and negative embeddings, compute the loss that encourages the distance between anchor-positive pairs to be smaller than anchor-negative pairs by at least a margin, with L2 distance and numerical stability for zero gradients.

Examples

Example 1

Input: anchor=[[1.0, 0.0]], positive=[[0.8, 0.2]], negative=[[0.2, 0.8]], margin=0.5
Output: 0.0

Computes max(0, d(a,p) - d(a,n) + margin) where d is L2 distance.

Constraints
  • NumPy only (import numpy as np)
  • Function must be named solution
Reference solution

Reference solution available after you attempt the question.

Ready to solve it?

Start a session on Mockbit #90. You'll get graded with specific critique when you submit.

Related ML questions
← Back homemockbit.io/q/90
PrivacyTerms© 2026 Mockbit