文章目录

  • ​​损失函数总结​​
  • ​​部分特殊损失函数详解​​
  • ​​1. 余弦损失函数 `torch.nn.CosineEmbeddingLoss`​​

损失函数总结

首先直接贴上个人看过比较好的一些的解析:

  • ​​深度学习之常用损失函数​​
  • ​​损失函数loss大总结​​​损失函数(Loss Function)​​pytorch中的gather函数_PyTorch中的损失函数–L1Loss /L2Loss/SmoothL1Loss

很全的Pytorch loss函数汇总:


部分特殊损失函数详解

1. 余弦损失函数 ​​torch.nn.CosineEmbeddingLoss​

  • 余弦损失函数,常常用于评估两个向量的相似性,两个向量的余弦值越高,则相似性越高。

Pytorch——常用损失函数详解_python

  • ​x​​​:包括​​x1​​​和​​x2​​​,即需要计算相似度的​​prediction​​​和​​GT​​;
  • ​y​​​:相当于人为给定的​​flag​​,决定按哪种方式计算得到loss的结果。

使用说明:

  • 如果需要约束使x1和x2尽可能的相似,那么就使用​​y=1​​​,​​prediction​​​和​​GT​​完全一致时,loss为0,反之亦然。

使用示例:

input1 = torch.randn(100, 128)
input2 = torch.randn(100, 128)
cos = nn.CosineEmbeddingLoss(reduction='mean')

loss_flag = torch.ones([100]) # 需要初始化一个N维的1或-1
output = cos(input1, input2, loss_flag)
print(output) # tensor(1.0003)