简体   繁体   English

有没有一种方法可以将模型保存在tf.keras中的指定纪元?

[英]Is there a way to save a model at a specified epoch in tf.keras?

Using tf.keras.callbacks, I am only able to auto-save a best model by picking one attribute to monitor (typically validation accuracy), but sometimes, I need it to save according to a comparison of validation and training accuracy. 使用tf.keras.callbacks,我只能通过选择一个要监视的属性来自动保存最佳模型(通常是验证准确性),但是有时候,我需要根据验证和训练准确性的比较来保存它。 How can I do this? 我怎样才能做到这一点?

Do tf.keras.history files record the model's weights at every epoch? tf.keras.history文件是否在每个时期都记录了模型的权重? If so, how can I save my model from the history file by specifying the epoch I want? 如果是这样,如何通过指定所需的时期从历史文件中保存模型? That is another possible solution. 那是另一种可能的解决方案。

This is the situation I'm running into: On occasion, my validation accuracy is very high in an early epoch (purely by chance I suppose) while my training accuracy is still far below it. 这是我遇到的情况:有时候,我的验证准确性在早期就很高(我想当然是偶然的),而我的训练准确性仍然远远低于它。 This epoch ends up being the model that is auto-saved. 该时期最终成为自动保存的模型。 It's a crappy model because of its poor training accuracy, but it's the one that got saved because of its high validation accuracy. 这是一个糟糕的模型,因为它的训练准确度很差,但是由于验证准确性很高,所以得到了保存。 If it had saved at a place where the training and validation accuracy meet, it would have been a pretty good model. 如果将其保存在训练和验证准确性相符的地方,那将是一个很好的模型。 So at every epoch, I'd prefer to compare the training accuracy and the validation accuracy, choose the lowest of the two, and decide my best model based on that. 因此,在每个时期,我都希望比较训练的准确性和验证的准确性,选择两者中的最低者,并据此确定最佳模型。 Any suggestions on how to do that? 有什么建议吗?

You can implement a Custom callback like this: 您可以像这样实现Custom回调:

class CustomModelCheckpoint(tf.keras.callbacks.Callback):
    def on_epoch_end(self, epoch, logs=None):
        # logs is a dictionary
        print(f"epoch: {epoch}, train_acc: {logs['acc']}, valid_acc: {logs['val_acc']}")
        if logs['val_acc'] > logs['acc']: # your custom condition
            self.model.save('model.h5', overwrite=True)

cbk = CustomModelCheckpoint()
model.fit(....callbacks=[cbk]...)

Checkout the callback ModelCheckpoint at https://keras.io/callbacks/ https://keras.io/callbacks/上签出回调ModelCheckpoint

You can save the model for each epoch and include the accuracy/val accuracy in the filename (or check the history object afterwards). 您可以为每个时期保存模型,并在文件名中包括准确性/ val准确性(或随后检查历史对象)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM