keras中的History对象

时间:2022-10-26 16:57:21


keras中的​​fit_generator​​​和​​fit​​函数均返回History对象,那么History怎么用呢?事实上History对象已经记录了运行输出。在了解之前,我们甚至自己定义回调函数记录损失和准确率等。

相关keras源码位于​​网址​​:

class History(Callback):
"""Callback that records events into a `History` object.
This callback is automatically applied to
every Keras model. The `History` object
gets returned by the `fit` method of models.
"""

def on_train_begin(self, logs=None):
self.epoch = []
self.history = {}

def on_epoch_end(self, epoch, logs=None):
logs = logs or {}
self.epoch.append(epoch)
for k, v in logs.items():
self.history.setdefault(k, []).append(v)

可以看出History类对象包含两个属性,分别为epoch和history,epoch为训练轮数。

根据compile参数metrics,history包含不同的内容。比如,当某一次​​metrics=['accuracy']​​​时,运行如下部分代码我们可以看出,history字典类型,包含​​val_loss​​​,​​val_acc​​​,​​loss​​​,​​acc​​四个key值。

####省略若干
history = model.fit_generator(
mp.train_flow,
steps_per_epoch=32,
epochs=3,
validation_data=mp.test_flow,
validation_steps=32)
print(history.history)
print(history.epoch)

print(history.history['val_loss'])

{‘val_loss’: [0.4231100323200226, 0.3713115310668945, 0.3836631367206573], ‘val_acc’: [0.815, 0.84, 0.83], ‘loss’: [0.8348453622311354, 0.5010451343324449, 0.4296100065112114], ‘acc’: [0.630859375, 0.7509920634920635, 0.783203125]}
[0, 1, 2]
[0.4231100323200226, 0.3713115310668945, 0.3836631367206573]