保存并加载keras.callbacks.History

bal*_*n16 6 python generator deep-learning keras

我正在使用Keras训练深度神经网络,并寻找一种方法来保存并稍后加载类型的历史对象keras.callbacks.History.这是设置:

history_model_1 = model_1.fit_generator(train_generator,
                          steps_per_epoch=100,
                          epochs=20,
                          validation_data=validation_generator,
                          validation_steps=50)
Run Code Online (Sandbox Code Playgroud)

history_model_1 是我希望在另一个Python会话期间保存和加载的变量.

Nas*_*Ben 12

history_model_1是一个回调对象.它包含各种数据,不可序列化.

但是,它包含一个字典,其中包含您实际要保存的所有值(参见您的评论):

import json
# Get the dictionary containing each metric and the loss for each epoch
history_dict = history_model_1.history
# Save it under the form of a json file
json.dump(history_dict, open(your_history_path, 'w'))
Run Code Online (Sandbox Code Playgroud)

你现在可以在第50世纪获得损失的价值,如下所示:

print(history_dict['loss'][49])
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助.

  • 它对我说“TypeError:‘float32’类型的对象不是 JSON 可序列化的” (11认同)
  • 您可以添加代码行来重新加载历史记录吗? (3认同)

Dr.*_*ade 10

您可以创建一个类,这样您将拥有相同的结构,并且可以在两种情况下使用相同的代码进行访问。

import pickle
class History_trained_model(object):
    def __init__(self, history, epoch, params):
        self.history = history
        self.epoch = epoch
        self.params = params

with open(savemodel_path+'/history', 'wb') as file:
    model_history= History_trained_model(history.history, history.epoch, history.params)
    pickle.dump(model_history, file, pickle.HIGHEST_PROTOCOL)
Run Code Online (Sandbox Code Playgroud)

然后访问它:

with open(savemodel_path+'/history', 'rb') as file:
    history=pickle.load(file)

print(history.history)
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以使用 Pandas 将历史对象保存为 CSV 文件。

import pandas as pd

pd.DataFrame.from_dict(history_model_1.history).to_csv('history.csv',index=False)
Run Code Online (Sandbox Code Playgroud)

JSON 方法会生成一个TypeError: Object of type 'float32' is not JSON serializable. 这样做的原因是历史字典中对应的值是 NumPy 数组。

  • 这会导致“ValueError:DataFrame 构造函数未正确调用!” (3认同)