pytorch笔记:TRIPLETMARGINLOSS

1 介绍

  • 创建一个衡量三元组损失的标准,给定输入张量 x1​、x2​ 和 x3​ 以及一个大于0的间距值。
  • 这用于测量样本之间的相对相似性。一个三元组由a、p和n组成(锚点、正例和负例)。所
  • 有输入张量的形状都应为 (N,D)

  • Loss function可以分为三种情况
    • 简单样本:
      • 此时 正样本距离anchor的距离d(ai, pi) + Margin仍然小于负样本距离anchor的距离d(ai, ni),该情况认为正样本距离足够小,不需要进行优化,因此Loss为0
    • 半难样本:
      • 虽然负样本距离anchor的距离d(ai, ni) 大于 正样本距离anchor的距离d(ai, pi),但是还不够大,没有超过 Margin,需要优化
    • 难样本:
      • 负样本距离anchor的距离d(ai, ni) 小于正样本距离anchor的距离d(ai, pi),需要优化

直观地来讲,负样本的位置和样本难度的关系如下:

2 基本使用方法

torch.nn.TripletMarginLoss(
    margin=1.0, 
    p=2.0, 
    eps=1e-06, 
    swap=False, 
    size_average=None, 
    reduce=None, 
    reduction='mean')

3 参数

margin(float,可选)默认为1
p(int,可选)用于成对距离的范数度。默认为2
reduction(str,可选)none/mean/sum,默认是mean

4 举例

import torch
import torch.nn as nn


anchor = torch.tensor([0.5, -0.5, 0.1], requires_grad=True)

pos = torch.tensor([0.7, 0.2, 0.1])

neg= torch.tensor([0.8, 0.9, 0.2])

triplet_loss = nn.TripletMarginLoss(margin=1.0, p=1)

triplet_loss(anchor,pos,neg)
#tensor(0.1000, grad_fn=<MeanBackward0>)

'''
(0.2-0.3)+(0.7-1.4)+(0-0.1)+1=0.1000
''
import torch
import torch.nn as nn


anchor = torch.tensor([0.5, -0.5, 0.1], requires_grad=True)

pos = torch.tensor([0.7, 0.2, 0.1])

neg= torch.tensor([0.8, 0.9, 0.2])

triplet_loss = nn.TripletMarginLoss(margin=1.0, p=2)

triplet_loss(anchor,pos,neg)
#tensor(0.2927, grad_fn=<MeanBackward0>)
'''
np.sqrt((0.2-0.3)**2+(0.7-1.4)**2+(0-0.1)**2)
'''

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UQI-LIUWJ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值