• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

人脸识别ArcFace损失函数

相关文章 海叔叔 4年前 (2021-11-18) 76次浏览 已收录 0个评论

技术标签: 深度学习 pytorch 神经网络

人脸识别ArcFace损失函数(代码)

# 实现方式1
class ArcLoss1(nn.Module):
	def __init__(self, class_num, feature_num, s=10, m=0.1):
		super().__init__()
		self.class_num = class_num
		self.feature_num = feature_num
		self.s = s
		self.m = torch.tensor(m)
		self.w = nn.Parameter(torch.rand(feature_num, class_num))  # 2*10

	def forward(self, feature):
		feature = F.normalize(feature, dim=1)  # 128*2
		w = F.normalize(self.w, dim=0)  # 2*10
		cos_theat = torch.matmul(feature, w) / 10
		sin_theat = torch.sqrt(1.0 - torch.pow(cos_theat, 2))
		cos_theat_m = cos_theat * torch.cos(self.m) - sin_theat * torch.sin(self.m)
		cos_theat_ = torch.exp(cos_theat * self.s)
		sum_cos_theat = torch.sum(torch.exp(cos_theat * self.s), dim=1, keepdim=True) - cos_theat_
		top = torch.exp(cos_theat_m * self.s)
		divide = (top / (top + sum_cos_theat))
		return divide

# 实现方式2
class ArcLoss2(nn.Module):
	def __init__(self, feature_dim=2, cls_dim=10):
		super().__init__()
		self.W = nn.Parameter(torch.randn(feature_dim, cls_dim))

	def forward(self, feature, m=1, s=10):
		x = F.normalize(feature, dim=1)
		w = F.normalize(self.W, dim=0)
		cos = torch.matmul(x, w)/10
		a = torch.acos(cos)
		top = torch.exp(s*torch.cos(a+m))
		down2 = torch.sum(torch.exp(s*torch.cos(a)), dim=1, keepdim=True)-torch.exp(s*torch.cos(a))
		out = torch.log(top/(top+down2))
		return out

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:人脸识别ArcFace损失函数
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址