# ArcFace/AAMLoss实现详解

2020/11/27 15:50

ArcFace/AAMLoss实现详解：

## Arcface 的 PyTorch 实现

    # implementation of additive margin softmax loss in https://arxiv.org/abs/1801.05599
def __init__(self, embedding_size=512, classnum=51332,  s=64., m=0.5):
super(Arcface, self).__init__()
self.classnum = classnum
self.kernel = Parameter(torch.Tensor(embedding_size,classnum))
# initial kernel
self.kernel.data.uniform_(-1, 1).renorm_(2,1,1e-5).mul_(1e5)
self.m = m # the margin value, default is 0.5
self.s = s # scalar value default is 64, see normface https://arxiv.org/abs/1704.06369
self.cos_m = math.cos(m)
self.sin_m = math.sin(m)
self.mm = self.sin_m * m  # issue 1
self.threshold = math.cos(math.pi - m)


l2_norm 会求导吗？

        # weights norm
nB = len(embbedings)
kernel_norm = l2_norm(self.kernel,axis=0)

• torch.mm 执行矩阵mat1mat2的矩阵乘法。
torch.clamp 将输入中的所有元素夹在[minmax]范围内并返回结果张量：

如果输入的类型为FloatTensorDoubleTensor，则 args minmax必须是实数，否则它们应该是整数。

        # cos(theta+m)
cos_theta = torch.mm(embbedings,kernel_norm)
# output = torch.mm(embbedings,kernel_norm)
cos_theta = cos_theta.clamp(-1,1) # for numerical stability
cos_theta_2 = torch.pow(cos_theta, 2)
sin_theta_2 = 1 - cos_theta_2
sin_theta = torch.sqrt(sin_theta_2)
cos_theta_m = (cos_theta * self.cos_m - sin_theta * self.sin_m)


# this condition controls the theta+m should in range [0, pi]
#      0<=theta+m<=pi
#     -m<=theta<=pi-m
cond_v = cos_theta - self.threshold
cond_mask = cond_v <= 0
keep_val = (cos_theta - self.mm) # when theta not in [0,pi], use cosface instead
output = cos_theta * 1.0 # a little bit hacky way to prevent in_place operation on cos_theta
idx_ = torch.arange(0, nB, dtype=torch.long)
output[idx_, label] = cos_theta_m[idx_, label]
output *= self.s # scale up in order to make softmax work, first introduced in normface
return output

def l2_norm(input,axis=1):
norm = torch.norm(input,2,axis,True)
output = torch.div(input, norm)
return output


0
0 收藏

0 评论
0 收藏
0