【问题标题】:save and load keras.callbacks.History保存和加载 keras.callbacks.History
【发布时间】:2018-10-02 18:52:18
【问题描述】:

我正在使用 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)

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

【问题讨论】:

  • 为什么要保存并重新加载它?它无法保存,但如果您需要的是例如每个时期的损失值和指标的值,则可能有一些选项......
  • 在我的笔记本电脑上训练模型大约需要 12 小时。我想保存绘制损失函数和精度值所需的数据
  • 谢谢 :-) 我试着回答这个问题

标签: python deep-learning keras generator


【解决方案1】:

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'))

您现在可以像这样访问第 50 个时期的损失值:

print(history_dict['loss'][49])

重新加载

history_dict = json.load(open(your_history_path, 'r'))

我希望这会有所帮助。

【讨论】:

  • 你能添加几行代码来重新加载历史吗?
  • 它对我说 TypeError: Object of type 'float32' is not JSON serializable
  • 不幸的是,这仅在方法 fit 结束(并创建 history_model_1)后才有效,但在计划中保存带有回调本身的此类对象会很有帮助。另外,如果培训被中断,我将如何恢复历史记录,以便在新一轮的培训课程中检查、继续和更新?
【解决方案2】:

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

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)

然后访问它:

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

print(history.history)

【讨论】:

  • 我收到了TypeError: cannot pickle '_thread.RLock' object。也许历史是不可序列化的,因此它失败了?
【解决方案3】:

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

import pandas as pd

pd.DataFrame.from_dict(history_model_1.history).to_csv('history.csv',index=False)

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

【讨论】:

  • 这个结果是ValueError: DataFrame constructor not properly called!
【解决方案4】:

取自 Tobias,使用此更新版本

import pandas as pd

pd.DataFrame.from_dict(history_model_1.history.history).to_csv('history.csv',index=False)

【讨论】:

    猜你喜欢
    • 2019-11-08
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多