【发布时间】:2021-06-09 22:03:05
【问题描述】:
我编写了一个自定义损失函数,将正则化损失添加到总损失中,我只将 L2 正则化器添加到内核,但是当我调用 model.fit() 时出现警告,指出这些偏差不存在梯度,并且偏差不会更新,如果我从其中一层的内核中删除正则化器,该内核的梯度也不存在。
我尝试向每一层添加偏差正则化器,一切正常,但我不想对偏差进行正则化,我该怎么办?
这是我的损失函数:
def _loss_function(y_true, y_pred):
# convert tensors to numpy arrays
y_true_n = y_true.numpy()
y_pred_n = y_pred.numpy()
# modify probablities for Knowledge Distillation loss
# we do this for old tasks only
old_y_true = np.float_power(y_true_n[:, :-1], 0.5)
old_y_true = old_y_true / np.sum(old_y_true)
old_y_pred = np.float_power(y_pred_n[:, :-1], 0.5)
old_y_pred = old_y_pred / np.sum(old_y_pred)
# Define the loss that we will used for new and old tasks
bce = tf.keras.losses.BinaryCrossentropy()
# compute the loss on old tasks
old_loss = bce(old_y_true, old_y_pred)
# compute the loss on new task
new_loss = bce(y_true_n[:, -1], y_pred_n[:, -1])
# compute the regularization loss
reg_loss = tf.compat.v1.losses.get_regularization_loss()
assert reg_loss is not None
# convert all tensors to float64
old_loss = tf.cast(old_loss, dtype=tf.float64)
new_loss = tf.cast(new_loss, dtype=tf.float64)
reg_loss = tf.cast(reg_loss, dtype=tf.float64)
return old_loss + new_loss + reg_loss
【问题讨论】:
标签: tensorflow deep-learning loss-function