0


使用Pytorch实现三元组损失

点击上方“Deephub 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 模型尝试学习模式,从而降低损失值。

#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 的长度。

#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

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

#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。

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”。

custom_model = custom_model.to(device)

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

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

作者:Nandhini

喜欢就关注一下吧:

点个 在看 你最好看!********** **********

标签:

“使用Pytorch实现三元组损失”的评论:

还没有评论