Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving just model & weights in Keras (in single file)

I have Python code that generates a deep convolutional neural network using Keras. I'm trying to save the model, but the result is gigantic (100s of MBs). I'd like to pare that down a bit to make something more manageable.

The problem is that model.save() stores (quoting the Keras FAQ):

  • the architecture of the model, allowing to re-create the model
  • the weights of the model
  • the training configuration (loss, optimizer)
  • the state of the optimizer, allowing to resume training exactly where you left off.

If I'm not doing any more training, I think I just need the first two.

I can use model.to_json() to make a JSON string of the architecture and save that off, and model.save_weights() to make a separate file containing the weights. That's about a third the size of the full model.save() result. But I'm wondering if there's some way to store these in a single self-contained file? (Short of outputting two files, zipping them together, and deleting the originals.) Alternatively, maybe there's a way to delete the training configuration and optimizer state when training is complete, so that model.save() doesn't give me something nearly so big?

Thanks.

like image 319
Adam Smith Avatar asked Jan 25 '26 10:01

Adam Smith


1 Answers

The save function of a Model has a parameter exactly for this, called include_optimizer, setting it to false will save the model without including the optimizer state, which should lead to a much smaller HDF5 file:

model.save("something.hdf5", include_optimizer=False)
like image 167
Dr. Snoopy Avatar answered Jan 27 '26 00:01

Dr. Snoopy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!