Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/Keras - Saving model weights after every N batches

Tags:

keras

I'm new to Python and Keras, and I have successfully built a neural network that saves weight files after every Epoch. However, I want more granularity (I'm visualizing layer weight distributions in time series) and would like to save the weights after every N batches, rather than every epoch.

Does anyone have any suggestions?

like image 290
DepressiveDerp Avatar asked May 05 '17 01:05

DepressiveDerp


People also ask

How do I save weights after each epoch?

To save weights every epoch, you can use something known as callbacks in Keras. checkpoint = ModelCheckpoint(.....) , assign the argument 'period' as 1 which assigns the periodicity of epochs. This should do it.

How do you save a model after every epoch keras?

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.

How do you save model weights in keras?

Save Your Neural Network Model to JSON The weights are saved directly from the model using the save_weights() function and later loaded using the symmetrical load_weights() function.


Video Answer


1 Answers

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

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

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

model.fit(X_train, Y_train, callbacks=[WeightsSaver(5)])
like image 110
grovina Avatar answered Jan 02 '23 21:01

grovina