[英]How to keep a list of models saved during training (save best only) in Keras?
我正在使用Modelcheckpoint功能根據“僅保存最佳”條件保存模型。
file_name = str(datetime.datetime.now()).split(' ')[0] + f'{model_name}'+ '_{epoch:02d}.hdf5'
checkpoint_main = ModelCheckpoint(filename, monitor='val_acc', verbose=2,
save_best_only=True, save_weights_only=False,
mode='auto', period=1)
由於我使用的是“僅保存最佳”,因此只會保存某些時期。 我想收集實際保存的模型的路徑,並將它們保存到訓練結束時可以訪問的列表。 該列表將通過管道傳輸到其他操作。
我嘗試查看源代碼,但是沒有看到返回列表的“ train_end”示例,因此我不確定在培訓結束時如何返回某些內容。
https://github.com/keras-team/keras/blob/master/keras/callbacks.py#L360
如果您要為每個時期存儲保存的模型的所有路徑,則可以使用Callback
,因為Callback
只是一個python對象,可以收集數據。
例如,它可以在列表中存儲模型的路徑:
import datetime
class SaveEveryEpoch(Callback):
def __init__(self, model_name, *args, **kwargs):
self.model_checkpoint_paths = []
self.model_name = model_name
super().__init__(*args, **kwargs)
def on_epoch_end(self, epoch, logs):
# I suppose here it's a Functional model
print(logs['acc'])
path_to_checkpoint = (
str(datetime.datetime.now()).split(' ')[0]
+ f'_{self.model_name}'
+ f'_{epoch:02d}.hdf5'
)
self.model.save(path_to_checkpoint)
self.model_checkpoint_paths.append(path_to_checkpoint)
__init__
初始化一個空列表並存儲模型基本名稱 on_epoch_end
在每個時期結束時保存模型; 還將模型路徑追加到模型路徑列表中 使用例
from keras.datasets import mnist
from keras.models import Model
from keras.layers import Dense, Input
import numpy as np
(X_tr, y_tr), (X_te, y_te) = mnist.load_data()
X_tr = (X_tr / 255.).reshape((60000, 784))
X_te = (X_te / 255.).reshape((10000, 784))
def binarize_labels(y):
y_bin = np.zeros((len(y), len(np.unique(y))))
y_bin[range(len(y)), y] = 1
return y_bin
y_train_bin, y_test_bin = binarize_labels(y_tr), binarize_labels(y_te)
model = Sequential()
model.add(InputLayer((784,)))
model.add(Dense(784, activation='relu'))
model.add(Dense(256, activation='relu'))
model.add(Dense(10, activation='softmax'))
model = Model(inp, out)
model.compile(loss='categorical_crossentropy', optimizer='adam')
使用檢查點運行模型
checkpoints = SaveEveryEpoch('mnist_model')
history = model.fit(X_tr, y_train_bin, callbacks=[checkpoints], epochs=3)
# ... training progress ...
checkpoints.model_checkpoint_paths
Out:
['2019-02-06_mnist_model_00.hdf5',
'2019-02-06_mnist_model_01.hdf5',
'2019-02-06_mnist_model_02.hdf5']
ls
輸出:
2019-02-06_mnist_model_00.hdf5
2019-02-06_mnist_model_01.hdf5
2019-02-06_mnist_model_02.hdf5
變化
修改on_epoch_end
以創建一些可以按loss
排序的集合,例如( logs
參數包含具有loss
的字典和一個名為acc
的度量(如果提供了某些度量)。 因此,您以后可以選擇損耗/度量值最小的模型:
class SaveEveryEpoch(Callback):
def __init__(self, model_name, *args, **kwargs):
self.model_checkpoints_with_loss = []
self.model_name = model_name
super().__init__(*args, **kwargs)
def on_epoch_end(self, epoch, logs):
# I suppose here it's a Functional model
print(logs['acc'])
path_to_checkpoint = (
str(datetime.datetime.now()).split(' ')[0]
+ f'_{self.model_name}'
+ f'_{epoch:02d}.hdf5'
)
self.model.save(path_to_checkpoint)
self.model_checkpoints_with_loss.append((logs['loss'], path_to_checkpoint))
另外,您可以重載默認回調,例如ModelCheckpoint,以保存所有路徑,不僅是最佳模型,而且我想在這種情況下沒有必要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.