我试图在Keras中使用自定义丢失功能。我的实现看起来像:
class LossFunction:
...
def loss(self, y_true, y_pred):
...
localization_loss = self._localization_loss()
confidence_loss = self._object_confidence_loss()
category_loss = self._category_loss()
self.loc_loss = localization_loss
self.obj_conf_loss = confidence_loss
self.category_loss = category_loss
tot_loss = localization_loss + confidence_loss + category_loss
self.tot_loss = tot_loss
return tot_loss
然后我定义自定义指标来查看存储的张量,如:
class MetricContainer:
def __init__(self, loss_obj):
self.loss = loss_obj
def local_loss(self, y_true, y_pred):
return self.loss.loc_loss
def confidence_loss(self, y_true, y_pred):
return self.loss.obj_conf_loss
def category_loss(self, y_true, y_pred):
return self.loss.category_loss
def tot_loss(self, y_true, y_pred):
return self.loss.tot_loss
然后我用这个命令编译我的模型:
model.compile('adam',
loss=loss_obj.loss,
metrics=[metric_container.local_loss,
metric_container.confidence_loss,
metric_container.category_loss,
metric_container.tot_loss])
当我训练模型时(在一个非常小的训练集上)我输出如下:
Epoch 1/2
1/2 [==============>...............] - ETA: 76s - loss: 482.6910 - category_loss: 28.1100 - confidence_loss: 439.9192 - local_loss: 13.1180 - tot_loss: 481.1472
2/2 [==============================] - 96s - loss: 324.6292 - category_loss: 18.1967 - confidence_loss: 296.0593 - local_loss: 8.8204 - tot_loss: 323.0764 - val_loss: 408.1170 - val_category_loss: 0.0000e+00 - val_confidence_loss: 400.0000 - val_local_loss: 6.5036 - val_tot_loss: 406.5036
由于某些原因tot_loss
和loss
不匹配,即使我应该为它们使用相同的值。
知道为什么会这样吗?返回后,Keras会做些什么来修改损失吗?
答案 0 :(得分:2)
您的损失等于所选损失函数和正则化项的总和。因此,如果您使用任何类型的正则化 - 它会通过添加正则化术语来影响您的损失。