解析人脸识别中cosface和arcface(insightface)的损失函数以及源码

人脸识别最近几年的发展,几乎就两条,第一是面向移动设备,第二,改进损失函数,使训练的模型更加有效。这就要求loss能push各个类内在空间分布的更紧凑。从normface开始,人脸识别就进入使用余弦相似度来判断识别精度的时代。对weight和feature都进行l2 norm,避免长尾,使样本不均衡不再制约精度。

在center loss中,指明softMax-based loss将特征空间呈原点发散状。这样可以通过计算两个样本在特征空间的向量夹角大小进行人脸验证。夹脚过小则说明两个样本属于同一类别。后来的normface sphereface 这些工作,继承A-softmax, L2softMax, Am-softmax等工作,尽可能的将样本分在超球面上,同时拉开类间的夹角,使得类内更加紧凑。

接下来,我将简单介绍cosface和arcface各自的损失函数以及对应的pytorch代码。

CosFace

l o s s c o s = 1 N i ∑ i − l o g e s ( c o s ( θ y i , i ) − m ) e s ( c o s ( θ y i , i ) − m ) + ∑ j ≠ y i e s c o s ( θ j , i ) loss_{cos}=\frac{1}{N_i} \sum_i -log\frac{e^{s(cos(\theta_{y_i,i})-m)}}{e^{s(cos(\theta_{y_i,i})-m)}+\sum_{j≠y_i}e^{scos(\theta_{j,i})}} losscos=Ni1iloges(cos(θyi,i)m)+j=yiescos(θj,i)es(cos(θyi,i)m)

cosface loss的设计思路是通过在余弦空间上减去一个正值,使得在0- π \pi π这个单调区间上, c o s ( θ y i , i ) − m cos(\theta_{y_i,i})-m cos(θyi,i)m更小,则等效 θ y i , i \theta_{y_i,i} θyi,i更大,说明样本与自己的类中心夹角过大。m的作用就是提高了样本的训练环境。待loss收敛时候, θ \theta θ就会更加小,则类内更加聚拢。
在这里插入图片描述

代码解读

class AddMarginProduct(nn.Module):
    r"""Implement of large margin cosine distance: :
    Args:
        in_features: size of each input sample
        out_features: size of each output sample
        s: norm of input feature
        m: margin
        cos(theta) - m
    """

    def __init__(self, in_features, out_features, s=30.0, m=0.40):
        super(AddMarginProduct, self).__init__()
        self.in_features = in_features
        self。.out_features = out_features
        self.s = s
        self.m = m
        self.weight = Parameter(torch.FloatTensor(out_features, in_features))
        nn.init.xavier_uniform_(self.weight)

    def forward(self, input, label):
        # --------------------------- cos(theta) & phi(theta) ---------------------------
        cosine = F.linear(F.normalize(input), F.normalize(self.weight))
        phi = cosine - self.m
        # --------------------------- convert label to one-hot ---------------------------
        one_hot = torch.zeros(cosine.size(), device='cuda')
        # one_hot = one_hot.cuda() if cosine.is_cuda else one_hot
        one_hot.scatter_(1, label.view(-1, 1).long(), 1)
        # -------------torch.where(out_i = {x_i if condition_i else y_i) -------------
        output = (one_hot * phi) + ((1.0 - one_hot) * cosine)
        # you can use torch.where if your torch.__version__ is 0.4
        output *= self.s
        # print(output)

        return output

    def __repr__(self):
        return self.__class__.__name__ + '(' \
               + 'in_features=' + str(self.in_features) \
               + ', out_features=' + str(self.out_features) \
               + ', s=' + str(self.s) \
               + ', m=' + str(self.m) + ')'

直接看forward部分,先把feature和weight用l2 norm 归一化。然后两个矩阵相乘,就得到cos值了。因为范数为1了。
接下来减去m,然后通过onehot的label,挑选出需要减去m的样本,保留其他位置的cos值,最后乘一个s,返回,送入交叉墒中就可以了。

ArcFace

因为arcface和虹软的一款人脸识别重名了。
形式如下:
l o s s a r c = 1 N i ∑ i − l o g e s ( c o s ( θ y i , i + m ) ) e s ( c o s ( θ y i , i + m ) ) + ∑ j ≠ y i e s ( c o s ( θ j , i ) ) loss_{arc}=\frac{1}{N_i}\sum_i -log\frac{e^{s(cos(\theta_{y_i,i}+m))}}{e^{s(cos(\theta_{y_i,i}+m))}+\sum_{j≠y_i} e^{s(cos(\theta_{j,i}))}} lossarc=Ni1iloges(cos(θyi,i+m))+j=yies(cos(θj,i))es(cos(θyi,i+m))
arc loss的出发点是,从反余弦空间优化类间距离,通过在夹角上加个m,使得cos值在0- π \pi π单调区间上值更小。

在这里插入图片描述

代码解读

class ArcMarginProduct(nn.Module):
    r"""Implement of large margin arc distance: :
        Args:
            in_features: size of each input sample
            out_features: size of each output sample
            s: norm of input feature
            m: margin
            cos(theta + m)
        """

    def __init__(self, in_features, out_features, s=30.0, m=0.50, easy_margin=False):
        super(ArcMarginProduct, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.s = s
        self.m = m
        self.weight = Parameter(torch.FloatTensor(out_features, in_features))
        nn.init.xavier_uniform_(self.weight)

        self.easy_margin = easy_margin
        self.cos_m = math.cos(m)
        self.sin_m = math.sin(m)
        self.th = math.cos(math.pi - m)
        self.mm = math.sin(math.pi - m) * m

    def forward(self, input, label):
        cosine = F.linear(F.normalize(input), F.normalize(self.weight))
        sine = torch.sqrt(1.0 - torch.pow(cosine, 2))
        # cos(a+b)=cos(a)*cos(b)-size(a)*sin(b)
        phi = cosine * self.cos_m - sine * self.sin_m
        if self.easy_margin:
            phi = torch.where(cosine > 0, phi, cosine)
        else:
            phi = torch.where(cosine > self.th, phi, cosine - self.mm)
        one_hot = torch.zeros(cosine.size(), device='cuda')
        one_hot.scatter_(1, label.view(-1, 1).long(), 1)
        output = (one_hot * phi) + ((1.0 - one_hot) * cosine)
        output *= self.s
        return output

这里m的是一个弧度值角度,实验设置为0.5
代码唯一造成困惑的地方可能就是easy margin那里,如果easy margin为true,只要夹角小于90度,这才再角度上加一个m。如果为false,以self.th为阈值,大家可以画下图,如果角度值theta小于m,在单调区间0-pi上,余弦值一定大于该阈值。所以th的作用就是保证了theta加m,依然在单调区间0-pi上。

  • 7
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是基于PyTorch的ArcFace人脸识别系统包含ArcFace函数的models.py文件的代码: ```python import torch import torch.nn as nn import torch.nn.functional as F class ArcFace(nn.Module): def __init__(self, embedding_size, num_classes, margin=0.5, scale=64): super().__init__() self.embedding_size = embedding_size self.num_classes = num_classes self.margin = margin self.scale = scale self.weight = nn.Parameter(torch.FloatTensor(num_classes, embedding_size)) nn.init.xavier_uniform_(self.weight) def forward(self, embeddings, labels): # normalize input embeddings embeddings = F.normalize(embeddings) # normalize weights weights = F.normalize(self.weight) # gather the correct weight for each label cosine = F.linear(embeddings, weights) logits = self.scale*cosine # add margin to the correct logit mask = F.one_hot(labels, self.num_classes) logits[mask.bool()] -= self.margin # softmax cross-entropy loss loss = F.cross_entropy(logits, labels) return loss ``` 该代码实现了一个名为ArcFace的类,它是一个PyTorch模块,可以用于训练人脸识别模型。该类的构造函数接受几个参数:embedding_size表示每个人脸图像嵌入的向量大小,num_classes表示人脸库的人数,margin表示ArcFace的余弦相似度边界,scale表示每次前向传递时对余弦相似度的缩放因子。 该类的forward()方法接受两个参数:embeddings表示一个大小为(batch_size, embedding_size)的张量,其包含了一批人脸图像的嵌入向量;labels表示一个大小为(batch_size,)的张量,其包含了每个嵌入向量对应的人脸ID。该方法首先将嵌入向量和权重向量归一化,然后使用余弦相似度计算输入向量和权重向量之间的相似度得分。然后,对于每个嵌入向量,它的相似度得分被缩放(scale)和减去一个边界(margin),以获得最终的logit。最后,使用softmax交叉熵损失函数计算损失。 该模型的训练过程通常是使用随机梯度下降(SGD)优化器来最小化损失函数。在每个训练步骤,模型首先将输入图像传递到卷积神经网络,然后将得到的嵌入向量传递给ArcFace模块进行训练。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值