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?
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.
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.
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.
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)])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With