且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python/Keras-每N批次保存一次模型权重

更新时间:2022-05-23 08:04:59

您可以创建自己的回调( https://keras.io/callbacks/).像这样:

You can create your own callback (https://keras.io/callbacks/). Something like:

from keras.callbacks import Callback

class WeightsSaver(Callback):
    def __init__(self, N):
        self.N = N
        self.batch = 0

    def on_batch_end(self, batch, logs={}):
        if self.batch % self.N == 0:
            name = 'weights%08d.h5' % self.batch
            self.model.save_weights(name)
        self.batch += 1

我使用self.batch而不是所提供的batch参数,因为后一个参数在每个时期都从0重新开始.

I use self.batch instead of the batch argument provided because the later restarts at 0 at each epoch.

然后将其添加到适合您的通话中.例如,要每5个批次节省重量:

Then add it to your fit call. For example, to save weights every 5 batches:

model.fit(X_train, Y_train, callbacks=[WeightsSaver(5)])