文章目录
- 1. focal loss损失函数的原理
- 2. 基于focal loss的深度卷积模型构建与测试
- 参考文献
1. focal loss损失函数的原理
代价敏感损失的定义:通过对不同类别的损失分配不同的权值,从而降低容易分类正确的富样本类对模型训练损失的贡献率,提升难区分类对模型训练损失的贡献率。
具体的,代价敏感损失的公式为:
L c o n f = { − α c l s 1 ⋅ ( 1 − p t ) γ log ( p t ) − α c l s 2 ⋅ p t γ ⋅ log ( p t ) L_{conf}=left{ begin{array}{c} -alpha _{cls1}cdot left( 1-p_t right) ^{gamma}log left( p_t right)\ -alpha _{cls2}cdot {p_t}^{gamma}cdot log left( p_t right)\ end{array} right. Lconf={−αcls1⋅(1−pt)γlog(pt)−αcls2⋅ptγ⋅log(pt)
式中,类别的权值因子 α c l s ( ⋅ ) alpha _{clsleft( cdot right)} αcls(⋅)和调制因子 ( 1 − p t ) γ left( 1-p_t right) ^{gamma} (1−pt)γ分别决定了模型损失函数针对数据类间不平衡导致的区分难以程度变化的权值调整。
2. 基于focal loss的深度卷积模型构建与测试固定权值因子的多分类代价敏感损失python代码。
# 多分类的focal loss 损失函数(只考虑调制因子)
def focal_loss_fixed(y_true, y_pred, gamma=2.0):
y_pred = tf.nn.softmax(y_pred, axis=-1)
eps = tf.keras.backend.epsilon()
y_pred = tf.clip_by_value(y_pred, eps, 1.0)
y_true = tf.cast(y_true, tf.float32)
loss = -y_true * tf.math.pow(1 - y_pred, gamma) * tf.math.log(y_pred)
loss = tf.reduce_sum(loss, axis=1)
return loss
######################################################################################
多分类代价敏感损失完整python代码。
def focal_loss(y_true, y_probs, alpha=0.5, gamma=1.5,):
epsilon = tf.keras.backend.epsilon()
positive_pt = tf.where(tf.equal(y_true, 1), y_probs, tf.ones_like(y_probs))
negative_pt = tf.where(tf.equal(y_true, 0), 1 - y_probs, tf.ones_like(y_probs))
loss = -alpha * tf.pow(1 - positive_pt, gamma) * tf.math.log(tf.clip_by_value(positive_pt, epsilon, 1.)) -
(1 - alpha) * tf.pow(1 - negative_pt, gamma) * tf.math.log(tf.clip_by_value(negative_pt, epsilon, 1.))
return tf.reduce_sum(loss)
参考文献模型训练过程可视化结果
[1] https://engineering.case.edu/bearingdatacenter
[2] https://zhuanlan.zhihu.com/p/448210993



