本文源自微信公众号【Python编程和深度学习】原文链接:常用损失函数Loss和Python代码,欢迎扫码关注鸭!
目录
一、损失函数
二、交叉熵损失
三、MSELoss
四、Dice Loss
五、Focal Loss
六、多种损失函数结合
一、损失函数
在机器学习和深度学习中,损失函数 Loss function 是用来估量训练过程中模型的预测值Prediction与真实值Target的偏差,损失函数越小,预测值和真实值越接近,模型的泛化性能越好,通过不断调整模型参数使得损失函数越来越小,从而指导模型的学习。
二、交叉熵损失
2.1、 Softmax Loss
交叉熵损失一般配合softmax使用的,通过softmax操作得到每个类别的概率值,所有概率值和为1,然后计算loss,softmax函数为:
f(zk)=ezk/(∑jezj)
Python代码如下:
import torch
import torch.nn as nn
import torch.nn.functional as F
input = torch.randn(3, requires_grad=True) # 从标准正态分布(均值为0,方差为1,即高斯白噪声)中抽取的3个随机数
target = torch.empty(3).random_(2) # 生成3个值,值为0 或者 1
#二值交叉熵,这里输入要经过sigmoid处理
out = F.sigmoid(input)
loss = nn.BCELoss(out, target)
#多分类交叉熵, 用这个 loss 前面不需要加 Softmax 层
out = activation fuction(input)#activation fuction是激活函数
loss= nn.CrossEntropyLoss(input, target)
loss.backward()
交叉熵Loss可以用在大多数语义分割场景中,但当某一类的数量占比远远小于其他类时,损失函数中这一类就会越来越不被重视,其他类的成分就会占据主导,导致效果不好。交叉熵损失还有一个特点,优化类间的距离非常棒,但是优化类内距离时比较弱,因此有很多研究人员对其进行改进优化。
2.2、带权交叉熵损失 Weighted Softmax Loss
在任务中当某一类数量占比很少,但这一类又很重要时,带权重的交叉熵损失就发挥用处了,函数如下:
L=−M∑c=1wcyclog(pc)
Wc=(N−Nc)/N
Python代码如下:
nn.CrossEntropyLoss(input, target, weight=class_weight)
2.3、Soft Softmax loss
公式如下: f(zk)=ezk/T/(∑jezj/T)
三、MSELoss
计算均方误差 Mean Squared Error (squared L2 Norm)。
公式如下,其中是真实值,是预测值:
loss =1nn∑i=1(y−ˆy)2
import torch
Loss = nn.MSELoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.randn(3, 5)
loss = loss(input, target)
loss.backward()
四、Dice Loss
是用来度量集合相似度的度量函数,通常用于计算两个样本之间的像素相似度,公式如下: diceLoss =1−2|A∗B||A|+|B|
Python代码如下:
import torch.nn as nn
import torch.nn.functional as F
class SoftDiceLoss(nn.Module):
def __init__(self, weight=None, size_average=True):
super(SoftDiceLoss, self).__init__()
def forward(self, logits, targets):
num = targets.size(0)
smooth = 1
probs = F.sigmoid(logits)
m1 = probs.view(num, -1)
m2 = targets.view(num, -1)
intersection = (m1 * m2)
score = 2. * (intersection.sum(1) + smooth) / (m1.sum(1) + m2.sum(1) + smooth)
score = 1 - score.sum() / num
return score
五、Focal Loss
何凯明团队在RetinaNet论文中引入了Focal Loss来解决难易样本数量不平衡,在one-stage目标检测中正负样本比例严重失衡,该损失函数降低了大量简单负样本在训练中所占的权重,也可理解为一种困难样本挖掘。
二元交叉熵函数如下:
loss =−ylogˆy−(1−y)log(1−ˆy)={−logˆy,y=1−log(1−ˆy),y=0
Python 代码如下:
import torch
import torch.nn as nn
#二分类
class FocalLoss(nn.Module):
def __init__(self, gamma=2,alpha=0.25):
super(FocalLoss, self).__init__()
self.gamma = gamma
self.alpha=alpha
def forward(self, input, target):
# input:size is M*2. M is the batch number
# target:size is M.
pt=torch.softmax(input,dim=1)
p=pt[:,1]
loss = -self.alpha*(1-p)**self.gamma*(target*torch.log(p))-\
(1-self.alpha)*p**self.gamma*((1-target)*torch.log(1-p))
return loss.mean()
六、多种损失函数结合
6.1 BCE + Dice Loss
在数据较为均衡的情况下有所改善,但是在数据极度不均衡的情况下交叉熵Loss会在迭代几个Epoch之后远远小于Dice Loss,这个组合Loss会退化为Dice Loss。
6.2 Focal Loss + Dice Loss
即将Focal Loss和Dice Loss相加,以来处理小器官的分割问题。