背景
多任务学习中多loss的问题:
Loss 值有大有小,取值大的 Loss 可能会主导,如图所示,需要处理这个问题。典型的例子是二分类任务 + 回归任务的多目标优化,L2 Loss 和交叉熵损失的 Loss 大小与梯度大小的量级和幅度可能差异很大,如果不处理会对优化造成很大干扰。
简单的多任务学习往往是把所有 公式 进行联合优化,通常需要需要手动调节他们的 weights。典型的 公式 Function 如下:
然而这种方式通常存在如下问题:
模型最后学习效果对于 weights 非常敏感,否则很难同时收获对于多个任务都比较优的模型。同时手工调节这些 weights 也是非常费时费力的工作。 这篇paper提出直接建模单个任务中的uncertainty,然后通过uncertainty来指导权重的调节。
为直接建模的uncertainty,是一个可学习的参数。 总 Loss 设计成这样的形式,模型优化过程中会倾向于惩罚高 Loss 而低 公式 的情况(如果一个任务的 Loss 高,同时 公式 又小的话,这一项就会很大,优化算法就会倾向于优化它)。
背后的含义是: Loss 大的任务,包含的uncertainty也应该多,而它的权重就应该小一点。 这样优化的结果就是往往 Loss 小(相对简单)的任务会有一个更大的权重。例如在分类 + 回归的多目标优化任务中,回归任务 Loss 大,Uncertainty Weight给予小权重,整体效果可能是有帮助的。
我的代码
def uncertainty_weight_loss(label, label2, label3, logits, pred2, pred3):
sigma1 = tf.get_variable('sigma1', 1,
initializer=tf.constant_initializer(1.0),
dtype=tf.float32)
sigma2 = tf.get_variable('sigma2', 1,
initializer=tf.constant_initializer(1.0),
dtype=tf.float32)
sigma3 = tf.get_variable('sigma3', 1,
initializer=tf.constant_initializer(1.0),
dtype=tf.float32)
sigma1 = tf.math.exp(sigma1)
sigma2 = tf.math.exp(sigma2)
sigma3 = tf.math.exp(sigma3)
weights1 = 1 / (sigma1**2)
weights2 = 1 / (2 * sigma2 ** 2)
weights3 = 1 / (2 * sigma3 ** 2)
loss1 = tf.losses.sigmoid_cross_entropy(label, logits, weights=tf.broadcast_to(weights1, tf.shape(label)))
loss2 = tf.losses.mean_squared_error(label2, pred2, weights=tf.broadcast_to(weights2, tf.shape(label2)))
loss3 = tf.losses.mean_squared_error(label3, pred3, weights=tf.broadcast_to(weights3, tf.shape(label3)))
loss = loss1 + loss2 + loss3 + tf.log(sigma1)[0] + tf.log(sigma2)[0] + tf.log(sigma3)[0]
return loss
回归问题和分类问题分别推导
- 回归问题:L2
l ( w ) = ∣ ∣ y − f ( x ) ∣ ∣ 2 l(w)= ||y-f(x)||^2 l(w)=∣∣y−f(x)∣∣2 - 分类问题:交叉熵
l ( w ) = − l o g S o f t m a x ( y , f ( x ) ) l(w)=-logSoftmax(y,f(x)) l(w)=−logSoftmax(y,f(x))
ref
http://www.liuxiao.org/2020/07/multi-task-learning-using-uncertainty-to-weigh-losses-for-scene-geometry-and-semantics/
file:///Users/alsc/Downloads/Multi-Task-Learning-Using-Uncertainty-to-Weigh-Losses-for-Scene-Geometry-and-Semantics.pdf
https://showmeai.tech/article-detail/multitask-learning