根据损失的 Keras 示例记录每个批次的 Keras 指标

Log Keras metrics for each batch as per Keras example for the loss

在 Keras 文档中,有一个 example,其中创建了自定义回调以记录每个批次的 loss。这对我来说效果很好,但我也想记录我添加的指标。

例如此代码:

optimizer = Adam()
loss = losses.categorical_crossentropy
metric = ["accuracy"]

model.compile(optimizer=optimizer,
              loss=loss,
              metrics=metric)


class LossHistory(Callback):
    def on_train_begin(self, logs={}):
        self.losses = []

    def on_batch_end(self, batch, logs={}):
        self.losses.append(logs.get('loss'))

loss_history = LossHistory()

history = model.fit(training_data, training_labels,
                    batch_size=batch_size,
                    epochs=epochs,
                    verbose=2,
                    validation_data=(val_data, val_labels),
                    callbacks=[loss_history])

我不知道如何访问指标。

指标历史存储在 loss_history.losses:

def on_batch_end(self, batch, logs={}):
  self.losses.append(logs.get('loss'))

此方法将在每个批次结束时调用,并将损失指标附加到 self.losses 中,因此一旦训练完成,您可以直接使用 loss_history.losses.[=16 访问此列表=]

我还应该补充一点,如果你想包括准确性,例如,你也可以这样做:

class LossHistory(Callback):
    def on_train_begin(self, logs={}):
        self.losses = []
        self.accuracy= []

    def on_batch_end(self, batch, logs={}):
        self.losses.append(logs.get('loss'))
        self.accuracy.append(logs.get('accuracy'))

然后随后访问它:

loss_history.accuracy