Keras Custom Losses:想要在每个 epoch 结束时跟踪每个损失值
Keras Custom Losses: Want to track each loss values at the end of each epoch
我想在每个纪元结束时检查 self.losses['RMSE']
、self.loss['CrossEntropy']
和 self.loss['OtherLoss']
的值。目前,我只能查看总损失self.loss['total']
。
def train_test(self):
def custom_loss(y_true, y_pred):
## (...) Calculate several losses inside this function
self.losses['total'] = self.losses['RMSE'] + self.losses['CrossEntropy'] + self.losses['OtherLoss']
return self.losses['total']
## (...) Generate Deep learning model & Read Inputs
logits = keras.layers.Dense(365, activation=keras.activations.softmax)(concat)
self.model = keras.Model(inputs=[...], outputs=logits)
self.model.compile(optimizer=keras.optimizers.Adam(0.001),
loss=custom_loss)
self.history = self.model.fit_generator(
generator=self.train_data,
steps_per_epoch=train_data_size//FLAGS.batch_size,
epochs=5,
callbacks=[CallbackA(self.losses)])
class TrackTestDataPerformanceCallback(keras.callbacks.Callback):
def __init__(self, losses):
self.losses = losses
def on_epoch_end(self, epoch, logs={}):
for key in self.losses.keys()
print('Type of loss: {}, Value: {}'.format(key, K.eval(self.losses[key])))
我将 self.loss
传递给回调函数 CallbackA
以便在每个纪元结束时打印子损失值。但是,它给出如下错误消息:
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'input_3' with dtype float and shape [?,5]
[[Node: input_3 = Placeholder[dtype=DT_FLOAT, shape=[?,5], _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]
[[Node: loss/dense_3_loss/survive_rates/while/LoopCond/_881 = _HostRecv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_360_loss/dense_3_loss/survive_rates/while/LoopCond", tensor_type=DT_BOOL, _device="/job:localhost/replica:0/task:0/device:CPU:0"](^_clooploss/dense_3_loss/survive_rates/while/strided_slice_4/stack_2/_837)]]
我可以再次将训练数据传递给回调函数,并预测自己来跟踪每个损失值。但我认为可能有更好的解决方案,我还不知道。
总结:如何在每个epoch后跟踪自定义损失函数中的几个损失值?
约束: 为了减少一些计算成本,我现在想在 custom_loss
函数中处理几个损失。但是,如果我必须将每个损失包装到每个函数中,那也可以。
编译时可以在一个列表中使用多个损失。例如,如果你想混合交叉熵和 mse,你可以使用:
model.compile(loss=['mse', 'binary_crossentropy'], loss_weights=[0.9, 0.1], optimizer=Adam())
历史将包含编译模型时使用的不同损失。
我必须为我们的模型维护一个组合的 custom_loss
,所以我找到了一种通过放入 metrics
参数来跟踪多个子损失的方法。每个损失函数单独定义为一个函数。
def custom_loss():
return subloss1() + subloss2() + subloss3()
def subloss1():
...
return value1
def subloss2():
...
return value2
def subloss3():
...
return value3
self.model.compile(optimizer=keras.optimizers.Adam(0.001),
loss=custom_loss,
metrics=[subloss1, subloss2, subloss3]
我想在每个纪元结束时检查 self.losses['RMSE']
、self.loss['CrossEntropy']
和 self.loss['OtherLoss']
的值。目前,我只能查看总损失self.loss['total']
。
def train_test(self):
def custom_loss(y_true, y_pred):
## (...) Calculate several losses inside this function
self.losses['total'] = self.losses['RMSE'] + self.losses['CrossEntropy'] + self.losses['OtherLoss']
return self.losses['total']
## (...) Generate Deep learning model & Read Inputs
logits = keras.layers.Dense(365, activation=keras.activations.softmax)(concat)
self.model = keras.Model(inputs=[...], outputs=logits)
self.model.compile(optimizer=keras.optimizers.Adam(0.001),
loss=custom_loss)
self.history = self.model.fit_generator(
generator=self.train_data,
steps_per_epoch=train_data_size//FLAGS.batch_size,
epochs=5,
callbacks=[CallbackA(self.losses)])
class TrackTestDataPerformanceCallback(keras.callbacks.Callback):
def __init__(self, losses):
self.losses = losses
def on_epoch_end(self, epoch, logs={}):
for key in self.losses.keys()
print('Type of loss: {}, Value: {}'.format(key, K.eval(self.losses[key])))
我将 self.loss
传递给回调函数 CallbackA
以便在每个纪元结束时打印子损失值。但是,它给出如下错误消息:
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'input_3' with dtype float and shape [?,5]
[[Node: input_3 = Placeholder[dtype=DT_FLOAT, shape=[?,5], _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]
[[Node: loss/dense_3_loss/survive_rates/while/LoopCond/_881 = _HostRecv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_360_loss/dense_3_loss/survive_rates/while/LoopCond", tensor_type=DT_BOOL, _device="/job:localhost/replica:0/task:0/device:CPU:0"](^_clooploss/dense_3_loss/survive_rates/while/strided_slice_4/stack_2/_837)]]
我可以再次将训练数据传递给回调函数,并预测自己来跟踪每个损失值。但我认为可能有更好的解决方案,我还不知道。
总结:如何在每个epoch后跟踪自定义损失函数中的几个损失值?
约束: 为了减少一些计算成本,我现在想在 custom_loss
函数中处理几个损失。但是,如果我必须将每个损失包装到每个函数中,那也可以。
编译时可以在一个列表中使用多个损失。例如,如果你想混合交叉熵和 mse,你可以使用:
model.compile(loss=['mse', 'binary_crossentropy'], loss_weights=[0.9, 0.1], optimizer=Adam())
历史将包含编译模型时使用的不同损失。
我必须为我们的模型维护一个组合的 custom_loss
,所以我找到了一种通过放入 metrics
参数来跟踪多个子损失的方法。每个损失函数单独定义为一个函数。
def custom_loss():
return subloss1() + subloss2() + subloss3()
def subloss1():
...
return value1
def subloss2():
...
return value2
def subloss3():
...
return value3
self.model.compile(optimizer=keras.optimizers.Adam(0.001),
loss=custom_loss,
metrics=[subloss1, subloss2, subloss3]