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

How do I use a ByteTensor in a contrastive cosine loss function?

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

我按如下方式实现了损失:

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() returns 是一个 ByteTensor,但是如果我试图用 torch.Tensor.float() 将它强制转换为 FloatTensor,我会得到 AttributeError: module 'torch.autograd.variable' has no attribute 'FloatTensor'.

我真的不知道从这里到哪里去。在余弦相似度张量和基于小于规则的 0 或 1 张量之间进行逐元素乘法对我来说似乎是合乎逻辑的。

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

我知道这个问题有时间,但是我来这里是为了寻找如何在对比中使用"cosine similarity"损失。 他们在文章中公开的公式对我来说似乎不正确。

如果你看一下公式13的运算符“<”,文章图(2)中的Ew < m 永远不会发生。我认为等式 13 如下:

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

等价于图 2 (m=0.4) 的方程图: Correct (13) equation