前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用Pytorch实现三元组损失

使用Pytorch实现三元组损失

作者头像
deephub
发布2021-10-09 16:29:45
1.9K0
发布2021-10-09 16:29:45
举报
文章被收录于专栏:DeepHub IMBADeepHub IMBA

在这篇文章中,我们将探索如何建立一个简单的具有三元组损失的网络模型。它在人脸验证、人脸识别和签名验证等领域都有广泛的应用。在进入代码之前,让我们先了解一下什么是三元组损失(Triplet Loss),以及如何在PyTorch中实现它。

三元组损失

三元组损失(Triplet loss)函数是当前应用较为广泛的一种损失函数,最早由Google研究团队在论文《FaceNet:A Unified Embedding for Face Recognition》所提出,Triplet loss的优势在于细节区分,即当两个输入相似时,Triplet loss能够更好地对细节进行建模,相当于加入了两个输入差异性差异的度量,学习到输入的更好表示。

这里的逻辑是我们一次总共拍摄三张图像,即我们的样本(anchor)、正样例(positive )和负样例(negative)。我们对于模型的训练方式是使anchor和positive 之间的距离最小化。而anchor和negative的距离最大化。为了 实现目标这个目标,我们就需要使用一个特殊的损失函数 三元组损失(Triplet loss)。

我们使用欧氏距离测量从各个图像中提取的特征之间的距离。公式中alpha 指的是在比较发生时将positive 与negative分开的边界限制/阈值是多少。

让我们以margin = 0.2为例,并将其应用于上述公式,

例子(1): dist (A,P)=0.7 & dist (A,N)=0.5 — 应用这个条件,我们有 max(0.7–0.5 + 0.2, 0) 会得到 max(0.4,0) = 0.4.每当anchor和positive之间的距离大于anchor和negative时损失值就会很高。我们模型学习的目标是缩小A&P之间的差距,拉开A&N之间的空间。

case(2): dist (A,P) = 0.1 & dist (A,N) = 0.5 — 在这种情况下,该值符合预期,当我们将所有这些都放入公式时,我们得到0 (即) max(0.1– 0.5 + 0.2, 0)。

Pytorch 中的实现:我们为损失函数创建一个新类,该类继承了抽象类 nn.Module ,并且固定的margin 为 0.2。

我们还更改的类的两个主要方法 __init__forward。我们在前向传播中使用了“relu”激活,是因为欧氏距离是正数之间计算的。所以在计算损失时对于零值和负值“relu”返回零,这是我们需要的结果。我们需要的损失主要就是当括号内的值为正值时的数值,因此 Siamese 模型尝试学习模式,从而降低损失值。

代码语言:javascript
复制
#define triplet loss functionclass triplet_loss(nn.Module):
 def __init__(self):
     super(triplet_loss, self).__init__()
     self.margin = 0.2def forward(self, anchor, positive, negative):
    pos_dist = (anchor - positive).pow(2).sum(1)
    neg_dist = (anchor - negative).pow(2).sum(1)
    loss = F.relu(pos_dist - neg_dist + self.margin)
    return loss.mean()#we can also use #torch.nn.functional.pairwise_distance(anchor,positive, keep_dims=True), which #computes the euclidean distance.

带有预训练模型的编码器

现在我们已经定义了损失函数,下一步就是模型。这里我们使用 resnet152,并且设置 pretrained = True ,这样可以使用Imagenet的与训练权重。我们还将提取的最终特征保持为 128 的长度。

代码语言:javascript
复制
#define a siamese network using ResNet152
custom_model = models.resnet152(pretrained=True)

#display the names of the individual blocks
for name, model in custom_model.named_children():
    print(name)

output: conv1 bn1 relu maxpool layer1 layer2 layer3 layer4 avgpool fc

让我们显示最后一层,看看它的样子,

代码语言:javascript
复制
#the last layer is the one we want to modify to 128 as this will be used for distance metric comparison
custom_model.fc

Linear(in_features=2048, out_features=1000, bias=True)

由于最后一层的输出是 1000,我们可能希望将其更改为 128。

代码语言:javascript
复制
in_ftrs = custom_model.fc.in_features
out_ftrs = custom_model.fc.out_features
print('number of input features of the model:', in_ftrs)
print('number of output features of the model:', out_ftrs )

output:
number of input features of the model: 2048 
number of output features of the model: 1000

#now update the last layer output to a length of 128
custom_model.fc = nn.Linear(in_ftrs, 128)

#print the updated model
custom_model.fc

output:
Linear(in_features=2048, out_features=128, bias=True)

现在将模型转换为使用“cuda”。

代码语言:javascript
复制
custom_model = custom_model.to(device)

训练步骤可以像下面这样给出,

代码语言:javascript
复制
loss_fun = triplet_loss()
optimizer = Adam(custom_model.parameters(), lr = 0.001)
for epoch in range(30):
    total_loss = 0
    for i, (anchor, positive, negative) in enumerate(custom_loader):
        anchor = anchor['image'].to(device)
        positive = positive['image'].to(device)
        negative = negative['image'].to(device)
        
        anchor_feature = custom_model(anchor)
        positive_feature = custom_model(positive)
        negative_feature = custom_model(negative)
        
        optimizer.zero_grad()
        loss = loss_fun(anchor_feature, positive_feature, negative_feature)
         loss.backward()
         optimizer.step()

以上只是训练的代码,除了三元组损失以外,还有类似的对比损失(contrastive loss) 可以使用,如果你对这个比较感兴趣,可以在这里找到代码。

https://github.com/adambielski/siamese-triplet/blob/master/losses.py

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-09-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 DeepHub IMBA 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 在这篇文章中,我们将探索如何建立一个简单的具有三元组损失的网络模型。它在人脸验证、人脸识别和签名验证等领域都有广泛的应用。在进入代码之前,让我们先了解一下什么是三元组损失(Triplet Loss),以及如何在PyTorch中实现它。
    • 三元组损失
      • 带有预训练模型的编码器
      相关产品与服务
      人脸识别
      腾讯云神图·人脸识别(Face Recognition)基于腾讯优图强大的面部分析技术,提供包括人脸检测与分析、比对、搜索、验证、五官定位、活体检测等多种功能,为开发者和企业提供高性能高可用的人脸识别服务。 可应用于在线娱乐、在线身份认证等多种应用场景,充分满足各行业客户的人脸属性识别及用户身份确认等需求。
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档