损失函数(深度学习)
一、交叉熵
1 二分类
在二分的情况下,模型最后需要预测的结果只有两种情况,对于每个类别我们的预测得到的概率为 和
,此时表达式为(log的底数是 e):
其中:
- —— 表示样本 的label,正类为 1,负类为0 ;
- —— 表示样本 预测为正类的概率.
from torch import nn
import torch
class CrossEntropyLoss(nn.Module):
def __init__(self, weight=None, reduction="mean") -> None:
super().__init__()
self.loss_fcn = torch.nn.CrossEntropyLoss(weight=weight, reduction=reduction)
def forward(self, pred, target):
loss = self.loss_fcn(pred, target)
return loss
2 多分类
多分类的情况实际上就是对二分类的扩展:
其中:M——类别的数量
——符号函数(0 或1 ),如果样本 的真实类别等于 c取 1,否则取 0
——观测样本
属于类别 c的预测概率
二、焦点损失函数
Focal Loss 的核心思想是动态调整不同样本的损失权重。对于分类容易的样本,降低其损失贡献;对于分类困难的样本,增加其损失权重,这种策略特别适用于处理类别不平衡和样本复杂性高的场景。
引入了一个权重因子α ∈ [ 0 , 1 ] ,全局损失的平衡系数 。当为正样本时,权重因子就是α,当为负样本时,权重因子为1-α。
γ为一个参数,范围在 [0,5], 当 γ为0时,就变为了最开始的CE损失函数。
是调制因子,可以降低易分样本的损失贡献,从而增加难分样本的损失比例。(解释)当Pt趋向于1,即说明该样本是易区分样本,此时调制因子是趋向于0,说明对损失的贡献较小,即减低了易区分样本的损失比例。当pt很小,也就是假如某个样本被分到正样本,但是该样本为前景的概率特别小,即被错分到正样本了,此时 调制因子是趋向于1,对loss也没有太大的影响。
"""
以二分类任务为例
"""
from torch import nn
import torch
class FocalLoss(nn.Module):
def __init__(self, gama=1.5, alpha=0.25, weight=None, reduction="mean") -> None:
super().__init__()
self.loss_fcn = torch.nn.CrossEntropyLoss(weight=weight, reduction=reduction)
self.gama = gama
self.alpha = alpha
def forward(self, pre, target):
logp = self.loss_fcn(pre, target)
p = torch.exp(-logp)
loss = (1-p)**self.gama * self.alpha * logp
return loss.mean()
三、多项式损失函数 POLYLOSS
1 CE多项式
2 FL多项式
四、焦点平滑函数
平滑焦点损失函数主要包含两个部分:标签平滑的二元交叉熵损失和焦点损失。
标 签 平 滑 策 略 中 , 原 始 的 硬 标 签 ( HardLabel)被平滑处理,引入了一个可调节的平滑系数。具体而言,对于二值化的目标标签 y,通过引入平滑系数(默认为 0.1),将标签值从严格的 0 和1 转化为更具鲁棒性的软标签。这一策略有效降低了模型对训练数据的过度自信,提升了泛化能力,计算公式为:
其中,y 表示原始目标标签,smoothing 是平滑系数,默认设置为 0.1。
改进后的损失函数
五、SupCon
SupCon 的本质是监督对比学习,通过在特征空间中显式地构建正负样本对,实现类内紧致、类间分离的特征分布。其关键在于利用标签信息定义正样本(同一类别的所有样本及其增强视图),从而比传统交叉熵更充分地挖掘了监督信号。
核心思想为:在特征空间中,拉近同一类别的样本(正样本对),推远不同类别的样本(负样本对)
公式:

参数说明:
: 一个批次中的“锚点”样本索引。注意,一个批次的大小是 ,因为它通常由 个原始样本和它们的 个增强版本构成。
: 锚点样本 经过编码器网络(如 ResNet)和投影头后得到的归一化特征向量(即 )。
: 批次中除了 本身之外的所有样本的索引集合,。
: 锚点 的所有正样本的索引集合,这是 SupCon 的关键所在。
对于锚点 , 包括:
(1) 由同一原始图像生成的不同增强视图(如果存在)。
(2) 批次中所有其他与 属于同一类别的样本(包括它们的增强视图)。
: 温度参数,一个标量。它用于调节分布的尖锐程度。较小的 会使损失对难负样本更敏感。
: 正样本集合的大小,如果某个类别在批次中只有一个样本,那么 (只有它自己的增强视图)。
"""
Author: Yonglong Tian (yonglong@mit.edu)
Date: May 07, 2020
"""
from __future__ import print_function
import torch
import torch.nn as nn
class SupConLoss(nn.Module):
"""Supervised Contrastive Learning: https://arxiv.org/pdf/2004.11362.pdf.
It also supports the unsupervised contrastive loss in SimCLR"""
def __init__(self, temperature=0.07, contrast_mode='all',
base_temperature=0.07):
super(SupConLoss, self).__init__()
self.temperature = temperature
self.contrast_mode = contrast_mode
self.base_temperature = base_temperature
def forward(self, features, labels=None, mask=None):
"""Compute loss for model. If both `labels` and `mask` are None,
it degenerates to SimCLR unsupervised loss:
https://arxiv.org/pdf/2002.05709.pdf
Args:
features: hidden vector of shape [bsz, n_views, ...].
labels: ground truth of shape [bsz].
mask: contrastive mask of shape [bsz, bsz], mask_{i,j}=1 if sample j
has the same class as sample i. Can be asymmetric.
Returns:
A loss scalar.
"""
device = (torch.device('cuda')
if features.is_cuda
else torch.device('cpu'))
if len(features.shape) < 3:
raise ValueError('`features` needs to be [bsz, n_views, ...],'
'at least 3 dimensions are required')
if len(features.shape) > 3:
features = features.view(features.shape[0], features.shape[1], -1)
batch_size = features.shape[0]
if labels is not None and mask is not None:
raise ValueError('Cannot define both `labels` and `mask`')
elif labels is None and mask is None:
mask = torch.eye(batch_size, dtype=torch.float32).to(device)
elif labels is not None:
labels = labels.contiguous().view(-1, 1)
if labels.shape[0] != batch_size:
raise ValueError('Num of labels does not match num of features')
mask = torch.eq(labels, labels.T).float().to(device)
else:
mask = mask.float().to(device)
contrast_count = features.shape[1]
contrast_feature = torch.cat(torch.unbind(features, dim=1), dim=0)
if self.contrast_mode == 'one':
anchor_feature = features[:, 0]
anchor_count = 1
elif self.contrast_mode == 'all':
anchor_feature = contrast_feature
anchor_count = contrast_count
else:
raise ValueError('Unknown mode: {}'.format(self.contrast_mode))
# compute logits
anchor_dot_contrast = torch.div(
torch.matmul(anchor_feature, contrast_feature.T),
self.temperature)
# for numerical stability
logits_max, _ = torch.max(anchor_dot_contrast, dim=1, keepdim=True)
logits = anchor_dot_contrast - logits_max.detach()
# tile mask
mask = mask.repeat(anchor_count, contrast_count)
# mask-out self-contrast cases
logits_mask = torch.scatter(
torch.ones_like(mask),
1,
torch.arange(batch_size * anchor_count).view(-1, 1).to(device),
0
)
mask = mask * logits_mask
# compute log_prob
exp_logits = torch.exp(logits) * logits_mask
log_prob = logits - torch.log(exp_logits.sum(1, keepdim=True))
# compute mean of log-likelihood over positive
mean_log_prob_pos = (mask * log_prob).sum(1) / mask.sum(1)
# loss
loss = - (self.temperature / self.base_temperature) * mean_log_prob_pos
loss = loss.view(anchor_count, batch_size).mean()
return loss
传统交叉熵的相似度,衡量的是样本特征与每个类别权重向量的匹配程度,它通过线性变换后的logit分数来直接推断样本的类别,本质上学习的是一个从“样本”到“类别”的映射关系。
而SupCon的相似度,衡量的是样本特征之间的直接相似程度,其训练过程不仅拉近同一数据的不同增强视图,更关键的是拉近了同批次中所有同类样本的特征。这种设计使其目标不是直接充当分类器,而是训练一个强大的特征编码器,在原论文中,训练完成后会在此编码器输出的通用特征之上,另训练一个简单的线性分类器来完成最终任务。
更多推荐


所有评论(0)