简体   繁体   English

在特定时期保存 Keras 模型

[英]Save Keras model at specific epochs

I am using Keras to do some training on my dataset and it is time consuming to keep running every time to locate the number of epochs needed to get the best results.我正在使用 Keras 对我的数据集进行一些训练,每次保持运行以定位获得最佳结果所需的 epoch 数是非常耗时的。 I tried using callbacks to get the best model, but it just does not work and usually stops too early.我尝试使用回调来获得最佳模型,但它不起作用并且通常过早停止。 Also, saving every N epochs is not an option for me.此外,保存每 N 个时期对我来说不是一个选择。

What I am trying to do is save the model after some specific epochs are done.我想做的是在完成某些特定时期后保存模型。 Let's say for example, after epoch = 150 is over, it will be saved as model.save(model_1.h5) and after epoch = 152 , it will be saved as model.save(model_2.h5) etc... for few specific epochs.比如说,在epoch = 150结束后,它会被保存为model.save(model_1.h5)并且在epoch = 152 ,它会被保存为model.save(model_2.h5)等等......特定的时代。

Is there a way to implement this in Keras ?有没有办法在 Keras 中实现这一点? I already searched for a method but no luck so far.我已经搜索了一种方法,但到目前为止还没有运气。

Thank you for any help/suggestion.感谢您的任何帮助/建议。

Edit编辑
In most cases it's enough to use name formatting suggested by @Toan Tran in his answer.在大多数情况下,使用@Toan Tran 在他的回答中建议的名称格式就足够了。

But if you need some sophisticated logic, you can use a callback , for example但是如果你需要一些复杂的逻辑,你可以使用回调,例如

import keras

class CustomSaver(keras.callbacks.Callback):
    def on_epoch_end(self, epoch, logs={}):
        if epoch == 2:  # or save after some epoch, each k-th epoch etc.
            self.model.save("model_{}.hd5".format(epoch))

on_epoch_end is called at the end of each epoch; on_epoch_end在每个 epoch 结束时调用; epoch is a number of epoch, latter argument is a logs (you can read about other callback methods in docs). epoch是多个纪元,后一个参数是一个日志(您可以在文档中阅读其他回调方法)。 Put the logic into this method (in example it's as simple as possible).将逻辑放入此方法中(在示例中它尽可能简单)。

Create saver object and put it into fit method:创建 saver 对象并将其放入fit方法:

import keras
import numpy as np

inp = keras.layers.Input(shape=(10,))
dense = keras.layers.Dense(10, activation='relu')(inp)
out = keras.layers.Dense(1, activation='sigmoid')(dense)
model = keras.models.Model(inp, out)
model.compile(optimizer="adam", loss="binary_crossentropy",)

# Just a noise data for fast working example
X = np.random.normal(0, 1, (1000, 10))
y = np.random.randint(0, 2, 1000)

# create and use callback:
saver = CustomSaver()
model.fit(X, y, callbacks=[saver], epochs=5)

In the bash :bash

!ls
Out:
model_2.hd5                     

So, it works.所以,它有效。

checkpoint = keras.callbacks.ModelCheckpoint('model{epoch:08d}.h5', period=5) 
model.fit(X_train, Y_train, callbacks=[checkpoint])

Did you try checkpoint?你试过检查点吗? period=5 means model is saved after 5 epoch period=5表示模型在 5 个 epoch 后保存

More details here更多细节在这里

Hope this help :)希望这有帮助:)

Well, I can't comment on posts yet.好吧,我还不能对帖子发表评论。 So, I'm adding on to @Toan Tran 's answer.所以,我要补充@Toan Tran的回答。 With the latest version of Keras, the argument period is deprecated.使用最新版本的 Keras,不推荐使用参数period Instead, we can use save_freq .相反,我们可以使用save_freq

In the following example, the model is saved after every epoch.在以下示例中,模型在每个 epoch 之后保存。

checkpoint = keras.callbacks.ModelCheckpoint(model_save_path+'/checkpoint_{epoch:02d}', save_freq='epoch')
H=model.fit(x=x_train, y=y_train,epochs=epoch_no,verbose=2, callbacks=[checkpoint])

You can find more details from keras documentation .您可以从keras 文档中找到更多详细信息。

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

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