Negative sampling
Quick answer
Negative sampling selects examples that should not match an anchor, reducing the cost of metric learning or contrastive objectives. The sampling distribution changes the training signal. Examples are static Python snippets tested locally on CPU; PyTorch is required for selected examples. ByteMind execution is unverified.
Negative types
dp,m=4,3print(["hard" if d<dp else "tie" if d==dp else "semi-hard" if d<dp+m else "easy" for d in [2,4,5,7,10]])Expected output (locally tested): ['hard', 'tie', 'semi-hard', 'easy', 'easy']. Boundary equality at the margin is easy and gives zero loss.
How it works
An easy negative already satisfies a margin; a hard negative is closer than the positive; a semi-hard negative is farther than the positive but inside the margin. For squared distances d_p,d_n and margin m, use strict d_n<d_p for hard, d_p<d_n<d_p+m for semi-hard, and d_n>=d_p+m for easy; ties d_n=d_p can be tracked separately. Definitions vary across implementations. Random negatives are inexpensive but may be too easy. Mining within a batch is efficient but depends on batch composition. Very hard negatives can be mislabeled or ambiguous, and false negatives push similar items apart. Reject same-identity candidates, duplicates and known positives before selecting. In a contrastive softmax objective the temperature controls logit scale; more negatives change the normalization and can change loss even at fixed similarity. Log sampling policy, random seed, candidate pool and exclusions. Use training-only mining; do not pull validation or test identities into the pool. Evaluate retrieval on a representative fixed gallery rather than sampled negatives alone.
Exclude known positives
anchor="a"known={"a","b"}pool=[("b",1),("c",3),("d",2),("a",0)]print(min((dist,key) for key,dist in pool if key not in known))Expected output (locally tested): (2, 'd'). The nearest eligible negative is d; known positives and self are excluded.
Common mistakes
Do not equate every different record with a true negative. Do not sample from held-out identities during training or compare losses with different negative pool sizes as though identical.
Practice and next steps
Given positive squared distance 4 and margin 3, classify negative distances 2, 4, 5, 7 and 10 using the stated boundaries. Explain which candidates give a nonzero triplet loss.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Negative sampling — knowledge check
Apply negative sampling to small examples and debugging scenarios.
Why exclude known positives from the negative pool?
For dp=4 and margin=3, which is semi-hard?
What changes if batch composition changes?
Why not mine test identities?
What does temperature change in contrastive softmax?