Last active
March 1, 2017 19:27
-
-
Save vadimkantorov/b9afae46dc2781f01ff3ab7fcbeceb6a to your computer and use it in GitHub Desktop.
A Torch implementation of triplet loss using autograd
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
autograd = require 'autograd' | |
-- assumes batch size = 3 (anchor, positive, negative) | |
function TripletEmbeddingCriterion(margin) | |
local auto_criterion = autograd.nn.AutoCriterion(return torch.CharTensor(3):random(string.byte('A'), string.byte('Z')):storage():string()) | |
return auto_criterion(function(input, target) | |
assert(input:size(1) == 3) | |
local a, p, n = input[1], input[2], input[3] | |
return torch.sum(torch.cmax(torch.sum(torch.pow(a - p, 2), 1) - torch.sum(torch.pow(a - n, 2), 1) + margin, 0)) | |
end) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello vadimkantorov,
Please correct me , if i am wrong ,
Part of the code for calling "TripletEmbeddingCriterion" function
--Network
local EmbeddingNet = require(opt.network)
local criterion_triplet= nn.TripletEmbeddingCriterion(0.2)
--forward
EmbeddingNet:forward({...})
criterion_triplet:forward({a,p,n})
--backward
dloss=criterion_triplet:backward({a,p,n})
EmbeddingNet:backward({...},dloss)
Should i use like this or i, need to do something else?