简体   繁体   中英

keras save the model weights to one file

i have a keras model which save weights of each epoch how can i make to one file

this is the line which saves the mode

and i have 50 epoch i will get 50 weights which i want only 1 save all of them inside one file

>     model.save_weights('checkpoint_epoch_{}.hdf5'.format(k))

any idea what shall i do to save it in one file because i have to convert weights later to tensorflow model

desiered weights

checkpoint.h5

You don't need the weights in one file, you can save the whole model and use the TFLiteConverter to convert your tf.keras model or tf model to lite directly from a .h5 file.

 import tensorflow as tf
 from tf.keras.models import load_model

 model=load_model("model.h5")

 # Convert the model.
 converter = tf.lite.TFLiteConverter.from_keras_model(model)
 tflite_model = converter.convert()

If you have a Keras model built, you can save the model at each epoch while training using a callback called ModelCheckpoint.

A callback is a set of functions to be applied at given stages of the training procedure. You can use callbacks to get a view on internal states and statistics of the model during training. You can pass a list of callbacks (as the keyword argument callbacks) to the .fit() method of the Sequential or Model classes. The relevant methods of the callbacks will then be called at each stage of the training.

from keras.callbacks import ModelCheckpoint


'''
saves the model weights after each epoch
'''
checkpointer = ModelCheckpoint(filepath='model-{epoch:02d}-{val_loss:.2f}.h5', verbose=1)
model.fit(x_train, y_train, batch_size=batchsize, epochs=epochs, verbose=0, validation_data=(X_test, Y_test), callbacks=[checkpointer])

Then the model will be saved with the epoch number and the validation loss in the filename

SO you can save a model and then later load it as described above.

Why do you want to save the weights for each epoch? Usually you save the weights for the epoch that has the lowest validation loss. Then after training is complete you load those weights into your model to make predictions. The Keras callback ModelCheckpoint will do that for you. You can either save just the weights or save the entire model. One thing I do not like about this callback is that it saves the result to a file, then you have to read in the data from the file. If you save the entire model, reloading the model can take a long time. To avoid this I wrote a custom callback which saves the weights with the lowest validation loss into a class variable. Code is here . The variable save_best_weights.best_weights stores the weights in it so then you can use model.set_weights(save_best_weights.best_weights) to make predictions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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