如何在对比余弦损失函数中使用ByteTensor?

时间:2017-11-04 05:02:34

标签: python neural-network deep-learning pytorch

我正在尝试在PyTorch中的http://anthology.aclweb.org/W16-1617中实现丢失函数。它显示如下:

enter image description here

我已将损失实施如下:

class CosineContrastiveLoss(nn.Module):
    """
    Cosine contrastive loss function.
    Based on: http://anthology.aclweb.org/W16-1617
    Maintain 0 for match, 1 for not match.
    If they match, loss is 1/4(1-cos_sim)^2.
    If they don't, it's cos_sim^2 if cos_sim < margin or 0 otherwise.
    Margin in the paper is ~0.4.
    """

    def __init__(self, margin=0.4):
        super(CosineContrastiveLoss, self).__init__()
        self.margin = margin

    def forward(self, output1, output2, label):
        cos_sim = F.cosine_similarity(output1, output2)
        loss_cos_con = torch.mean((1-label) * torch.div(torch.pow((1.0-cos_sim), 2), 4) +
                                    (label) * torch.pow(cos_sim * torch.lt(cos_sim, self.margin), 2))
        return loss_cos_con

然而,我收到一个错误说: TypeError: mul received an invalid combination of arguments - got (torch.cuda.ByteTensor), but expected one of: * (float value) didn't match because some of the arguments have invalid types: (torch.cuda.ByteTensor) * (torch.cuda.FloatTensor other) didn't match because some of the arguments have invalid types: (torch.cuda.ByteTensor)

我知道torch.lt()会返回一个ByteTensor,但如果我尝试将其强制转换为带有torch.Tensor.float()的FloatTensor,我会得到AttributeError: module 'torch.autograd.variable' has no attribute 'FloatTensor'

我真的不确定从哪里开始。对于我来说,基于小于规则在余弦相似性张量和基于0或1的张量之间进行元素乘法似乎是合乎逻辑的。

2 个答案:

答案 0 :(得分:1)

也许你可以直接在变量上尝试float()方法? 变量(torch.zeros(5))。float() - 适用于我,例如

答案 1 :(得分:0)

我知道这个问题有时间,但是我和很多人一起来找到如何使用&#34;余弦相似性&#34;在对比损失。 他们在文章中公开的公式对我来说似乎不正确。

如果你看看运营商&#34;&lt;&#34;式13的结果,Ew&lt;文章图(2)中的m永远不会发生。我认为等式13如下:

enter image description here

文章的等式(13)的图(它看起来不像图2): Wrong (13) equation

等效于图2(m = 0.4)的等式的图: Correct (13) equation