[英]keras: how to save the training history attribute of the history object
在 Keras 中,我们可以将model.fit
的输出返回到历史记录中,如下所示:
history = model.fit(X_train, y_train,
batch_size=batch_size,
nb_epoch=nb_epoch,
validation_data=(X_test, y_test))
现在,如何将 history 对象的 history 属性保存到文件中以供进一步使用(例如,针对 epoch 绘制 acc 或 loss 的图)?
我使用的是以下内容:
with open('/trainHistoryDict', 'wb') as file_pi:
pickle.dump(history.history, file_pi)
通过这种方式,我将历史保存为字典,以防我以后想绘制损失或准确性。
另一种方法来做到这一点:
由于history.history
是一个dict
,您也可以将其转换为pandas
DataFrame
对象,然后可以将其保存以满足您的需要。
一步步:
import pandas as pd
# assuming you stored your model.fit results in a 'history' variable:
history = model.fit(x_train, y_train, epochs=10)
# convert the history.history dict to a pandas DataFrame:
hist_df = pd.DataFrame(history.history)
# save to json:
hist_json_file = 'history.json'
with open(hist_json_file, mode='w') as f:
hist_df.to_json(f)
# or save to csv:
hist_csv_file = 'history.csv'
with open(hist_csv_file, mode='w') as f:
hist_df.to_csv(f)
最简单的方法:
保存:
np.save('my_history.npy',history.history)
加载:
history=np.load('my_history.npy',allow_pickle='TRUE').item()
那么历史就是一本字典,您可以使用键检索所有想要的值。
model
历史可以保存到一个文件中,如下所示
import json
hist = model.fit(X_train, y_train, epochs=5, batch_size=batch_size,validation_split=0.1)
with open('file.json', 'w') as f:
json.dump(hist.history, f)
history
对象有一个history
字段是一个字典,其中包含跨越每个训练时期的不同训练指标。 因此,例如history.history['loss'][99]
将在第 100 个训练时期返回模型的损失。 为了节省,你可以pickle
本字典或简单的保存不同的列出了此字典相应的文件。
我遇到了 keras 列表中的值不是 json 可序列化的问题。 因此,我为我的使用原因编写了这两个方便的函数。
import json,codecs
import numpy as np
def saveHist(path,history):
new_hist = {}
for key in list(history.history.keys()):
new_hist[key]=history.history[key]
if type(history.history[key]) == np.ndarray:
new_hist[key] = history.history[key].tolist()
elif type(history.history[key]) == list:
if type(history.history[key][0]) == np.float64:
new_hist[key] = list(map(float, history.history[key]))
print(new_hist)
with codecs.open(path, 'w', encoding='utf-8') as file:
json.dump(new_hist, file, separators=(',', ':'), sort_keys=True, indent=4)
def loadHist(path):
with codecs.open(path, 'r', encoding='utf-8') as file:
n = json.loads(file.read())
return n
其中 saveHist 只需要获取 json 文件应该保存的路径,以及从 keras fit
或fit_generator
方法返回的历史对象。
我敢肯定有很多方法可以做到这一点,但我摸索着想出了一个我自己的版本。
首先,自定义回调可以在每个 epoch 结束时获取和更新历史记录。 在那里我还有一个回调来保存模型。 这两个都很方便,因为如果您崩溃或关机,您可以在最后一个完成的 epoch 中继续训练。
class LossHistory(Callback):
# https://stackoverflow.com/a/53653154/852795
def on_epoch_end(self, epoch, logs = None):
new_history = {}
for k, v in logs.items(): # compile new history from logs
new_history[k] = [v] # convert values into lists
current_history = loadHist(history_filename) # load history from current training
current_history = appendHist(current_history, new_history) # append the logs
saveHist(history_filename, current_history) # save history from current training
model_checkpoint = ModelCheckpoint(model_filename, verbose = 0, period = 1)
history_checkpoint = LossHistory()
callbacks_list = [model_checkpoint, history_checkpoint]
其次,这里有一些“辅助”功能,可以完全按照他们所说的去做。 这些都是从LossHistory()
回调中调用的。
# https://stackoverflow.com/a/54092401/852795
import json, codecs
def saveHist(path, history):
with codecs.open(path, 'w', encoding='utf-8') as f:
json.dump(history, f, separators=(',', ':'), sort_keys=True, indent=4)
def loadHist(path):
n = {} # set history to empty
if os.path.exists(path): # reload history if it exists
with codecs.open(path, 'r', encoding='utf-8') as f:
n = json.loads(f.read())
return n
def appendHist(h1, h2):
if h1 == {}:
return h2
else:
dest = {}
for key, value in h1.items():
dest[key] = value + h2[key]
return dest
之后,您只需要将history_filename
设置为data/model-history.json
,并将model_filename
设置为data/model.h5
。 确保在训练结束时不会弄乱你的历史的最后一个调整,假设你停止和开始,以及坚持回调,是这样做的:
new_history = model.fit(X_train, y_train,
batch_size = batch_size,
nb_epoch = nb_epoch,
validation_data=(X_test, y_test),
callbacks=callbacks_list)
history = appendHist(history, new_history.history)
无论何时, history = loadHist(history_filename)
都可以获取您的历史记录。
时髦来自 json 和列表,但我无法在不通过迭代转换的情况下使其工作。 无论如何,我知道这很有效,因为我已经研究它好几天了。 https://stackoverflow.com/a/44674337/852795 上的pickle.dump
答案可能更好,但我不知道那是什么。 如果我在这里遗漏了任何内容或者您无法使用它,请告诉我。
在训练过程结束时保存历史记录时,上述答案很有用。 如果您想在训练期间保存历史记录,CSVLogger 回调会很有帮助。
下面的代码以数据表文件log.csv 的形式保存模型权重和历史训练。
model_cb = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path)
history_cb = tf.keras.callbacks.CSVLogger('./log.csv', separator=",", append=False)
history = model.fit(callbacks=[model_cb, history_cb])
您可以将tf.keras.callbacks.History
History 属性保存为.txt形式
with open("./result_model.txt",'w') as f:
for k in history.history.keys():
print(k,file=f)
for i in history.history[k]:
print(i,file=f)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.