Omar Inuwa
Omar Inuwa

Reputation: 47

How to save a TensorFlow model after a certain amount of epochs?

I have a model that train images, I want to know how to save the model after a certain amount of epochs so I have multiple reference points rather that having just one saved model at the end. Also how do I specify the folder or directory on which I would like to save the model? Here's an example, where would I add the new code to save after a number of epochs? (Also side question, would the model save command at the end work? I haven't started training and I don't want to get to the end to find the model is not saving)

model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])
# Adam optimizer
# loss function will be categorical cross entropy
# evaluation metric will be accuracy

step_size_train=train_generator.n//train_generator.batch_size
model.fit_generator(generator=train_generator,
                   steps_per_epoch=step_size_train,
                   epochs=15)

model.save('C:\Users\Omar\Desktop\trainedmodel.h5')

Upvotes: 0

Views: 144

Answers (1)

DapperDuck
DapperDuck

Reputation: 2876

You can use the keras model checkpoint callback. Here is the code:

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

Add this to the fit generator using the following command:

model.fit_generator(generator=train_generator,
                   steps_per_epoch=step_size_train,
                   epochs=15,
                   callbacks=[checkpoint])

Upvotes: 1

Related Questions