Focal Loss 损失函数简述

Focal Loss

摘要

Focal Loss目标是解决样本类别不平衡以及样本分类难度不平衡等问题,如目标检测中大量简单的background,不多量较难的foreground样本。Focal Loss经过修改交叉熵函数,经过增长类别权重\(\alpha\) 和 样本难度权重调因子(modulating factor)\((1-p_t)^\gamma\),来减缓上述问题,提高模型精确。python

1、技术背景

咱们知道object detection的算法主要能够分为两大类:two-stage detector和one-stage detector。前者是指相似Faster RCNN,RFCN这样须要region proposal的检测算法,这类算法能够达到很高的准确率,可是速度较慢。虽然能够经过减小proposal的数量或下降输入图像的分辨率等方式达到提速,可是速度并无质的提高。后者是指相似YOLO,SSD这样不须要region proposal,直接回归的检测算法,这类算法速度很快,可是准确率不如前者。做者提出focal loss的出发点也是但愿one-stage detector能够达到two-stage detector的准确率,同时不影响原有的速度。算法

2、拟解决问题

做者认为one-stage detector的准确率不如two-stage detector的缘由是:样本不均衡问题,其中包括两个方面:函数

    1. 解决样本的类别不平衡问题
    1. 解决简单/困难样本不平衡问题

When summed over a lager number of easy examples, these small loss values can overwhelm the rare class.
大量loss小的简单样本相加,能够淹没稀有类.优化

如在object detection领域,一张图像可能生成成千上万的candidate locations,可是其中只有不多一部分是包含object的(1:1000)。这就带来了类别不均衡。那么类别不均衡会带来什么后果呢?引用原文讲的两个后果:(1) training is inefficient as most locations are easy negatives that contribute no useful learning signal; (2) en masse, the easy negatives can overwhelm training and lead to degenerate models.
负样本数量太大,占总的loss的大部分,并且可能是容易分类的,所以使得模型的优化方向并非咱们所但愿的那样。spa

3、解决方案

为了解决(1)解决样本的类别不平衡问题和(2)解决简单/困难样本不平衡问题,做者提出一种新的损失函数:focal loss。这个损失函数是在标准交叉熵损失基础上改进获得:.net

该focal loss函数曲线为:
code

其中,\(-log(p_t)\) 为初始交叉熵损失函数,\(\alpha\)类别间(0-1二分类)的权重参数\((1-p_t)^\gamma\)简单/困难样本调节因子(modulating factor),而\(\gamma\)聚焦参数(focusing parameter)blog

一、造成过程:

(1)初始二分类的交叉熵(Cross Emtropy, CE)函数:


在上面的\(y\in \{\pm1\}\) 为指定的ground-truth类别,\(p \in [0, 1]\) 是模型对带有 \(y=1\) 标签类别的几率估计。为了方便,咱们将\(p_t\)定义为:
ip

和重写的\(CE(p, y)\)
ci

(2)平衡交叉熵(Balanced Cross Entropy):

一个广泛解决类别不平衡的方法是增长权重参数\(\alpha \in [0 ,1]\),当$ y=1 \(类的权重为\)\alpha$ ,\(y=-1\) 类的权重为\(1-\alpha\) 。在实验中,\(\alpha\) 被设成逆类别频率(inverse class frequence),\(\alpha_t\)定义与\(p_t\)同样:

所以,\(\alpha-balanced\) 的CE损失函数为:

(3)聚焦损失(Focal Loss):

尽管\(\alpha\)能平衡positive/negative的重要性,可是没法区分简单easy/困难hard样本。为此,对于简单的样本增长一个小的权重(down-weighted),让损失函数聚焦在困难样本的训练。
所以,在交叉熵损失函数增长调节因子\((1-p_t)^\gamma\) ,和可调节聚参数\(\gamma \geq 0\)。,因此损失函数变成:

\(p_t\rightarrow0\)时,同时调节因子也 \((1-p_t)^\gamma\rightarrow0\) ,所以简单样本的权重越小。直观地讲,调节因子减小了简单示例的loss贡献,并扩展了样本接收低loss的范围。 例如,在γ= 2的状况下,与CE相比,分类为pt = 0.9的示例的损失将下降100倍,而对于pt≈0.968的示例,其损失将下降1000倍。 这反过来增长了纠正错误分类示例的重要性(对于pt≤0.5和γ= 2,其损失最多缩小4倍)。

(4)最终的损失函数Focal Loss形式:

根据论文做者实验,\(\alpha=0.25\)\(\gamma=2\) 效果最好

实现代码:

def focal_loss(y_true, y_pred):
    alpha, gamma = 0.25, 2
    y_pred = K.clip(y_pred, 1e-8, 1 - 1e-8)
    return - alpha * y_true * K.log(y_pred) * (1 - y_pred)**gamma\
           - (1 - alpha) * (1 - y_true) * K.log(1 - y_pred) * y_pred**gamma

4、Reference

  1. https://blog.csdn.net/u014380165/article/details/77019084
  2. Lin T Y, Goyal P, Girshick R, et al. Focal loss for dense object detection[C]//Proceedings of the IEEE international conference on computer vision. 2017: 2980-2988.
相关文章
相关标签/搜索