Train with known triplets #695
-
Hi all! I feel like I am missing something obvious here, appreciate any guidance. I have a dataset that contains known image pairs. I want to train a model to minimise the cosine similarity between them. How should I set up my data loader and training loop? I think ideally I want to be able to specify the 3 images in the triplet or specify both the anchor positive and anchor negative pairs. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
Pairs or triplets are formed based on labels. So when you load a batch of image pairs, give each image in the pair the same label. For example, let's say you have a batch of 4 images, where images 0 and 1 are a pair and images 2 and 3 are a pair: from pytorch_metric_learning.losses import ContrastiveLoss
loss_fn = ContrastiveLoss()
embeddings = model(images)
labels = torch.tensor([0,0,1,1])
loss = loss_fn(embeddings, labels) If each image in each batch has exactly 1 positive, then you can accomplish the same thing with SelfSupervisedLoss without creating labels: from pytorch_metric_learning.losses import ContrastiveLoss, SelfSupervisedLoss
loss_fn = SelfSupervisedLoss(ContrastiveLoss())
anchor_embs = model(anchors)
positive_embs = model(positives)
loss = loss_fn(anchor_embs, positive_embs) |
Beta Was this translation helpful? Give feedback.
Pairs or triplets are formed based on labels. So when you load a batch of image pairs, give each image in the pair the same label.
For example, let's say you have a batch of 4 images, where images 0 and 1 are a pair and images 2 and 3 are a pair:
If each image in each batch has exactly 1 positive, then you can accomplish the same thing with SelfSupervisedLoss without creating labels: